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-2012, 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/hash.h"
19 #include "access/transam.h"
20 #include "catalog/pg_type.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/pathnode.h"
24 #include "optimizer/planmain.h"
25 #include "optimizer/tlist.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;
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 Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
85 static Plan *set_indexonlyscan_references(PlannerInfo *root,
88 static Plan *set_subqueryscan_references(PlannerInfo *root,
91 static bool trivial_subqueryscan(SubqueryScan *plan);
92 static Node *fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset);
93 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
94 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
95 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
96 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
97 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
98 static indexed_tlist *build_tlist_index(List *tlist);
99 static Var *search_indexed_tlist_for_var(Var *var,
100 indexed_tlist *itlist,
103 static Var *search_indexed_tlist_for_non_var(Node *node,
104 indexed_tlist *itlist,
106 static Var *search_indexed_tlist_for_sortgroupref(Node *node,
108 indexed_tlist *itlist,
110 static List *fix_join_expr(PlannerInfo *root,
112 indexed_tlist *outer_itlist,
113 indexed_tlist *inner_itlist,
114 Index acceptable_rel, int rtoffset);
115 static Node *fix_join_expr_mutator(Node *node,
116 fix_join_expr_context *context);
117 static Node *fix_upper_expr(PlannerInfo *root,
119 indexed_tlist *subplan_itlist,
122 static Node *fix_upper_expr_mutator(Node *node,
123 fix_upper_expr_context *context);
124 static bool fix_opfuncids_walker(Node *node, void *context);
125 static bool extract_query_dependencies_walker(Node *node,
126 PlannerInfo *context);
129 /*****************************************************************************
133 *****************************************************************************/
136 * set_plan_references
138 * This is the final processing pass of the planner/optimizer. The plan
139 * tree is complete; we just have to adjust some representational details
140 * for the convenience of the executor:
142 * 1. We flatten the various subquery rangetables into a single list, and
143 * zero out RangeTblEntry fields that are not useful to the executor.
145 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
147 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
150 * 4. We compute regproc OIDs for operators (ie, we look up the function
151 * that implements each op).
153 * 5. We create lists of specific objects that the plan depends on.
154 * This will be used by plancache.c to drive invalidation of cached plans.
155 * Relation dependencies are represented by OIDs, and everything else by
156 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
157 * Currently, relations and user-defined functions are the only types of
158 * objects that are explicitly tracked this way.
160 * We also perform one final optimization step, which is to delete
161 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
162 * no qual and a no-op targetlist). The reason for doing this last is that
163 * it can't readily be done before set_plan_references, because it would
164 * break set_upper_references: the Vars in the subquery's top tlist
165 * wouldn't match up with the Vars in the outer plan tree. The SubqueryScan
166 * serves a necessary function as a buffer between outer query and subquery
167 * variable numbering ... but after we've flattened the rangetable this is
168 * no longer a problem, since then there's only one rtindex namespace.
170 * set_plan_references recursively traverses the whole plan tree.
172 * The return value is normally the same Plan node passed in, but can be
173 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
175 * The flattened rangetable entries are appended to root->glob->finalrtable.
176 * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
177 * RT indexes of ModifyTable result relations to root->glob->resultRelations.
178 * Plan dependencies are appended to root->glob->relationOids (for relations)
179 * and root->glob->invalItems (for everything else).
181 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
182 * to process targetlist and qual expressions. We can assume that the Plan
183 * nodes were just built by the planner and are not multiply referenced, but
184 * it's not so safe to assume that for expression tree nodes.
187 set_plan_references(PlannerInfo *root, Plan *plan)
189 PlannerGlobal *glob = root->glob;
190 int rtoffset = list_length(glob->finalrtable);
194 * In the flat rangetable, we zero out substructure pointers that are not
195 * needed by the executor; this reduces the storage space and copying cost
196 * for cached plans. We keep only the alias and eref Alias fields, which
197 * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
198 * which are needed for executor-startup permissions checking and for
199 * trigger event checking.
201 foreach(lc, root->parse->rtable)
203 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
204 RangeTblEntry *newrte;
206 /* flat copy to duplicate all the scalar fields */
207 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
208 memcpy(newrte, rte, sizeof(RangeTblEntry));
210 /* zap unneeded sub-structure */
211 newrte->subquery = NULL;
212 newrte->joinaliasvars = NIL;
213 newrte->funcexpr = NULL;
214 newrte->funccoltypes = NIL;
215 newrte->funccoltypmods = NIL;
216 newrte->funccolcollations = NIL;
217 newrte->values_lists = NIL;
218 newrte->values_collations = NIL;
219 newrte->ctecoltypes = NIL;
220 newrte->ctecoltypmods = NIL;
221 newrte->ctecolcollations = NIL;
223 glob->finalrtable = lappend(glob->finalrtable, newrte);
226 * If it's a plain relation RTE, add the table to relationOids.
228 * We do this even though the RTE might be unreferenced in the plan
229 * tree; this would correspond to cases such as views that were
230 * expanded, child tables that were eliminated by constraint
231 * exclusion, etc. Schema invalidation on such a rel must still force
232 * rebuilding of the plan.
234 * Note we don't bother to avoid duplicate list entries. We could,
235 * but it would probably cost more cycles than it would save.
237 if (newrte->rtekind == RTE_RELATION)
238 glob->relationOids = lappend_oid(glob->relationOids,
243 * Check for RT index overflow; it's very unlikely, but if it did happen,
244 * the executor would get confused by varnos that match the special varno
247 if (IS_SPECIAL_VARNO(list_length(glob->finalrtable)))
249 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
250 errmsg("too many range table entries")));
253 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
255 foreach(lc, root->rowMarks)
257 PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
260 Assert(IsA(rc, PlanRowMark));
262 /* flat copy is enough since all fields are scalars */
263 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
264 memcpy(newrc, rc, sizeof(PlanRowMark));
266 /* adjust indexes ... but *not* the rowmarkId */
267 newrc->rti += rtoffset;
268 newrc->prti += rtoffset;
270 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
273 /* Now fix the Plan tree */
274 return set_plan_refs(root, plan, rtoffset);
278 * set_plan_refs: recurse through the Plan nodes of a single subquery level
281 set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
289 * Plan-type-specific fixes
291 switch (nodeTag(plan))
295 SeqScan *splan = (SeqScan *) plan;
297 splan->scanrelid += rtoffset;
298 splan->plan.targetlist =
299 fix_scan_list(root, splan->plan.targetlist, rtoffset);
301 fix_scan_list(root, splan->plan.qual, rtoffset);
306 IndexScan *splan = (IndexScan *) plan;
308 splan->scan.scanrelid += rtoffset;
309 splan->scan.plan.targetlist =
310 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
311 splan->scan.plan.qual =
312 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
314 fix_scan_list(root, splan->indexqual, rtoffset);
315 splan->indexqualorig =
316 fix_scan_list(root, splan->indexqualorig, rtoffset);
317 splan->indexorderby =
318 fix_scan_list(root, splan->indexorderby, rtoffset);
319 splan->indexorderbyorig =
320 fix_scan_list(root, splan->indexorderbyorig, rtoffset);
323 case T_IndexOnlyScan:
325 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
327 return set_indexonlyscan_references(root, splan, rtoffset);
330 case T_BitmapIndexScan:
332 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
334 splan->scan.scanrelid += rtoffset;
335 /* no need to fix targetlist and qual */
336 Assert(splan->scan.plan.targetlist == NIL);
337 Assert(splan->scan.plan.qual == NIL);
339 fix_scan_list(root, splan->indexqual, rtoffset);
340 splan->indexqualorig =
341 fix_scan_list(root, splan->indexqualorig, rtoffset);
344 case T_BitmapHeapScan:
346 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
348 splan->scan.scanrelid += rtoffset;
349 splan->scan.plan.targetlist =
350 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
351 splan->scan.plan.qual =
352 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
353 splan->bitmapqualorig =
354 fix_scan_list(root, splan->bitmapqualorig, rtoffset);
359 TidScan *splan = (TidScan *) plan;
361 splan->scan.scanrelid += rtoffset;
362 splan->scan.plan.targetlist =
363 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
364 splan->scan.plan.qual =
365 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
367 fix_scan_list(root, splan->tidquals, rtoffset);
371 /* Needs special treatment, see comments below */
372 return set_subqueryscan_references(root,
373 (SubqueryScan *) plan,
377 FunctionScan *splan = (FunctionScan *) plan;
379 splan->scan.scanrelid += rtoffset;
380 splan->scan.plan.targetlist =
381 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
382 splan->scan.plan.qual =
383 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
385 fix_scan_expr(root, splan->funcexpr, rtoffset);
390 ValuesScan *splan = (ValuesScan *) plan;
392 splan->scan.scanrelid += rtoffset;
393 splan->scan.plan.targetlist =
394 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
395 splan->scan.plan.qual =
396 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
397 splan->values_lists =
398 fix_scan_list(root, splan->values_lists, rtoffset);
403 CteScan *splan = (CteScan *) plan;
405 splan->scan.scanrelid += rtoffset;
406 splan->scan.plan.targetlist =
407 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
408 splan->scan.plan.qual =
409 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
412 case T_WorkTableScan:
414 WorkTableScan *splan = (WorkTableScan *) plan;
416 splan->scan.scanrelid += rtoffset;
417 splan->scan.plan.targetlist =
418 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
419 splan->scan.plan.qual =
420 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
425 ForeignScan *splan = (ForeignScan *) plan;
427 splan->scan.scanrelid += rtoffset;
428 splan->scan.plan.targetlist =
429 fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
430 splan->scan.plan.qual =
431 fix_scan_list(root, splan->scan.plan.qual, rtoffset);
438 set_join_references(root, (Join *) plan, rtoffset);
448 * These plan types don't actually bother to evaluate their
449 * targetlists, because they just return their unmodified input
450 * tuples. Even though the targetlist won't be used by the
451 * executor, we fix it up for possible use by EXPLAIN (not to
452 * mention ease of debugging --- wrong varnos are very confusing).
454 set_dummy_tlist_references(plan, rtoffset);
457 * Since these plan types don't check quals either, we should not
458 * find any qual expression attached to them.
460 Assert(plan->qual == NIL);
464 LockRows *splan = (LockRows *) plan;
467 * Like the plan types above, LockRows doesn't evaluate its
468 * tlist or quals. But we have to fix up the RT indexes in
471 set_dummy_tlist_references(plan, rtoffset);
472 Assert(splan->plan.qual == NIL);
474 foreach(l, splan->rowMarks)
476 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
479 rc->prti += rtoffset;
485 Limit *splan = (Limit *) plan;
488 * Like the plan types above, Limit doesn't evaluate its tlist
489 * or quals. It does have live expressions for limit/offset,
490 * however; and those cannot contain subplan variable refs, so
491 * fix_scan_expr works for them.
493 set_dummy_tlist_references(plan, rtoffset);
494 Assert(splan->plan.qual == NIL);
497 fix_scan_expr(root, splan->limitOffset, rtoffset);
499 fix_scan_expr(root, splan->limitCount, rtoffset);
504 set_upper_references(root, plan, rtoffset);
508 WindowAgg *wplan = (WindowAgg *) plan;
510 set_upper_references(root, plan, rtoffset);
513 * Like Limit node limit/offset expressions, WindowAgg has
514 * frame offset expressions, which cannot contain subplan
515 * variable refs, so fix_scan_expr works for them.
518 fix_scan_expr(root, wplan->startOffset, rtoffset);
520 fix_scan_expr(root, wplan->endOffset, rtoffset);
525 Result *splan = (Result *) plan;
528 * Result may or may not have a subplan; if not, it's more
529 * like a scan node than an upper node.
531 if (splan->plan.lefttree != NULL)
532 set_upper_references(root, plan, rtoffset);
535 splan->plan.targetlist =
536 fix_scan_list(root, splan->plan.targetlist, rtoffset);
538 fix_scan_list(root, splan->plan.qual, rtoffset);
540 /* resconstantqual can't contain any subplan variable refs */
541 splan->resconstantqual =
542 fix_scan_expr(root, splan->resconstantqual, rtoffset);
547 ModifyTable *splan = (ModifyTable *) plan;
550 * planner.c already called set_returning_clause_references,
551 * so we should not process either the targetlist or the
554 Assert(splan->plan.qual == NIL);
556 foreach(l, splan->resultRelations)
558 lfirst_int(l) += rtoffset;
560 foreach(l, splan->rowMarks)
562 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
565 rc->prti += rtoffset;
567 foreach(l, splan->plans)
569 lfirst(l) = set_plan_refs(root,
575 * Append this ModifyTable node's final result relation RT
576 * index(es) to the global list for the plan, and set its
577 * resultRelIndex to reflect their starting position in the
580 splan->resultRelIndex = list_length(root->glob->resultRelations);
581 root->glob->resultRelations =
582 list_concat(root->glob->resultRelations,
583 list_copy(splan->resultRelations));
588 Append *splan = (Append *) plan;
591 * Append, like Sort et al, doesn't actually evaluate its
592 * targetlist or check quals.
594 set_dummy_tlist_references(plan, rtoffset);
595 Assert(splan->plan.qual == NIL);
596 foreach(l, splan->appendplans)
598 lfirst(l) = set_plan_refs(root,
606 MergeAppend *splan = (MergeAppend *) plan;
609 * MergeAppend, like Sort et al, doesn't actually evaluate its
610 * targetlist or check quals.
612 set_dummy_tlist_references(plan, rtoffset);
613 Assert(splan->plan.qual == NIL);
614 foreach(l, splan->mergeplans)
616 lfirst(l) = set_plan_refs(root,
622 case T_RecursiveUnion:
623 /* This doesn't evaluate targetlist or check quals either */
624 set_dummy_tlist_references(plan, rtoffset);
625 Assert(plan->qual == NIL);
629 BitmapAnd *splan = (BitmapAnd *) plan;
631 /* BitmapAnd works like Append, but has no tlist */
632 Assert(splan->plan.targetlist == NIL);
633 Assert(splan->plan.qual == NIL);
634 foreach(l, splan->bitmapplans)
636 lfirst(l) = set_plan_refs(root,
644 BitmapOr *splan = (BitmapOr *) plan;
646 /* BitmapOr works like Append, but has no tlist */
647 Assert(splan->plan.targetlist == NIL);
648 Assert(splan->plan.qual == NIL);
649 foreach(l, splan->bitmapplans)
651 lfirst(l) = set_plan_refs(root,
658 elog(ERROR, "unrecognized node type: %d",
659 (int) nodeTag(plan));
664 * Now recurse into child plans, if any
666 * NOTE: it is essential that we recurse into child plans AFTER we set
667 * subplan references in this plan's tlist and quals. If we did the
668 * reference-adjustments bottom-up, then we would fail to match this
669 * plan's var nodes against the already-modified nodes of the children.
671 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
672 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
678 * set_indexonlyscan_references
679 * Do set_plan_references processing on an IndexOnlyScan
681 * This is unlike the handling of a plain IndexScan because we have to
682 * convert Vars referencing the heap into Vars referencing the index.
683 * We can use the fix_upper_expr machinery for that, by working from a
684 * targetlist describing the index columns.
687 set_indexonlyscan_references(PlannerInfo *root,
691 indexed_tlist *index_itlist;
693 index_itlist = build_tlist_index(plan->indextlist);
695 plan->scan.scanrelid += rtoffset;
696 plan->scan.plan.targetlist = (List *)
698 (Node *) plan->scan.plan.targetlist,
702 plan->scan.plan.qual = (List *)
704 (Node *) plan->scan.plan.qual,
708 /* indexqual is already transformed to reference index columns */
709 plan->indexqual = fix_scan_list(root, plan->indexqual, rtoffset);
710 /* indexorderby is already transformed to reference index columns */
711 plan->indexorderby = fix_scan_list(root, plan->indexorderby, rtoffset);
712 /* indextlist must NOT be transformed to reference index columns */
713 plan->indextlist = fix_scan_list(root, plan->indextlist, rtoffset);
717 return (Plan *) plan;
721 * set_subqueryscan_references
722 * Do set_plan_references processing on a SubqueryScan
724 * We try to strip out the SubqueryScan entirely; if we can't, we have
725 * to do the normal processing on it.
728 set_subqueryscan_references(PlannerInfo *root,
735 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
736 rel = find_base_rel(root, plan->scan.scanrelid);
737 Assert(rel->subplan == plan->subplan);
739 /* Recursively process the subplan */
740 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
742 if (trivial_subqueryscan(plan))
745 * We can omit the SubqueryScan node and just pull up the subplan.
750 result = plan->subplan;
752 /* We have to be sure we don't lose any initplans */
753 result->initPlan = list_concat(plan->scan.plan.initPlan,
757 * We also have to transfer the SubqueryScan's result-column names
758 * into the subplan, else columns sent to client will be improperly
759 * labeled if this is the topmost plan level. Copy the "source
760 * column" information too.
762 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
764 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
765 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
767 ctle->resname = ptle->resname;
768 ctle->resorigtbl = ptle->resorigtbl;
769 ctle->resorigcol = ptle->resorigcol;
775 * Keep the SubqueryScan node. We have to do the processing that
776 * set_plan_references would otherwise have done on it. Notice we do
777 * not do set_upper_references() here, because a SubqueryScan will
778 * always have been created with correct references to its subplan's
779 * outputs to begin with.
781 plan->scan.scanrelid += rtoffset;
782 plan->scan.plan.targetlist =
783 fix_scan_list(root, plan->scan.plan.targetlist, rtoffset);
784 plan->scan.plan.qual =
785 fix_scan_list(root, plan->scan.plan.qual, rtoffset);
787 result = (Plan *) plan;
794 * trivial_subqueryscan
795 * Detect whether a SubqueryScan can be deleted from the plan tree.
797 * We can delete it if it has no qual to check and the targetlist just
798 * regurgitates the output of the child plan.
801 trivial_subqueryscan(SubqueryScan *plan)
807 if (plan->scan.plan.qual != NIL)
810 if (list_length(plan->scan.plan.targetlist) !=
811 list_length(plan->subplan->targetlist))
812 return false; /* tlists not same length */
815 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
817 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
818 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
820 if (ptle->resjunk != ctle->resjunk)
821 return false; /* tlist doesn't match junk status */
824 * We accept either a Var referencing the corresponding element of the
825 * subplan tlist, or a Const equaling the subplan element. See
826 * generate_setop_tlist() for motivation.
828 if (ptle->expr && IsA(ptle->expr, Var))
830 Var *var = (Var *) ptle->expr;
832 Assert(var->varno == plan->scan.scanrelid);
833 Assert(var->varlevelsup == 0);
834 if (var->varattno != attrno)
835 return false; /* out of order */
837 else if (ptle->expr && IsA(ptle->expr, Const))
839 if (!equal(ptle->expr, ctle->expr))
855 * fix_scan_expr and friends do this enough times that it's worth having
856 * a bespoke routine instead of using the generic copyObject() function.
861 Var *newvar = (Var *) palloc(sizeof(Var));
869 * Do generic set_plan_references processing on an expression node
871 * This is code that is common to all variants of expression-fixing.
872 * We must look up operator opcode info for OpExpr and related nodes,
873 * add OIDs from regclass Const nodes into root->glob->relationOids, and
874 * add catalog TIDs for user-defined functions into root->glob->invalItems.
876 * We assume it's okay to update opcode info in-place. So this could possibly
877 * scribble on the planner's input data structures, but it's OK.
880 fix_expr_common(PlannerInfo *root, Node *node)
882 /* We assume callers won't call us on a NULL pointer */
883 if (IsA(node, Aggref))
885 record_plan_function_dependency(root,
886 ((Aggref *) node)->aggfnoid);
888 else if (IsA(node, WindowFunc))
890 record_plan_function_dependency(root,
891 ((WindowFunc *) node)->winfnoid);
893 else if (IsA(node, FuncExpr))
895 record_plan_function_dependency(root,
896 ((FuncExpr *) node)->funcid);
898 else if (IsA(node, OpExpr))
900 set_opfuncid((OpExpr *) node);
901 record_plan_function_dependency(root,
902 ((OpExpr *) node)->opfuncid);
904 else if (IsA(node, DistinctExpr))
906 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
907 record_plan_function_dependency(root,
908 ((DistinctExpr *) node)->opfuncid);
910 else if (IsA(node, NullIfExpr))
912 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
913 record_plan_function_dependency(root,
914 ((NullIfExpr *) node)->opfuncid);
916 else if (IsA(node, ScalarArrayOpExpr))
918 set_sa_opfuncid((ScalarArrayOpExpr *) node);
919 record_plan_function_dependency(root,
920 ((ScalarArrayOpExpr *) node)->opfuncid);
922 else if (IsA(node, ArrayCoerceExpr))
924 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
925 record_plan_function_dependency(root,
926 ((ArrayCoerceExpr *) node)->elemfuncid);
928 else if (IsA(node, Const))
930 Const *con = (Const *) node;
932 /* Check for regclass reference */
933 if (ISREGCLASSCONST(con))
934 root->glob->relationOids =
935 lappend_oid(root->glob->relationOids,
936 DatumGetObjectId(con->constvalue));
942 * Do set_plan_references processing on a scan-level expression
944 * This consists of incrementing all Vars' varnos by rtoffset,
945 * looking up operator opcode info for OpExpr and related nodes,
946 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
949 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset)
951 fix_scan_expr_context context;
954 context.rtoffset = rtoffset;
956 if (rtoffset != 0 || root->glob->lastPHId != 0)
958 return fix_scan_expr_mutator(node, &context);
963 * If rtoffset == 0, we don't need to change any Vars, and if there
964 * are no placeholders anywhere we won't need to remove them. Then
965 * it's OK to just scribble on the input node tree instead of copying
966 * (since the only change, filling in any unset opfuncid fields, is
967 * harmless). This saves just enough cycles to be noticeable on
970 (void) fix_scan_expr_walker(node, &context);
976 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
982 Var *var = copyVar((Var *) node);
984 Assert(var->varlevelsup == 0);
987 * We should not see any Vars marked INNER_VAR or OUTER_VAR. But an
988 * indexqual expression could contain INDEX_VAR Vars.
990 Assert(var->varno != INNER_VAR);
991 Assert(var->varno != OUTER_VAR);
992 if (!IS_SPECIAL_VARNO(var->varno))
993 var->varno += context->rtoffset;
994 if (var->varnoold > 0)
995 var->varnoold += context->rtoffset;
998 if (IsA(node, CurrentOfExpr))
1000 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1002 Assert(cexpr->cvarno != INNER_VAR);
1003 Assert(cexpr->cvarno != OUTER_VAR);
1004 if (!IS_SPECIAL_VARNO(cexpr->cvarno))
1005 cexpr->cvarno += context->rtoffset;
1006 return (Node *) cexpr;
1008 if (IsA(node, PlaceHolderVar))
1010 /* At scan level, we should always just evaluate the contained expr */
1011 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1013 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
1015 fix_expr_common(context->root, node);
1016 return expression_tree_mutator(node, fix_scan_expr_mutator,
1021 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
1025 Assert(!IsA(node, PlaceHolderVar));
1026 fix_expr_common(context->root, node);
1027 return expression_tree_walker(node, fix_scan_expr_walker,
1032 * set_join_references
1033 * Modify the target list and quals of a join node to reference its
1034 * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
1035 * attno values to the result domain number of either the corresponding
1036 * outer or inner join tuple item. Also perform opcode lookup for these
1037 * expressions. and add regclass OIDs to root->glob->relationOids.
1040 set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1042 Plan *outer_plan = join->plan.lefttree;
1043 Plan *inner_plan = join->plan.righttree;
1044 indexed_tlist *outer_itlist;
1045 indexed_tlist *inner_itlist;
1047 outer_itlist = build_tlist_index(outer_plan->targetlist);
1048 inner_itlist = build_tlist_index(inner_plan->targetlist);
1050 /* All join plans have tlist, qual, and joinqual */
1051 join->plan.targetlist = fix_join_expr(root,
1052 join->plan.targetlist,
1057 join->plan.qual = fix_join_expr(root,
1063 join->joinqual = fix_join_expr(root,
1070 /* Now do join-type-specific stuff */
1071 if (IsA(join, NestLoop))
1073 NestLoop *nl = (NestLoop *) join;
1076 foreach(lc, nl->nestParams)
1078 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
1080 nlp->paramval = (Var *) fix_upper_expr(root,
1081 (Node *) nlp->paramval,
1085 /* Check we replaced any PlaceHolderVar with simple Var */
1086 if (!(IsA(nlp->paramval, Var) &&
1087 nlp->paramval->varno == OUTER_VAR))
1088 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1091 else if (IsA(join, MergeJoin))
1093 MergeJoin *mj = (MergeJoin *) join;
1095 mj->mergeclauses = fix_join_expr(root,
1102 else if (IsA(join, HashJoin))
1104 HashJoin *hj = (HashJoin *) join;
1106 hj->hashclauses = fix_join_expr(root,
1114 pfree(outer_itlist);
1115 pfree(inner_itlist);
1119 * set_upper_references
1120 * Update the targetlist and quals of an upper-level plan node
1121 * to refer to the tuples returned by its lefttree subplan.
1122 * Also perform opcode lookup for these expressions, and
1123 * add regclass OIDs to root->glob->relationOids.
1125 * This is used for single-input plan types like Agg, Group, Result.
1127 * In most cases, we have to match up individual Vars in the tlist and
1128 * qual expressions with elements of the subplan's tlist (which was
1129 * generated by flatten_tlist() from these selfsame expressions, so it
1130 * should have all the required variables). There is an important exception,
1131 * however: GROUP BY and ORDER BY expressions will have been pushed into the
1132 * subplan tlist unflattened. If these values are also needed in the output
1133 * then we want to reference the subplan tlist element rather than recomputing
1137 set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
1139 Plan *subplan = plan->lefttree;
1140 indexed_tlist *subplan_itlist;
1141 List *output_targetlist;
1144 subplan_itlist = build_tlist_index(subplan->targetlist);
1146 output_targetlist = NIL;
1147 foreach(l, plan->targetlist)
1149 TargetEntry *tle = (TargetEntry *) lfirst(l);
1152 /* If it's a non-Var sort/group item, first try to match by sortref */
1153 if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
1156 search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
1157 tle->ressortgroupref,
1161 newexpr = fix_upper_expr(root,
1168 newexpr = fix_upper_expr(root,
1173 tle = flatCopyTargetEntry(tle);
1174 tle->expr = (Expr *) newexpr;
1175 output_targetlist = lappend(output_targetlist, tle);
1177 plan->targetlist = output_targetlist;
1179 plan->qual = (List *)
1180 fix_upper_expr(root,
1181 (Node *) plan->qual,
1186 pfree(subplan_itlist);
1190 * set_dummy_tlist_references
1191 * Replace the targetlist of an upper-level plan node with a simple
1192 * list of OUTER_VAR references to its child.
1194 * This is used for plan types like Sort and Append that don't evaluate
1195 * their targetlists. Although the executor doesn't care at all what's in
1196 * the tlist, EXPLAIN needs it to be realistic.
1198 * Note: we could almost use set_upper_references() here, but it fails for
1199 * Append for lack of a lefttree subplan. Single-purpose code is faster
1203 set_dummy_tlist_references(Plan *plan, int rtoffset)
1205 List *output_targetlist;
1208 output_targetlist = NIL;
1209 foreach(l, plan->targetlist)
1211 TargetEntry *tle = (TargetEntry *) lfirst(l);
1212 Var *oldvar = (Var *) tle->expr;
1215 newvar = makeVar(OUTER_VAR,
1217 exprType((Node *) oldvar),
1218 exprTypmod((Node *) oldvar),
1219 exprCollation((Node *) oldvar),
1221 if (IsA(oldvar, Var))
1223 newvar->varnoold = oldvar->varno + rtoffset;
1224 newvar->varoattno = oldvar->varattno;
1228 newvar->varnoold = 0; /* wasn't ever a plain Var */
1229 newvar->varoattno = 0;
1232 tle = flatCopyTargetEntry(tle);
1233 tle->expr = (Expr *) newvar;
1234 output_targetlist = lappend(output_targetlist, tle);
1236 plan->targetlist = output_targetlist;
1238 /* We don't touch plan->qual here */
1243 * build_tlist_index --- build an index data structure for a child tlist
1245 * In most cases, subplan tlists will be "flat" tlists with only Vars,
1246 * so we try to optimize that case by extracting information about Vars
1247 * in advance. Matching a parent tlist to a child is still an O(N^2)
1248 * operation, but at least with a much smaller constant factor than plain
1249 * tlist_member() searches.
1251 * The result of this function is an indexed_tlist struct to pass to
1252 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1253 * When done, the indexed_tlist may be freed with a single pfree().
1255 static indexed_tlist *
1256 build_tlist_index(List *tlist)
1258 indexed_tlist *itlist;
1262 /* Create data structure with enough slots for all tlist entries */
1263 itlist = (indexed_tlist *)
1264 palloc(offsetof(indexed_tlist, vars) +
1265 list_length(tlist) * sizeof(tlist_vinfo));
1267 itlist->tlist = tlist;
1268 itlist->has_ph_vars = false;
1269 itlist->has_non_vars = false;
1271 /* Find the Vars and fill in the index array */
1272 vinfo = itlist->vars;
1275 TargetEntry *tle = (TargetEntry *) lfirst(l);
1277 if (tle->expr && IsA(tle->expr, Var))
1279 Var *var = (Var *) tle->expr;
1281 vinfo->varno = var->varno;
1282 vinfo->varattno = var->varattno;
1283 vinfo->resno = tle->resno;
1286 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1287 itlist->has_ph_vars = true;
1289 itlist->has_non_vars = true;
1292 itlist->num_vars = (vinfo - itlist->vars);
1298 * build_tlist_index_other_vars --- build a restricted tlist index
1300 * This is like build_tlist_index, but we only index tlist entries that
1301 * are Vars belonging to some rel other than the one specified. We will set
1302 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1303 * (so nothing other than Vars and PlaceHolderVars can be matched).
1305 static indexed_tlist *
1306 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1308 indexed_tlist *itlist;
1312 /* Create data structure with enough slots for all tlist entries */
1313 itlist = (indexed_tlist *)
1314 palloc(offsetof(indexed_tlist, vars) +
1315 list_length(tlist) * sizeof(tlist_vinfo));
1317 itlist->tlist = tlist;
1318 itlist->has_ph_vars = false;
1319 itlist->has_non_vars = false;
1321 /* Find the desired Vars and fill in the index array */
1322 vinfo = itlist->vars;
1325 TargetEntry *tle = (TargetEntry *) lfirst(l);
1327 if (tle->expr && IsA(tle->expr, Var))
1329 Var *var = (Var *) tle->expr;
1331 if (var->varno != ignore_rel)
1333 vinfo->varno = var->varno;
1334 vinfo->varattno = var->varattno;
1335 vinfo->resno = tle->resno;
1339 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1340 itlist->has_ph_vars = true;
1343 itlist->num_vars = (vinfo - itlist->vars);
1349 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1351 * If a match is found, return a copy of the given Var with suitably
1352 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1353 * Also ensure that varnoold is incremented by rtoffset.
1354 * If no match, return NULL.
1357 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1358 Index newvarno, int rtoffset)
1360 Index varno = var->varno;
1361 AttrNumber varattno = var->varattno;
1365 vinfo = itlist->vars;
1366 i = itlist->num_vars;
1369 if (vinfo->varno == varno && vinfo->varattno == varattno)
1372 Var *newvar = copyVar(var);
1374 newvar->varno = newvarno;
1375 newvar->varattno = vinfo->resno;
1376 if (newvar->varnoold > 0)
1377 newvar->varnoold += rtoffset;
1382 return NULL; /* no match */
1386 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1388 * If a match is found, return a Var constructed to reference the tlist item.
1389 * If no match, return NULL.
1391 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1392 * itlist->has_non_vars
1395 search_indexed_tlist_for_non_var(Node *node,
1396 indexed_tlist *itlist, Index newvarno)
1400 tle = tlist_member(node, itlist->tlist);
1403 /* Found a matching subplan output expression */
1406 newvar = makeVarFromTargetEntry(newvarno, tle);
1407 newvar->varnoold = 0; /* wasn't ever a plain Var */
1408 newvar->varoattno = 0;
1411 return NULL; /* no match */
1415 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
1416 * (which is assumed not to be just a Var)
1418 * If a match is found, return a Var constructed to reference the tlist item.
1419 * If no match, return NULL.
1421 * This is needed to ensure that we select the right subplan TLE in cases
1422 * where there are multiple textually-equal()-but-volatile sort expressions.
1423 * And it's also faster than search_indexed_tlist_for_non_var.
1426 search_indexed_tlist_for_sortgroupref(Node *node,
1428 indexed_tlist *itlist,
1433 foreach(lc, itlist->tlist)
1435 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1437 /* The equal() check should be redundant, but let's be paranoid */
1438 if (tle->ressortgroupref == sortgroupref &&
1439 equal(node, tle->expr))
1441 /* Found a matching subplan output expression */
1444 newvar = makeVarFromTargetEntry(newvarno, tle);
1445 newvar->varnoold = 0; /* wasn't ever a plain Var */
1446 newvar->varoattno = 0;
1450 return NULL; /* no match */
1455 * Create a new set of targetlist entries or join qual clauses by
1456 * changing the varno/varattno values of variables in the clauses
1457 * to reference target list values from the outer and inner join
1458 * relation target lists. Also perform opcode lookup and add
1459 * regclass OIDs to root->glob->relationOids.
1461 * This is used in two different scenarios: a normal join clause, where all
1462 * the Vars in the clause *must* be replaced by OUTER_VAR or INNER_VAR
1463 * references; and a RETURNING clause, which may contain both Vars of the
1464 * target relation and Vars of other relations. In the latter case we want
1465 * to replace the other-relation Vars by OUTER_VAR references, while leaving
1466 * target Vars alone.
1468 * For a normal join, acceptable_rel should be zero so that any failure to
1469 * match a Var will be reported as an error. For the RETURNING case, pass
1470 * inner_itlist = NULL and acceptable_rel = the ID of the target relation.
1472 * 'clauses' is the targetlist or list of join clauses
1473 * 'outer_itlist' is the indexed target list of the outer join relation
1474 * 'inner_itlist' is the indexed target list of the inner join relation,
1476 * 'acceptable_rel' is either zero or the rangetable index of a relation
1477 * whose Vars may appear in the clause without provoking an error
1478 * 'rtoffset': how much to increment varnoold by
1480 * Returns the new expression tree. The original clause structure is
1484 fix_join_expr(PlannerInfo *root,
1486 indexed_tlist *outer_itlist,
1487 indexed_tlist *inner_itlist,
1488 Index acceptable_rel,
1491 fix_join_expr_context context;
1493 context.root = root;
1494 context.outer_itlist = outer_itlist;
1495 context.inner_itlist = inner_itlist;
1496 context.acceptable_rel = acceptable_rel;
1497 context.rtoffset = rtoffset;
1498 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1502 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1510 Var *var = (Var *) node;
1512 /* First look for the var in the input tlists */
1513 newvar = search_indexed_tlist_for_var(var,
1514 context->outer_itlist,
1518 return (Node *) newvar;
1519 if (context->inner_itlist)
1521 newvar = search_indexed_tlist_for_var(var,
1522 context->inner_itlist,
1526 return (Node *) newvar;
1529 /* If it's for acceptable_rel, adjust and return it */
1530 if (var->varno == context->acceptable_rel)
1533 if (var->varnoold > 0)
1534 var->varnoold += context->rtoffset;
1535 return (Node *) var;
1538 /* No referent found for Var */
1539 elog(ERROR, "variable not found in subplan target lists");
1541 if (IsA(node, PlaceHolderVar))
1543 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1545 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1546 if (context->outer_itlist->has_ph_vars)
1548 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1549 context->outer_itlist,
1552 return (Node *) newvar;
1554 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1556 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1557 context->inner_itlist,
1560 return (Node *) newvar;
1563 /* If not supplied by input plans, evaluate the contained expr */
1564 return fix_join_expr_mutator((Node *) phv->phexpr, context);
1566 /* Try matching more complex expressions too, if tlists have any */
1567 if (context->outer_itlist->has_non_vars)
1569 newvar = search_indexed_tlist_for_non_var(node,
1570 context->outer_itlist,
1573 return (Node *) newvar;
1575 if (context->inner_itlist && context->inner_itlist->has_non_vars)
1577 newvar = search_indexed_tlist_for_non_var(node,
1578 context->inner_itlist,
1581 return (Node *) newvar;
1583 fix_expr_common(context->root, node);
1584 return expression_tree_mutator(node,
1585 fix_join_expr_mutator,
1591 * Modifies an expression tree so that all Var nodes reference outputs
1592 * of a subplan. Also performs opcode lookup, and adds regclass OIDs to
1593 * root->glob->relationOids.
1595 * This is used to fix up target and qual expressions of non-join upper-level
1596 * plan nodes, as well as index-only scan nodes.
1598 * An error is raised if no matching var can be found in the subplan tlist
1599 * --- so this routine should only be applied to nodes whose subplans'
1600 * targetlists were generated via flatten_tlist() or some such method.
1602 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1603 * against elements of the subplan tlist, so that we can avoid recomputing
1604 * expressions that were already computed by the subplan. (This is relatively
1605 * expensive, so we don't want to try it in the common case where the
1606 * subplan tlist is just a flattened list of Vars.)
1608 * 'node': the tree to be fixed (a target item or qual)
1609 * 'subplan_itlist': indexed target list for subplan (or index)
1610 * 'newvarno': varno to use for Vars referencing tlist elements
1611 * 'rtoffset': how much to increment varnoold by
1613 * The resulting tree is a copy of the original in which all Var nodes have
1614 * varno = newvarno, varattno = resno of corresponding targetlist element.
1615 * The original tree is not modified.
1618 fix_upper_expr(PlannerInfo *root,
1620 indexed_tlist *subplan_itlist,
1624 fix_upper_expr_context context;
1626 context.root = root;
1627 context.subplan_itlist = subplan_itlist;
1628 context.newvarno = newvarno;
1629 context.rtoffset = rtoffset;
1630 return fix_upper_expr_mutator(node, &context);
1634 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1642 Var *var = (Var *) node;
1644 newvar = search_indexed_tlist_for_var(var,
1645 context->subplan_itlist,
1649 elog(ERROR, "variable not found in subplan target list");
1650 return (Node *) newvar;
1652 if (IsA(node, PlaceHolderVar))
1654 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1656 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1657 if (context->subplan_itlist->has_ph_vars)
1659 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1660 context->subplan_itlist,
1663 return (Node *) newvar;
1665 /* If not supplied by input plan, evaluate the contained expr */
1666 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
1668 /* Try matching more complex expressions too, if tlist has any */
1669 if (context->subplan_itlist->has_non_vars)
1671 newvar = search_indexed_tlist_for_non_var(node,
1672 context->subplan_itlist,
1675 return (Node *) newvar;
1677 fix_expr_common(context->root, node);
1678 return expression_tree_mutator(node,
1679 fix_upper_expr_mutator,
1684 * set_returning_clause_references
1685 * Perform setrefs.c's work on a RETURNING targetlist
1687 * If the query involves more than just the result table, we have to
1688 * adjust any Vars that refer to other tables to reference junk tlist
1689 * entries in the top subplan's targetlist. Vars referencing the result
1690 * table should be left alone, however (the executor will evaluate them
1691 * using the actual heap tuple, after firing triggers if any). In the
1692 * adjusted RETURNING list, result-table Vars will still have their
1693 * original varno, but Vars for other rels will have varno OUTER_VAR.
1695 * We also must perform opcode lookup and add regclass OIDs to
1696 * root->glob->relationOids.
1698 * 'rlist': the RETURNING targetlist to be fixed
1699 * 'topplan': the top subplan node that will be just below the ModifyTable
1700 * node (note it's not yet passed through set_plan_references)
1701 * 'resultRelation': RT index of the associated result relation
1703 * Note: we assume that result relations will have rtoffset zero, that is,
1704 * they are not coming from a subplan.
1707 set_returning_clause_references(PlannerInfo *root,
1710 Index resultRelation)
1712 indexed_tlist *itlist;
1715 * We can perform the desired Var fixup by abusing the fix_join_expr
1716 * machinery that formerly handled inner indexscan fixup. We search the
1717 * top plan's targetlist for Vars of non-result relations, and use
1718 * fix_join_expr to convert RETURNING Vars into references to those tlist
1719 * entries, while leaving result-rel Vars as-is.
1721 * PlaceHolderVars will also be sought in the targetlist, but no
1722 * more-complex expressions will be. Note that it is not possible for a
1723 * PlaceHolderVar to refer to the result relation, since the result is
1724 * never below an outer join. If that case could happen, we'd have to be
1725 * prepared to pick apart the PlaceHolderVar and evaluate its contained
1726 * expression instead.
1728 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
1730 rlist = fix_join_expr(root,
1742 /*****************************************************************************
1743 * OPERATOR REGPROC LOOKUP
1744 *****************************************************************************/
1748 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1749 * The given tree can be anything expression_tree_walker handles.
1751 * The argument is modified in-place. (This is OK since we'd want the
1752 * same change for any node, even if it gets visited more than once due to
1753 * shared structure.)
1756 fix_opfuncids(Node *node)
1758 /* This tree walk requires no special setup, so away we go... */
1759 fix_opfuncids_walker(node, NULL);
1763 fix_opfuncids_walker(Node *node, void *context)
1767 if (IsA(node, OpExpr))
1768 set_opfuncid((OpExpr *) node);
1769 else if (IsA(node, DistinctExpr))
1770 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1771 else if (IsA(node, NullIfExpr))
1772 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1773 else if (IsA(node, ScalarArrayOpExpr))
1774 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1775 return expression_tree_walker(node, fix_opfuncids_walker, context);
1780 * Set the opfuncid (procedure OID) in an OpExpr node,
1781 * if it hasn't been set already.
1783 * Because of struct equivalence, this can also be used for
1784 * DistinctExpr and NullIfExpr nodes.
1787 set_opfuncid(OpExpr *opexpr)
1789 if (opexpr->opfuncid == InvalidOid)
1790 opexpr->opfuncid = get_opcode(opexpr->opno);
1795 * As above, for ScalarArrayOpExpr nodes.
1798 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1800 if (opexpr->opfuncid == InvalidOid)
1801 opexpr->opfuncid = get_opcode(opexpr->opno);
1804 /*****************************************************************************
1805 * QUERY DEPENDENCY MANAGEMENT
1806 *****************************************************************************/
1809 * record_plan_function_dependency
1810 * Mark the current plan as depending on a particular function.
1812 * This is exported so that the function-inlining code can record a
1813 * dependency on a function that it's removed from the plan tree.
1816 record_plan_function_dependency(PlannerInfo *root, Oid funcid)
1819 * For performance reasons, we don't bother to track built-in functions;
1820 * we just assume they'll never change (or at least not in ways that'd
1821 * invalidate plans using them). For this purpose we can consider a
1822 * built-in function to be one with OID less than FirstBootstrapObjectId.
1823 * Note that the OID generator guarantees never to generate such an OID
1824 * after startup, even at OID wraparound.
1826 if (funcid >= (Oid) FirstBootstrapObjectId)
1828 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
1831 * It would work to use any syscache on pg_proc, but the easiest is
1832 * PROCOID since we already have the function's OID at hand. Note
1833 * that plancache.c knows we use PROCOID. Also, we're perhaps
1834 * assuming more than we should about how CatalogCacheComputeHashValue
1835 * computes hash values...
1837 inval_item->cacheId = PROCOID;
1838 inval_item->hashValue =
1839 DatumGetUInt32(DirectFunctionCall1(hashoid,
1840 ObjectIdGetDatum(funcid)));
1842 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
1847 * extract_query_dependencies
1848 * Given a not-yet-planned query or queries (i.e. a Query node or list
1849 * of Query nodes), extract dependencies just as set_plan_references
1852 * This is needed by plancache.c to handle invalidation of cached unplanned
1856 extract_query_dependencies(Node *query,
1857 List **relationOids,
1863 /* Make up dummy planner state so we can use this module's machinery */
1864 MemSet(&glob, 0, sizeof(glob));
1865 glob.type = T_PlannerGlobal;
1866 glob.relationOids = NIL;
1867 glob.invalItems = NIL;
1869 MemSet(&root, 0, sizeof(root));
1870 root.type = T_PlannerInfo;
1873 (void) extract_query_dependencies_walker(query, &root);
1875 *relationOids = glob.relationOids;
1876 *invalItems = glob.invalItems;
1880 extract_query_dependencies_walker(Node *node, PlannerInfo *context)
1884 Assert(!IsA(node, PlaceHolderVar));
1885 /* Extract function dependencies and check for regclass Consts */
1886 fix_expr_common(context, node);
1887 if (IsA(node, Query))
1889 Query *query = (Query *) node;
1892 if (query->commandType == CMD_UTILITY)
1894 /* Ignore utility statements, except EXPLAIN */
1895 if (IsA(query->utilityStmt, ExplainStmt))
1897 query = (Query *) ((ExplainStmt *) query->utilityStmt)->query;
1898 Assert(IsA(query, Query));
1899 Assert(query->commandType != CMD_UTILITY);
1905 /* Collect relation OIDs in this Query's rtable */
1906 foreach(lc, query->rtable)
1908 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
1910 if (rte->rtekind == RTE_RELATION)
1911 context->glob->relationOids =
1912 lappend_oid(context->glob->relationOids, rte->relid);
1915 /* And recurse into the query's subexpressions */
1916 return query_tree_walker(query, extract_query_dependencies_walker,
1917 (void *) context, 0);
1919 return expression_tree_walker(node, extract_query_dependencies_walker,