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-2008, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/backend/optimizer/plan/setrefs.c,v 1.146 2008/10/21 20:42:53 tgl Exp $
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/clauses.h"
23 #include "optimizer/planmain.h"
24 #include "optimizer/tlist.h"
25 #include "parser/parsetree.h"
26 #include "utils/lsyscache.h"
27 #include "utils/syscache.h"
32 Index varno; /* RT index of Var */
33 AttrNumber varattno; /* attr number of Var */
34 AttrNumber resno; /* TLE position of Var */
39 List *tlist; /* underlying target list */
40 int num_vars; /* number of plain Var tlist entries */
41 bool has_ph_vars; /* are there PlaceHolderVar entries? */
42 bool has_non_vars; /* are there other entries? */
43 /* array of num_vars entries: */
44 tlist_vinfo vars[1]; /* VARIABLE LENGTH ARRAY */
45 } indexed_tlist; /* VARIABLE LENGTH STRUCT */
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;
67 } fix_upper_expr_context;
70 * Check if a Const node is a regclass value. We accept plain OID too,
71 * since a regclass Const will get folded to that type if it's an argument
72 * to oideq or similar operators. (This might result in some extraneous
73 * values in a plan's list of relation dependencies, but the worst result
74 * would be occasional useless replans.)
76 #define ISREGCLASSCONST(con) \
77 (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
80 #define fix_scan_list(glob, lst, rtoffset) \
81 ((List *) fix_scan_expr(glob, (Node *) (lst), rtoffset))
83 static Plan *set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset);
84 static Plan *set_subqueryscan_references(PlannerGlobal *glob,
87 static bool trivial_subqueryscan(SubqueryScan *plan);
88 static Node *fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset);
89 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
90 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
91 static void set_join_references(PlannerGlobal *glob, Join *join, int rtoffset);
92 static void set_inner_join_references(PlannerGlobal *glob, Plan *inner_plan,
93 indexed_tlist *outer_itlist);
94 static void set_upper_references(PlannerGlobal *glob, Plan *plan, int rtoffset);
95 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
96 static indexed_tlist *build_tlist_index(List *tlist);
97 static Var *search_indexed_tlist_for_var(Var *var,
98 indexed_tlist *itlist,
101 static Var *search_indexed_tlist_for_non_var(Node *node,
102 indexed_tlist *itlist,
104 static List *fix_join_expr(PlannerGlobal *glob,
106 indexed_tlist *outer_itlist,
107 indexed_tlist *inner_itlist,
108 Index acceptable_rel, int rtoffset);
109 static Node *fix_join_expr_mutator(Node *node,
110 fix_join_expr_context *context);
111 static Node *fix_upper_expr(PlannerGlobal *glob,
113 indexed_tlist *subplan_itlist,
115 static Node *fix_upper_expr_mutator(Node *node,
116 fix_upper_expr_context *context);
117 static bool fix_opfuncids_walker(Node *node, void *context);
118 static bool extract_query_dependencies_walker(Node *node,
119 PlannerGlobal *context);
122 /*****************************************************************************
126 *****************************************************************************/
129 * set_plan_references
131 * This is the final processing pass of the planner/optimizer. The plan
132 * tree is complete; we just have to adjust some representational details
133 * for the convenience of the executor:
135 * 1. We flatten the various subquery rangetables into a single list, and
136 * zero out RangeTblEntry fields that are not useful to the executor.
138 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
140 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
143 * 4. We compute regproc OIDs for operators (ie, we look up the function
144 * that implements each op).
146 * 5. We create lists of specific objects that the plan depends on.
147 * This will be used by plancache.c to drive invalidation of cached plans.
148 * Relation dependencies are represented by OIDs, and everything else by
149 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
150 * Currently, relations and user-defined functions are the only types of
151 * objects that are explicitly tracked this way.
153 * We also perform one final optimization step, which is to delete
154 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
155 * no qual and a no-op targetlist). The reason for doing this last is that
156 * it can't readily be done before set_plan_references, because it would
157 * break set_upper_references: the Vars in the subquery's top tlist
158 * wouldn't match up with the Vars in the outer plan tree. The SubqueryScan
159 * serves a necessary function as a buffer between outer query and subquery
160 * variable numbering ... but after we've flattened the rangetable this is
161 * no longer a problem, since then there's only one rtindex namespace.
163 * set_plan_references recursively traverses the whole plan tree.
166 * glob: global data for planner run
167 * plan: the topmost node of the plan
168 * rtable: the rangetable for the current subquery
170 * The return value is normally the same Plan node passed in, but can be
171 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
173 * The flattened rangetable entries are appended to glob->finalrtable, and
174 * plan dependencies are appended to glob->relationOids (for relations)
175 * and glob->invalItems (for everything else).
177 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
178 * to process targetlist and qual expressions. We can assume that the Plan
179 * nodes were just built by the planner and are not multiply referenced, but
180 * it's not so safe to assume that for expression tree nodes.
183 set_plan_references(PlannerGlobal *glob, Plan *plan, List *rtable)
185 int rtoffset = list_length(glob->finalrtable);
189 * In the flat rangetable, we zero out substructure pointers that are not
190 * needed by the executor; this reduces the storage space and copying cost
191 * for cached plans. We keep only the alias and eref Alias fields, which
192 * are needed by EXPLAIN.
196 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
197 RangeTblEntry *newrte;
199 /* flat copy to duplicate all the scalar fields */
200 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
201 memcpy(newrte, rte, sizeof(RangeTblEntry));
203 /* zap unneeded sub-structure */
204 newrte->subquery = NULL;
205 newrte->joinaliasvars = NIL;
206 newrte->funcexpr = NULL;
207 newrte->funccoltypes = NIL;
208 newrte->funccoltypmods = NIL;
209 newrte->values_lists = NIL;
210 newrte->ctecoltypes = NIL;
211 newrte->ctecoltypmods = NIL;
213 glob->finalrtable = lappend(glob->finalrtable, newrte);
216 * If it's a plain relation RTE, add the table to relationOids.
218 * We do this even though the RTE might be unreferenced in the plan
219 * tree; this would correspond to cases such as views that were
220 * expanded, child tables that were eliminated by constraint
221 * exclusion, etc. Schema invalidation on such a rel must still force
222 * rebuilding of the plan.
224 * Note we don't bother to avoid duplicate list entries. We could,
225 * but it would probably cost more cycles than it would save.
227 if (newrte->rtekind == RTE_RELATION)
228 glob->relationOids = lappend_oid(glob->relationOids,
232 /* Now fix the Plan tree */
233 return set_plan_refs(glob, plan, rtoffset);
237 * set_plan_refs: recurse through the Plan nodes of a single subquery level
240 set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
248 * Plan-type-specific fixes
250 switch (nodeTag(plan))
254 SeqScan *splan = (SeqScan *) plan;
256 splan->scanrelid += rtoffset;
257 splan->plan.targetlist =
258 fix_scan_list(glob, splan->plan.targetlist, rtoffset);
260 fix_scan_list(glob, splan->plan.qual, rtoffset);
265 IndexScan *splan = (IndexScan *) plan;
267 splan->scan.scanrelid += rtoffset;
268 splan->scan.plan.targetlist =
269 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
270 splan->scan.plan.qual =
271 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
273 fix_scan_list(glob, splan->indexqual, rtoffset);
274 splan->indexqualorig =
275 fix_scan_list(glob, splan->indexqualorig, rtoffset);
278 case T_BitmapIndexScan:
280 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
282 splan->scan.scanrelid += rtoffset;
283 /* no need to fix targetlist and qual */
284 Assert(splan->scan.plan.targetlist == NIL);
285 Assert(splan->scan.plan.qual == NIL);
287 fix_scan_list(glob, splan->indexqual, rtoffset);
288 splan->indexqualorig =
289 fix_scan_list(glob, splan->indexqualorig, rtoffset);
292 case T_BitmapHeapScan:
294 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
296 splan->scan.scanrelid += rtoffset;
297 splan->scan.plan.targetlist =
298 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
299 splan->scan.plan.qual =
300 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
301 splan->bitmapqualorig =
302 fix_scan_list(glob, splan->bitmapqualorig, rtoffset);
307 TidScan *splan = (TidScan *) plan;
309 splan->scan.scanrelid += rtoffset;
310 splan->scan.plan.targetlist =
311 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
312 splan->scan.plan.qual =
313 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
315 fix_scan_list(glob, splan->tidquals, rtoffset);
319 /* Needs special treatment, see comments below */
320 return set_subqueryscan_references(glob,
321 (SubqueryScan *) plan,
325 FunctionScan *splan = (FunctionScan *) plan;
327 splan->scan.scanrelid += rtoffset;
328 splan->scan.plan.targetlist =
329 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
330 splan->scan.plan.qual =
331 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
333 fix_scan_expr(glob, splan->funcexpr, rtoffset);
338 ValuesScan *splan = (ValuesScan *) plan;
340 splan->scan.scanrelid += rtoffset;
341 splan->scan.plan.targetlist =
342 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
343 splan->scan.plan.qual =
344 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
345 splan->values_lists =
346 fix_scan_list(glob, splan->values_lists, rtoffset);
351 CteScan *splan = (CteScan *) plan;
353 splan->scan.scanrelid += rtoffset;
354 splan->scan.plan.targetlist =
355 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
356 splan->scan.plan.qual =
357 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
360 case T_WorkTableScan:
362 WorkTableScan *splan = (WorkTableScan *) plan;
364 splan->scan.scanrelid += rtoffset;
365 splan->scan.plan.targetlist =
366 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
367 splan->scan.plan.qual =
368 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
374 set_join_references(glob, (Join *) plan, rtoffset);
384 * These plan types don't actually bother to evaluate their
385 * targetlists, because they just return their unmodified input
386 * tuples. Even though the targetlist won't be used by the
387 * executor, we fix it up for possible use by EXPLAIN (not to
388 * mention ease of debugging --- wrong varnos are very confusing).
390 set_dummy_tlist_references(plan, rtoffset);
393 * Since these plan types don't check quals either, we should not
394 * find any qual expression attached to them.
396 Assert(plan->qual == NIL);
400 Limit *splan = (Limit *) plan;
403 * Like the plan types above, Limit doesn't evaluate its tlist
404 * or quals. It does have live expressions for limit/offset,
405 * however; and those cannot contain subplan variable refs, so
406 * fix_scan_expr works for them.
408 set_dummy_tlist_references(plan, rtoffset);
409 Assert(splan->plan.qual == NIL);
412 fix_scan_expr(glob, splan->limitOffset, rtoffset);
414 fix_scan_expr(glob, splan->limitCount, rtoffset);
419 set_upper_references(glob, plan, rtoffset);
423 Result *splan = (Result *) plan;
426 * Result may or may not have a subplan; if not, it's more
427 * like a scan node than an upper node.
429 if (splan->plan.lefttree != NULL)
430 set_upper_references(glob, plan, rtoffset);
433 splan->plan.targetlist =
434 fix_scan_list(glob, splan->plan.targetlist, rtoffset);
436 fix_scan_list(glob, splan->plan.qual, rtoffset);
438 /* resconstantqual can't contain any subplan variable refs */
439 splan->resconstantqual =
440 fix_scan_expr(glob, splan->resconstantqual, rtoffset);
445 Append *splan = (Append *) plan;
448 * Append, like Sort et al, doesn't actually evaluate its
449 * targetlist or check quals.
451 set_dummy_tlist_references(plan, rtoffset);
452 Assert(splan->plan.qual == NIL);
453 foreach(l, splan->appendplans)
455 lfirst(l) = set_plan_refs(glob,
461 case T_RecursiveUnion:
462 /* This doesn't evaluate targetlist or check quals either */
463 set_dummy_tlist_references(plan, rtoffset);
464 Assert(plan->qual == NIL);
468 BitmapAnd *splan = (BitmapAnd *) plan;
470 /* BitmapAnd works like Append, but has no tlist */
471 Assert(splan->plan.targetlist == NIL);
472 Assert(splan->plan.qual == NIL);
473 foreach(l, splan->bitmapplans)
475 lfirst(l) = set_plan_refs(glob,
483 BitmapOr *splan = (BitmapOr *) plan;
485 /* BitmapOr works like Append, but has no tlist */
486 Assert(splan->plan.targetlist == NIL);
487 Assert(splan->plan.qual == NIL);
488 foreach(l, splan->bitmapplans)
490 lfirst(l) = set_plan_refs(glob,
497 elog(ERROR, "unrecognized node type: %d",
498 (int) nodeTag(plan));
503 * Now recurse into child plans, if any
505 * NOTE: it is essential that we recurse into child plans AFTER we set
506 * subplan references in this plan's tlist and quals. If we did the
507 * reference-adjustments bottom-up, then we would fail to match this
508 * plan's var nodes against the already-modified nodes of the children.
510 plan->lefttree = set_plan_refs(glob, plan->lefttree, rtoffset);
511 plan->righttree = set_plan_refs(glob, plan->righttree, rtoffset);
517 * set_subqueryscan_references
518 * Do set_plan_references processing on a SubqueryScan
520 * We try to strip out the SubqueryScan entirely; if we can't, we have
521 * to do the normal processing on it.
524 set_subqueryscan_references(PlannerGlobal *glob,
530 /* First, recursively process the subplan */
531 plan->subplan = set_plan_references(glob, plan->subplan, plan->subrtable);
533 /* subrtable is no longer needed in the plan tree */
534 plan->subrtable = NIL;
536 if (trivial_subqueryscan(plan))
539 * We can omit the SubqueryScan node and just pull up the subplan.
544 result = plan->subplan;
546 /* We have to be sure we don't lose any initplans */
547 result->initPlan = list_concat(plan->scan.plan.initPlan,
551 * We also have to transfer the SubqueryScan's result-column names
552 * into the subplan, else columns sent to client will be improperly
553 * labeled if this is the topmost plan level. Copy the "source
554 * column" information too.
556 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
558 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
559 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
561 ctle->resname = ptle->resname;
562 ctle->resorigtbl = ptle->resorigtbl;
563 ctle->resorigcol = ptle->resorigcol;
569 * Keep the SubqueryScan node. We have to do the processing that
570 * set_plan_references would otherwise have done on it. Notice we do
571 * not do set_upper_references() here, because a SubqueryScan will
572 * always have been created with correct references to its subplan's
573 * outputs to begin with.
575 plan->scan.scanrelid += rtoffset;
576 plan->scan.plan.targetlist =
577 fix_scan_list(glob, plan->scan.plan.targetlist, rtoffset);
578 plan->scan.plan.qual =
579 fix_scan_list(glob, plan->scan.plan.qual, rtoffset);
581 result = (Plan *) plan;
588 * trivial_subqueryscan
589 * Detect whether a SubqueryScan can be deleted from the plan tree.
591 * We can delete it if it has no qual to check and the targetlist just
592 * regurgitates the output of the child plan.
595 trivial_subqueryscan(SubqueryScan *plan)
601 if (plan->scan.plan.qual != NIL)
604 if (list_length(plan->scan.plan.targetlist) !=
605 list_length(plan->subplan->targetlist))
606 return false; /* tlists not same length */
609 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
611 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
612 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
614 if (ptle->resjunk != ctle->resjunk)
615 return false; /* tlist doesn't match junk status */
618 * We accept either a Var referencing the corresponding element of the
619 * subplan tlist, or a Const equaling the subplan element. See
620 * generate_setop_tlist() for motivation.
622 if (ptle->expr && IsA(ptle->expr, Var))
624 Var *var = (Var *) ptle->expr;
626 Assert(var->varno == plan->scan.scanrelid);
627 Assert(var->varlevelsup == 0);
628 if (var->varattno != attrno)
629 return false; /* out of order */
631 else if (ptle->expr && IsA(ptle->expr, Const))
633 if (!equal(ptle->expr, ctle->expr))
649 * fix_scan_expr and friends do this enough times that it's worth having
650 * a bespoke routine instead of using the generic copyObject() function.
655 Var *newvar = (Var *) palloc(sizeof(Var));
663 * Do generic set_plan_references processing on an expression node
665 * This is code that is common to all variants of expression-fixing.
666 * We must look up operator opcode info for OpExpr and related nodes,
667 * add OIDs from regclass Const nodes into glob->relationOids,
668 * and add catalog TIDs for user-defined functions into glob->invalItems.
670 * We assume it's okay to update opcode info in-place. So this could possibly
671 * scribble on the planner's input data structures, but it's OK.
674 fix_expr_common(PlannerGlobal *glob, Node *node)
676 /* We assume callers won't call us on a NULL pointer */
677 if (IsA(node, Aggref))
679 record_plan_function_dependency(glob,
680 ((Aggref *) node)->aggfnoid);
682 else if (IsA(node, FuncExpr))
684 record_plan_function_dependency(glob,
685 ((FuncExpr *) node)->funcid);
687 else if (IsA(node, OpExpr))
689 set_opfuncid((OpExpr *) node);
690 record_plan_function_dependency(glob,
691 ((OpExpr *) node)->opfuncid);
693 else if (IsA(node, DistinctExpr))
695 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
696 record_plan_function_dependency(glob,
697 ((DistinctExpr *) node)->opfuncid);
699 else if (IsA(node, NullIfExpr))
701 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
702 record_plan_function_dependency(glob,
703 ((NullIfExpr *) node)->opfuncid);
705 else if (IsA(node, ScalarArrayOpExpr))
707 set_sa_opfuncid((ScalarArrayOpExpr *) node);
708 record_plan_function_dependency(glob,
709 ((ScalarArrayOpExpr *) node)->opfuncid);
711 else if (IsA(node, ArrayCoerceExpr))
713 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
714 record_plan_function_dependency(glob,
715 ((ArrayCoerceExpr *) node)->elemfuncid);
717 else if (IsA(node, Const))
719 Const *con = (Const *) node;
721 /* Check for regclass reference */
722 if (ISREGCLASSCONST(con))
724 lappend_oid(glob->relationOids,
725 DatumGetObjectId(con->constvalue));
731 * Do set_plan_references processing on a scan-level expression
733 * This consists of incrementing all Vars' varnos by rtoffset,
734 * looking up operator opcode info for OpExpr and related nodes,
735 * and adding OIDs from regclass Const nodes into glob->relationOids.
738 fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset)
740 fix_scan_expr_context context;
743 context.rtoffset = rtoffset;
745 if (rtoffset != 0 || glob->lastPHId != 0)
747 return fix_scan_expr_mutator(node, &context);
752 * If rtoffset == 0, we don't need to change any Vars, and if there
753 * are no placeholders anywhere we won't need to remove them. Then
754 * it's OK to just scribble on the input node tree instead of copying
755 * (since the only change, filling in any unset opfuncid fields,
756 * is harmless). This saves just enough cycles to be noticeable on
759 (void) fix_scan_expr_walker(node, &context);
765 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
771 Var *var = copyVar((Var *) node);
773 Assert(var->varlevelsup == 0);
776 * We should not see any Vars marked INNER, but in a nestloop inner
777 * scan there could be OUTER Vars. Leave them alone.
779 Assert(var->varno != INNER);
780 if (var->varno > 0 && var->varno != OUTER)
781 var->varno += context->rtoffset;
782 if (var->varnoold > 0)
783 var->varnoold += context->rtoffset;
786 if (IsA(node, CurrentOfExpr))
788 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
790 Assert(cexpr->cvarno != INNER);
791 Assert(cexpr->cvarno != OUTER);
792 cexpr->cvarno += context->rtoffset;
793 return (Node *) cexpr;
795 if (IsA(node, PlaceHolderVar))
797 /* At scan level, we should always just evaluate the contained expr */
798 PlaceHolderVar *phv = (PlaceHolderVar *) node;
800 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
802 fix_expr_common(context->glob, node);
803 return expression_tree_mutator(node, fix_scan_expr_mutator,
808 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
812 Assert(!IsA(node, PlaceHolderVar));
813 fix_expr_common(context->glob, node);
814 return expression_tree_walker(node, fix_scan_expr_walker,
819 * set_join_references
820 * Modify the target list and quals of a join node to reference its
821 * subplans, by setting the varnos to OUTER or INNER and setting attno
822 * values to the result domain number of either the corresponding outer
823 * or inner join tuple item. Also perform opcode lookup for these
824 * expressions. and add regclass OIDs to glob->relationOids.
826 * In the case of a nestloop with inner indexscan, we will also need to
827 * apply the same transformation to any outer vars appearing in the
828 * quals of the child indexscan. set_inner_join_references does that.
831 set_join_references(PlannerGlobal *glob, Join *join, int rtoffset)
833 Plan *outer_plan = join->plan.lefttree;
834 Plan *inner_plan = join->plan.righttree;
835 indexed_tlist *outer_itlist;
836 indexed_tlist *inner_itlist;
838 outer_itlist = build_tlist_index(outer_plan->targetlist);
839 inner_itlist = build_tlist_index(inner_plan->targetlist);
841 /* All join plans have tlist, qual, and joinqual */
842 join->plan.targetlist = fix_join_expr(glob,
843 join->plan.targetlist,
848 join->plan.qual = fix_join_expr(glob,
854 join->joinqual = fix_join_expr(glob,
861 /* Now do join-type-specific stuff */
862 if (IsA(join, NestLoop))
864 /* This processing is split out to handle possible recursion */
865 set_inner_join_references(glob, inner_plan, outer_itlist);
867 else if (IsA(join, MergeJoin))
869 MergeJoin *mj = (MergeJoin *) join;
871 mj->mergeclauses = fix_join_expr(glob,
878 else if (IsA(join, HashJoin))
880 HashJoin *hj = (HashJoin *) join;
882 hj->hashclauses = fix_join_expr(glob,
895 * set_inner_join_references
896 * Handle join references appearing in an inner indexscan's quals
898 * To handle bitmap-scan plan trees, we have to be able to recurse down
899 * to the bottom BitmapIndexScan nodes; likewise, appendrel indexscans
900 * require recursing through Append nodes. This is split out as a separate
901 * function so that it can recurse.
903 * Note we do *not* apply any rtoffset for non-join Vars; this is because
904 * the quals will be processed again by fix_scan_expr when the set_plan_refs
905 * recursion reaches the inner indexscan, and so we'd have done it twice.
908 set_inner_join_references(PlannerGlobal *glob, Plan *inner_plan,
909 indexed_tlist *outer_itlist)
911 if (IsA(inner_plan, IndexScan))
914 * An index is being used to reduce the number of tuples scanned in
915 * the inner relation. If there are join clauses being used with the
916 * index, we must update their outer-rel var nodes to refer to the
917 * outer side of the join.
919 IndexScan *innerscan = (IndexScan *) inner_plan;
920 List *indexqualorig = innerscan->indexqualorig;
922 /* No work needed if indexqual refers only to its own rel... */
923 if (NumRelids((Node *) indexqualorig) > 1)
925 Index innerrel = innerscan->scan.scanrelid;
927 /* only refs to outer vars get changed in the inner qual */
928 innerscan->indexqualorig = fix_join_expr(glob,
934 innerscan->indexqual = fix_join_expr(glob,
935 innerscan->indexqual,
942 * We must fix the inner qpqual too, if it has join clauses (this
943 * could happen if special operators are involved: some indexquals
944 * may get rechecked as qpquals).
946 if (NumRelids((Node *) inner_plan->qual) > 1)
947 inner_plan->qual = fix_join_expr(glob,
955 else if (IsA(inner_plan, BitmapIndexScan))
958 * Same, but index is being used within a bitmap plan.
960 BitmapIndexScan *innerscan = (BitmapIndexScan *) inner_plan;
961 List *indexqualorig = innerscan->indexqualorig;
963 /* No work needed if indexqual refers only to its own rel... */
964 if (NumRelids((Node *) indexqualorig) > 1)
966 Index innerrel = innerscan->scan.scanrelid;
968 /* only refs to outer vars get changed in the inner qual */
969 innerscan->indexqualorig = fix_join_expr(glob,
975 innerscan->indexqual = fix_join_expr(glob,
976 innerscan->indexqual,
981 /* no need to fix inner qpqual */
982 Assert(inner_plan->qual == NIL);
985 else if (IsA(inner_plan, BitmapHeapScan))
988 * The inner side is a bitmap scan plan. Fix the top node, and
989 * recurse to get the lower nodes.
991 * Note: create_bitmap_scan_plan removes clauses from bitmapqualorig
992 * if they are duplicated in qpqual, so must test these independently.
994 BitmapHeapScan *innerscan = (BitmapHeapScan *) inner_plan;
995 Index innerrel = innerscan->scan.scanrelid;
996 List *bitmapqualorig = innerscan->bitmapqualorig;
998 /* only refs to outer vars get changed in the inner qual */
999 if (NumRelids((Node *) bitmapqualorig) > 1)
1000 innerscan->bitmapqualorig = fix_join_expr(glob,
1008 * We must fix the inner qpqual too, if it has join clauses (this
1009 * could happen if special operators are involved: some indexquals may
1010 * get rechecked as qpquals).
1012 if (NumRelids((Node *) inner_plan->qual) > 1)
1013 inner_plan->qual = fix_join_expr(glob,
1021 set_inner_join_references(glob, inner_plan->lefttree, outer_itlist);
1023 else if (IsA(inner_plan, BitmapAnd))
1025 /* All we need do here is recurse */
1026 BitmapAnd *innerscan = (BitmapAnd *) inner_plan;
1029 foreach(l, innerscan->bitmapplans)
1031 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1034 else if (IsA(inner_plan, BitmapOr))
1036 /* All we need do here is recurse */
1037 BitmapOr *innerscan = (BitmapOr *) inner_plan;
1040 foreach(l, innerscan->bitmapplans)
1042 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1045 else if (IsA(inner_plan, TidScan))
1047 TidScan *innerscan = (TidScan *) inner_plan;
1048 Index innerrel = innerscan->scan.scanrelid;
1050 innerscan->tidquals = fix_join_expr(glob,
1051 innerscan->tidquals,
1057 else if (IsA(inner_plan, Append))
1060 * The inner side is an append plan. Recurse to see if it contains
1061 * indexscans that need to be fixed.
1063 Append *appendplan = (Append *) inner_plan;
1066 foreach(l, appendplan->appendplans)
1068 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1071 else if (IsA(inner_plan, Result))
1073 /* Recurse through a gating Result node (similar to Append case) */
1074 Result *result = (Result *) inner_plan;
1076 if (result->plan.lefttree)
1077 set_inner_join_references(glob, result->plan.lefttree, outer_itlist);
1082 * set_upper_references
1083 * Update the targetlist and quals of an upper-level plan node
1084 * to refer to the tuples returned by its lefttree subplan.
1085 * Also perform opcode lookup for these expressions, and
1086 * add regclass OIDs to glob->relationOids.
1088 * This is used for single-input plan types like Agg, Group, Result.
1090 * In most cases, we have to match up individual Vars in the tlist and
1091 * qual expressions with elements of the subplan's tlist (which was
1092 * generated by flatten_tlist() from these selfsame expressions, so it
1093 * should have all the required variables). There is an important exception,
1094 * however: GROUP BY and ORDER BY expressions will have been pushed into the
1095 * subplan tlist unflattened. If these values are also needed in the output
1096 * then we want to reference the subplan tlist element rather than recomputing
1100 set_upper_references(PlannerGlobal *glob, Plan *plan, int rtoffset)
1102 Plan *subplan = plan->lefttree;
1103 indexed_tlist *subplan_itlist;
1104 List *output_targetlist;
1107 subplan_itlist = build_tlist_index(subplan->targetlist);
1109 output_targetlist = NIL;
1110 foreach(l, plan->targetlist)
1112 TargetEntry *tle = (TargetEntry *) lfirst(l);
1115 newexpr = fix_upper_expr(glob,
1119 tle = flatCopyTargetEntry(tle);
1120 tle->expr = (Expr *) newexpr;
1121 output_targetlist = lappend(output_targetlist, tle);
1123 plan->targetlist = output_targetlist;
1125 plan->qual = (List *)
1126 fix_upper_expr(glob,
1127 (Node *) plan->qual,
1131 pfree(subplan_itlist);
1135 * set_dummy_tlist_references
1136 * Replace the targetlist of an upper-level plan node with a simple
1137 * list of OUTER references to its child.
1139 * This is used for plan types like Sort and Append that don't evaluate
1140 * their targetlists. Although the executor doesn't care at all what's in
1141 * the tlist, EXPLAIN needs it to be realistic.
1143 * Note: we could almost use set_upper_references() here, but it fails for
1144 * Append for lack of a lefttree subplan. Single-purpose code is faster
1148 set_dummy_tlist_references(Plan *plan, int rtoffset)
1150 List *output_targetlist;
1153 output_targetlist = NIL;
1154 foreach(l, plan->targetlist)
1156 TargetEntry *tle = (TargetEntry *) lfirst(l);
1157 Var *oldvar = (Var *) tle->expr;
1160 newvar = makeVar(OUTER,
1162 exprType((Node *) oldvar),
1163 exprTypmod((Node *) oldvar),
1165 if (IsA(oldvar, Var))
1167 newvar->varnoold = oldvar->varno + rtoffset;
1168 newvar->varoattno = oldvar->varattno;
1172 newvar->varnoold = 0; /* wasn't ever a plain Var */
1173 newvar->varoattno = 0;
1176 tle = flatCopyTargetEntry(tle);
1177 tle->expr = (Expr *) newvar;
1178 output_targetlist = lappend(output_targetlist, tle);
1180 plan->targetlist = output_targetlist;
1182 /* We don't touch plan->qual here */
1187 * build_tlist_index --- build an index data structure for a child tlist
1189 * In most cases, subplan tlists will be "flat" tlists with only Vars,
1190 * so we try to optimize that case by extracting information about Vars
1191 * in advance. Matching a parent tlist to a child is still an O(N^2)
1192 * operation, but at least with a much smaller constant factor than plain
1193 * tlist_member() searches.
1195 * The result of this function is an indexed_tlist struct to pass to
1196 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1197 * When done, the indexed_tlist may be freed with a single pfree().
1199 static indexed_tlist *
1200 build_tlist_index(List *tlist)
1202 indexed_tlist *itlist;
1206 /* Create data structure with enough slots for all tlist entries */
1207 itlist = (indexed_tlist *)
1208 palloc(offsetof(indexed_tlist, vars) +
1209 list_length(tlist) * sizeof(tlist_vinfo));
1211 itlist->tlist = tlist;
1212 itlist->has_ph_vars = false;
1213 itlist->has_non_vars = false;
1215 /* Find the Vars and fill in the index array */
1216 vinfo = itlist->vars;
1219 TargetEntry *tle = (TargetEntry *) lfirst(l);
1221 if (tle->expr && IsA(tle->expr, Var))
1223 Var *var = (Var *) tle->expr;
1225 vinfo->varno = var->varno;
1226 vinfo->varattno = var->varattno;
1227 vinfo->resno = tle->resno;
1230 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1231 itlist->has_ph_vars = true;
1233 itlist->has_non_vars = true;
1236 itlist->num_vars = (vinfo - itlist->vars);
1242 * build_tlist_index_other_vars --- build a restricted tlist index
1244 * This is like build_tlist_index, but we only index tlist entries that
1245 * are Vars belonging to some rel other than the one specified. We will set
1246 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1247 * (so nothing other than Vars and PlaceHolderVars can be matched).
1249 static indexed_tlist *
1250 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1252 indexed_tlist *itlist;
1256 /* Create data structure with enough slots for all tlist entries */
1257 itlist = (indexed_tlist *)
1258 palloc(offsetof(indexed_tlist, vars) +
1259 list_length(tlist) * sizeof(tlist_vinfo));
1261 itlist->tlist = tlist;
1262 itlist->has_ph_vars = false;
1263 itlist->has_non_vars = false;
1265 /* Find the desired Vars and fill in the index array */
1266 vinfo = itlist->vars;
1269 TargetEntry *tle = (TargetEntry *) lfirst(l);
1271 if (tle->expr && IsA(tle->expr, Var))
1273 Var *var = (Var *) tle->expr;
1275 if (var->varno != ignore_rel)
1277 vinfo->varno = var->varno;
1278 vinfo->varattno = var->varattno;
1279 vinfo->resno = tle->resno;
1283 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1284 itlist->has_ph_vars = true;
1287 itlist->num_vars = (vinfo - itlist->vars);
1293 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1295 * If a match is found, return a copy of the given Var with suitably
1296 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1297 * Also ensure that varnoold is incremented by rtoffset.
1298 * If no match, return NULL.
1301 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1302 Index newvarno, int rtoffset)
1304 Index varno = var->varno;
1305 AttrNumber varattno = var->varattno;
1309 vinfo = itlist->vars;
1310 i = itlist->num_vars;
1313 if (vinfo->varno == varno && vinfo->varattno == varattno)
1316 Var *newvar = copyVar(var);
1318 newvar->varno = newvarno;
1319 newvar->varattno = vinfo->resno;
1320 if (newvar->varnoold > 0)
1321 newvar->varnoold += rtoffset;
1326 return NULL; /* no match */
1330 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1332 * If a match is found, return a Var constructed to reference the tlist item.
1333 * If no match, return NULL.
1335 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1336 * itlist->has_non_vars
1339 search_indexed_tlist_for_non_var(Node *node,
1340 indexed_tlist *itlist, Index newvarno)
1344 tle = tlist_member(node, itlist->tlist);
1347 /* Found a matching subplan output expression */
1350 newvar = makeVar(newvarno,
1352 exprType((Node *) tle->expr),
1353 exprTypmod((Node *) tle->expr),
1355 newvar->varnoold = 0; /* wasn't ever a plain Var */
1356 newvar->varoattno = 0;
1359 return NULL; /* no match */
1364 * Create a new set of targetlist entries or join qual clauses by
1365 * changing the varno/varattno values of variables in the clauses
1366 * to reference target list values from the outer and inner join
1367 * relation target lists. Also perform opcode lookup and add
1368 * regclass OIDs to glob->relationOids.
1370 * This is used in two different scenarios: a normal join clause, where
1371 * all the Vars in the clause *must* be replaced by OUTER or INNER references;
1372 * and an indexscan being used on the inner side of a nestloop join.
1373 * In the latter case we want to replace the outer-relation Vars by OUTER
1374 * references, while Vars of the inner relation should be adjusted by rtoffset.
1375 * (We also implement RETURNING clause fixup using this second scenario.)
1377 * For a normal join, acceptable_rel should be zero so that any failure to
1378 * match a Var will be reported as an error. For the indexscan case,
1379 * pass inner_itlist = NULL and acceptable_rel = the (not-offseted-yet) ID
1380 * of the inner relation.
1382 * 'clauses' is the targetlist or list of join clauses
1383 * 'outer_itlist' is the indexed target list of the outer join relation
1384 * 'inner_itlist' is the indexed target list of the inner join relation,
1386 * 'acceptable_rel' is either zero or the rangetable index of a relation
1387 * whose Vars may appear in the clause without provoking an error.
1388 * 'rtoffset' is what to add to varno for Vars of acceptable_rel.
1390 * Returns the new expression tree. The original clause structure is
1394 fix_join_expr(PlannerGlobal *glob,
1396 indexed_tlist *outer_itlist,
1397 indexed_tlist *inner_itlist,
1398 Index acceptable_rel,
1401 fix_join_expr_context context;
1403 context.glob = glob;
1404 context.outer_itlist = outer_itlist;
1405 context.inner_itlist = inner_itlist;
1406 context.acceptable_rel = acceptable_rel;
1407 context.rtoffset = rtoffset;
1408 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1412 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1420 Var *var = (Var *) node;
1422 /* First look for the var in the input tlists */
1423 newvar = search_indexed_tlist_for_var(var,
1424 context->outer_itlist,
1428 return (Node *) newvar;
1429 if (context->inner_itlist)
1431 newvar = search_indexed_tlist_for_var(var,
1432 context->inner_itlist,
1436 return (Node *) newvar;
1439 /* If it's for acceptable_rel, adjust and return it */
1440 if (var->varno == context->acceptable_rel)
1443 var->varno += context->rtoffset;
1444 var->varnoold += context->rtoffset;
1445 return (Node *) var;
1448 /* No referent found for Var */
1449 elog(ERROR, "variable not found in subplan target lists");
1451 if (IsA(node, PlaceHolderVar))
1453 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1455 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1456 if (context->outer_itlist->has_ph_vars)
1458 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1459 context->outer_itlist,
1462 return (Node *) newvar;
1464 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1466 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1467 context->inner_itlist,
1470 return (Node *) newvar;
1473 /* If not supplied by input plans, evaluate the contained expr */
1474 return fix_join_expr_mutator((Node *) phv->phexpr, context);
1476 /* Try matching more complex expressions too, if tlists have any */
1477 if (context->outer_itlist->has_non_vars)
1479 newvar = search_indexed_tlist_for_non_var(node,
1480 context->outer_itlist,
1483 return (Node *) newvar;
1485 if (context->inner_itlist && context->inner_itlist->has_non_vars)
1487 newvar = search_indexed_tlist_for_non_var(node,
1488 context->inner_itlist,
1491 return (Node *) newvar;
1493 fix_expr_common(context->glob, node);
1494 return expression_tree_mutator(node,
1495 fix_join_expr_mutator,
1501 * Modifies an expression tree so that all Var nodes reference outputs
1502 * of a subplan. Also performs opcode lookup, and adds regclass OIDs to
1503 * glob->relationOids.
1505 * This is used to fix up target and qual expressions of non-join upper-level
1508 * An error is raised if no matching var can be found in the subplan tlist
1509 * --- so this routine should only be applied to nodes whose subplans'
1510 * targetlists were generated via flatten_tlist() or some such method.
1512 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1513 * against elements of the subplan tlist, so that we can avoid recomputing
1514 * expressions that were already computed by the subplan. (This is relatively
1515 * expensive, so we don't want to try it in the common case where the
1516 * subplan tlist is just a flattened list of Vars.)
1518 * 'node': the tree to be fixed (a target item or qual)
1519 * 'subplan_itlist': indexed target list for subplan
1520 * 'rtoffset': how much to increment varnoold by
1522 * The resulting tree is a copy of the original in which all Var nodes have
1523 * varno = OUTER, varattno = resno of corresponding subplan target.
1524 * The original tree is not modified.
1527 fix_upper_expr(PlannerGlobal *glob,
1529 indexed_tlist *subplan_itlist,
1532 fix_upper_expr_context context;
1534 context.glob = glob;
1535 context.subplan_itlist = subplan_itlist;
1536 context.rtoffset = rtoffset;
1537 return fix_upper_expr_mutator(node, &context);
1541 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1549 Var *var = (Var *) node;
1551 newvar = search_indexed_tlist_for_var(var,
1552 context->subplan_itlist,
1556 elog(ERROR, "variable not found in subplan target list");
1557 return (Node *) newvar;
1559 if (IsA(node, PlaceHolderVar))
1561 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1563 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1564 if (context->subplan_itlist->has_ph_vars)
1566 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1567 context->subplan_itlist,
1570 return (Node *) newvar;
1572 /* If not supplied by input plan, evaluate the contained expr */
1573 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
1575 /* Try matching more complex expressions too, if tlist has any */
1576 if (context->subplan_itlist->has_non_vars)
1578 newvar = search_indexed_tlist_for_non_var(node,
1579 context->subplan_itlist,
1582 return (Node *) newvar;
1584 fix_expr_common(context->glob, node);
1585 return expression_tree_mutator(node,
1586 fix_upper_expr_mutator,
1591 * set_returning_clause_references
1592 * Perform setrefs.c's work on a RETURNING targetlist
1594 * If the query involves more than just the result table, we have to
1595 * adjust any Vars that refer to other tables to reference junk tlist
1596 * entries in the top plan's targetlist. Vars referencing the result
1597 * table should be left alone, however (the executor will evaluate them
1598 * using the actual heap tuple, after firing triggers if any). In the
1599 * adjusted RETURNING list, result-table Vars will still have their
1600 * original varno, but Vars for other rels will have varno OUTER.
1602 * We also must perform opcode lookup and add regclass OIDs to
1603 * glob->relationOids.
1605 * 'rlist': the RETURNING targetlist to be fixed
1606 * 'topplan': the top Plan node for the query (not yet passed through
1607 * set_plan_references)
1608 * 'resultRelation': RT index of the associated result relation
1610 * Note: we assume that result relations will have rtoffset zero, that is,
1611 * they are not coming from a subplan.
1614 set_returning_clause_references(PlannerGlobal *glob,
1617 Index resultRelation)
1619 indexed_tlist *itlist;
1622 * We can perform the desired Var fixup by abusing the fix_join_expr
1623 * machinery that normally handles inner indexscan fixup. We search the
1624 * top plan's targetlist for Vars of non-result relations, and use
1625 * fix_join_expr to convert RETURNING Vars into references to those tlist
1626 * entries, while leaving result-rel Vars as-is.
1628 * PlaceHolderVars will also be sought in the targetlist, but no
1629 * more-complex expressions will be. Note that it is not possible for
1630 * a PlaceHolderVar to refer to the result relation, since the result
1631 * is never below an outer join. If that case could happen, we'd have
1632 * to be prepared to pick apart the PlaceHolderVar and evaluate its
1633 * contained expression instead.
1635 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
1637 rlist = fix_join_expr(glob,
1649 /*****************************************************************************
1650 * OPERATOR REGPROC LOOKUP
1651 *****************************************************************************/
1655 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1656 * The given tree can be anything expression_tree_walker handles.
1658 * The argument is modified in-place. (This is OK since we'd want the
1659 * same change for any node, even if it gets visited more than once due to
1660 * shared structure.)
1663 fix_opfuncids(Node *node)
1665 /* This tree walk requires no special setup, so away we go... */
1666 fix_opfuncids_walker(node, NULL);
1670 fix_opfuncids_walker(Node *node, void *context)
1674 if (IsA(node, OpExpr))
1675 set_opfuncid((OpExpr *) node);
1676 else if (IsA(node, DistinctExpr))
1677 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1678 else if (IsA(node, NullIfExpr))
1679 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1680 else if (IsA(node, ScalarArrayOpExpr))
1681 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1682 return expression_tree_walker(node, fix_opfuncids_walker, context);
1687 * Set the opfuncid (procedure OID) in an OpExpr node,
1688 * if it hasn't been set already.
1690 * Because of struct equivalence, this can also be used for
1691 * DistinctExpr and NullIfExpr nodes.
1694 set_opfuncid(OpExpr *opexpr)
1696 if (opexpr->opfuncid == InvalidOid)
1697 opexpr->opfuncid = get_opcode(opexpr->opno);
1702 * As above, for ScalarArrayOpExpr nodes.
1705 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1707 if (opexpr->opfuncid == InvalidOid)
1708 opexpr->opfuncid = get_opcode(opexpr->opno);
1711 /*****************************************************************************
1712 * QUERY DEPENDENCY MANAGEMENT
1713 *****************************************************************************/
1716 * record_plan_function_dependency
1717 * Mark the current plan as depending on a particular function.
1719 * This is exported so that the function-inlining code can record a
1720 * dependency on a function that it's removed from the plan tree.
1723 record_plan_function_dependency(PlannerGlobal *glob, Oid funcid)
1726 * For performance reasons, we don't bother to track built-in functions;
1727 * we just assume they'll never change (or at least not in ways that'd
1728 * invalidate plans using them). For this purpose we can consider a
1729 * built-in function to be one with OID less than FirstBootstrapObjectId.
1730 * Note that the OID generator guarantees never to generate such an
1731 * OID after startup, even at OID wraparound.
1733 if (funcid >= (Oid) FirstBootstrapObjectId)
1735 HeapTuple func_tuple;
1736 PlanInvalItem *inval_item;
1738 func_tuple = SearchSysCache(PROCOID,
1739 ObjectIdGetDatum(funcid),
1741 if (!HeapTupleIsValid(func_tuple))
1742 elog(ERROR, "cache lookup failed for function %u", funcid);
1744 inval_item = makeNode(PlanInvalItem);
1747 * It would work to use any syscache on pg_proc, but plancache.c
1748 * expects us to use PROCOID.
1750 inval_item->cacheId = PROCOID;
1751 inval_item->tupleId = func_tuple->t_self;
1753 glob->invalItems = lappend(glob->invalItems, inval_item);
1755 ReleaseSysCache(func_tuple);
1760 * extract_query_dependencies
1761 * Given a list of not-yet-planned queries (i.e. Query nodes),
1762 * extract their dependencies just as set_plan_references would do.
1764 * This is needed by plancache.c to handle invalidation of cached unplanned
1768 extract_query_dependencies(List *queries,
1769 List **relationOids,
1774 /* Make up a dummy PlannerGlobal so we can use this module's machinery */
1775 MemSet(&glob, 0, sizeof(glob));
1776 glob.type = T_PlannerGlobal;
1777 glob.relationOids = NIL;
1778 glob.invalItems = NIL;
1780 (void) extract_query_dependencies_walker((Node *) queries, &glob);
1782 *relationOids = glob.relationOids;
1783 *invalItems = glob.invalItems;
1787 extract_query_dependencies_walker(Node *node, PlannerGlobal *context)
1791 Assert(!IsA(node, PlaceHolderVar));
1792 /* Extract function dependencies and check for regclass Consts */
1793 fix_expr_common(context, node);
1794 if (IsA(node, Query))
1796 Query *query = (Query *) node;
1799 /* Collect relation OIDs in this Query's rtable */
1800 foreach(lc, query->rtable)
1802 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
1804 if (rte->rtekind == RTE_RELATION)
1805 context->relationOids = lappend_oid(context->relationOids,
1809 /* And recurse into the query's subexpressions */
1810 return query_tree_walker(query, extract_query_dependencies_walker,
1811 (void *) context, 0);
1813 return expression_tree_walker(node, extract_query_dependencies_walker,