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-2010, 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.157 2010/01/15 22:36:32 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 Var *search_indexed_tlist_for_sortgroupref(Node *node,
106 indexed_tlist *itlist,
108 static List *fix_join_expr(PlannerGlobal *glob,
110 indexed_tlist *outer_itlist,
111 indexed_tlist *inner_itlist,
112 Index acceptable_rel, int rtoffset);
113 static Node *fix_join_expr_mutator(Node *node,
114 fix_join_expr_context *context);
115 static Node *fix_upper_expr(PlannerGlobal *glob,
117 indexed_tlist *subplan_itlist,
119 static Node *fix_upper_expr_mutator(Node *node,
120 fix_upper_expr_context *context);
121 static bool fix_opfuncids_walker(Node *node, void *context);
122 static bool extract_query_dependencies_walker(Node *node,
123 PlannerGlobal *context);
126 /*****************************************************************************
130 *****************************************************************************/
133 * set_plan_references
135 * This is the final processing pass of the planner/optimizer. The plan
136 * tree is complete; we just have to adjust some representational details
137 * for the convenience of the executor:
139 * 1. We flatten the various subquery rangetables into a single list, and
140 * zero out RangeTblEntry fields that are not useful to the executor.
142 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
144 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
147 * 4. We compute regproc OIDs for operators (ie, we look up the function
148 * that implements each op).
150 * 5. We create lists of specific objects that the plan depends on.
151 * This will be used by plancache.c to drive invalidation of cached plans.
152 * Relation dependencies are represented by OIDs, and everything else by
153 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
154 * Currently, relations and user-defined functions are the only types of
155 * objects that are explicitly tracked this way.
157 * We also perform one final optimization step, which is to delete
158 * SubqueryScan plan nodes that aren't doing anything useful (ie, have
159 * no qual and a no-op targetlist). The reason for doing this last is that
160 * it can't readily be done before set_plan_references, because it would
161 * break set_upper_references: the Vars in the subquery's top tlist
162 * wouldn't match up with the Vars in the outer plan tree. The SubqueryScan
163 * serves a necessary function as a buffer between outer query and subquery
164 * variable numbering ... but after we've flattened the rangetable this is
165 * no longer a problem, since then there's only one rtindex namespace.
167 * set_plan_references recursively traverses the whole plan tree.
170 * glob: global data for planner run
171 * plan: the topmost node of the plan
172 * rtable: the rangetable for the current subquery
173 * rowmarks: the PlanRowMark list for the current subquery
175 * The return value is normally the same Plan node passed in, but can be
176 * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
178 * The flattened rangetable entries are appended to glob->finalrtable,
179 * and we also append rowmarks entries to glob->finalrowmarks.
180 * Plan dependencies are appended to glob->relationOids (for relations)
181 * and glob->invalItems (for everything else).
183 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
184 * to process targetlist and qual expressions. We can assume that the Plan
185 * nodes were just built by the planner and are not multiply referenced, but
186 * it's not so safe to assume that for expression tree nodes.
189 set_plan_references(PlannerGlobal *glob, Plan *plan,
190 List *rtable, List *rowmarks)
192 int rtoffset = list_length(glob->finalrtable);
196 * In the flat rangetable, we zero out substructure pointers that are not
197 * needed by the executor; this reduces the storage space and copying cost
198 * for cached plans. We keep only the alias and eref Alias fields, which
199 * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
200 * which are needed for executor-startup permissions checking and for
201 * trigger event checking.
205 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
206 RangeTblEntry *newrte;
208 /* flat copy to duplicate all the scalar fields */
209 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
210 memcpy(newrte, rte, sizeof(RangeTblEntry));
212 /* zap unneeded sub-structure */
213 newrte->subquery = NULL;
214 newrte->joinaliasvars = NIL;
215 newrte->funcexpr = NULL;
216 newrte->funccoltypes = NIL;
217 newrte->funccoltypmods = NIL;
218 newrte->values_lists = NIL;
219 newrte->ctecoltypes = NIL;
220 newrte->ctecoltypmods = NIL;
222 glob->finalrtable = lappend(glob->finalrtable, newrte);
225 * If it's a plain relation RTE, add the table to relationOids.
227 * We do this even though the RTE might be unreferenced in the plan
228 * tree; this would correspond to cases such as views that were
229 * expanded, child tables that were eliminated by constraint
230 * exclusion, etc. Schema invalidation on such a rel must still force
231 * rebuilding of the plan.
233 * Note we don't bother to avoid duplicate list entries. We could,
234 * but it would probably cost more cycles than it would save.
236 if (newrte->rtekind == RTE_RELATION)
237 glob->relationOids = lappend_oid(glob->relationOids,
242 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
244 foreach(lc, rowmarks)
246 PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
249 Assert(IsA(rc, PlanRowMark));
251 /* flat copy is enough since all fields are scalars */
252 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
253 memcpy(newrc, rc, sizeof(PlanRowMark));
256 newrc->rti += rtoffset;
257 newrc->prti += rtoffset;
259 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
262 /* Now fix the Plan tree */
263 return set_plan_refs(glob, plan, rtoffset);
267 * set_plan_refs: recurse through the Plan nodes of a single subquery level
270 set_plan_refs(PlannerGlobal *glob, Plan *plan, int rtoffset)
278 * Plan-type-specific fixes
280 switch (nodeTag(plan))
284 SeqScan *splan = (SeqScan *) plan;
286 splan->scanrelid += rtoffset;
287 splan->plan.targetlist =
288 fix_scan_list(glob, splan->plan.targetlist, rtoffset);
290 fix_scan_list(glob, splan->plan.qual, rtoffset);
295 IndexScan *splan = (IndexScan *) plan;
297 splan->scan.scanrelid += rtoffset;
298 splan->scan.plan.targetlist =
299 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
300 splan->scan.plan.qual =
301 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
303 fix_scan_list(glob, splan->indexqual, rtoffset);
304 splan->indexqualorig =
305 fix_scan_list(glob, splan->indexqualorig, rtoffset);
308 case T_BitmapIndexScan:
310 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
312 splan->scan.scanrelid += rtoffset;
313 /* no need to fix targetlist and qual */
314 Assert(splan->scan.plan.targetlist == NIL);
315 Assert(splan->scan.plan.qual == NIL);
317 fix_scan_list(glob, splan->indexqual, rtoffset);
318 splan->indexqualorig =
319 fix_scan_list(glob, splan->indexqualorig, rtoffset);
322 case T_BitmapHeapScan:
324 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
326 splan->scan.scanrelid += rtoffset;
327 splan->scan.plan.targetlist =
328 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
329 splan->scan.plan.qual =
330 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
331 splan->bitmapqualorig =
332 fix_scan_list(glob, splan->bitmapqualorig, rtoffset);
337 TidScan *splan = (TidScan *) plan;
339 splan->scan.scanrelid += rtoffset;
340 splan->scan.plan.targetlist =
341 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
342 splan->scan.plan.qual =
343 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
345 fix_scan_list(glob, splan->tidquals, rtoffset);
349 /* Needs special treatment, see comments below */
350 return set_subqueryscan_references(glob,
351 (SubqueryScan *) plan,
355 FunctionScan *splan = (FunctionScan *) plan;
357 splan->scan.scanrelid += rtoffset;
358 splan->scan.plan.targetlist =
359 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
360 splan->scan.plan.qual =
361 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
363 fix_scan_expr(glob, splan->funcexpr, rtoffset);
368 ValuesScan *splan = (ValuesScan *) plan;
370 splan->scan.scanrelid += rtoffset;
371 splan->scan.plan.targetlist =
372 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
373 splan->scan.plan.qual =
374 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
375 splan->values_lists =
376 fix_scan_list(glob, splan->values_lists, rtoffset);
381 CteScan *splan = (CteScan *) plan;
383 splan->scan.scanrelid += rtoffset;
384 splan->scan.plan.targetlist =
385 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
386 splan->scan.plan.qual =
387 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
390 case T_WorkTableScan:
392 WorkTableScan *splan = (WorkTableScan *) plan;
394 splan->scan.scanrelid += rtoffset;
395 splan->scan.plan.targetlist =
396 fix_scan_list(glob, splan->scan.plan.targetlist, rtoffset);
397 splan->scan.plan.qual =
398 fix_scan_list(glob, splan->scan.plan.qual, rtoffset);
404 set_join_references(glob, (Join *) plan, rtoffset);
414 * These plan types don't actually bother to evaluate their
415 * targetlists, because they just return their unmodified input
416 * tuples. Even though the targetlist won't be used by the
417 * executor, we fix it up for possible use by EXPLAIN (not to
418 * mention ease of debugging --- wrong varnos are very confusing).
420 set_dummy_tlist_references(plan, rtoffset);
423 * Since these plan types don't check quals either, we should not
424 * find any qual expression attached to them.
426 Assert(plan->qual == NIL);
430 LockRows *splan = (LockRows *) plan;
433 * Like the plan types above, LockRows doesn't evaluate its
434 * tlist or quals. But we have to fix up the RT indexes
437 set_dummy_tlist_references(plan, rtoffset);
438 Assert(splan->plan.qual == NIL);
440 foreach(l, splan->rowMarks)
442 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
445 rc->prti += rtoffset;
451 Limit *splan = (Limit *) plan;
454 * Like the plan types above, Limit doesn't evaluate its tlist
455 * or quals. It does have live expressions for limit/offset,
456 * however; and those cannot contain subplan variable refs, so
457 * fix_scan_expr works for them.
459 set_dummy_tlist_references(plan, rtoffset);
460 Assert(splan->plan.qual == NIL);
463 fix_scan_expr(glob, splan->limitOffset, rtoffset);
465 fix_scan_expr(glob, splan->limitCount, rtoffset);
471 set_upper_references(glob, plan, rtoffset);
475 Result *splan = (Result *) plan;
478 * Result may or may not have a subplan; if not, it's more
479 * like a scan node than an upper node.
481 if (splan->plan.lefttree != NULL)
482 set_upper_references(glob, plan, rtoffset);
485 splan->plan.targetlist =
486 fix_scan_list(glob, splan->plan.targetlist, rtoffset);
488 fix_scan_list(glob, splan->plan.qual, rtoffset);
490 /* resconstantqual can't contain any subplan variable refs */
491 splan->resconstantqual =
492 fix_scan_expr(glob, splan->resconstantqual, rtoffset);
497 ModifyTable *splan = (ModifyTable *) plan;
500 * planner.c already called set_returning_clause_references,
501 * so we should not process either the targetlist or the
504 Assert(splan->plan.qual == NIL);
506 foreach(l, splan->resultRelations)
508 lfirst_int(l) += rtoffset;
510 foreach(l, splan->rowMarks)
512 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
515 rc->prti += rtoffset;
517 foreach(l, splan->plans)
519 lfirst(l) = set_plan_refs(glob,
527 Append *splan = (Append *) plan;
530 * Append, like Sort et al, doesn't actually evaluate its
531 * targetlist or check quals.
533 set_dummy_tlist_references(plan, rtoffset);
534 Assert(splan->plan.qual == NIL);
535 foreach(l, splan->appendplans)
537 lfirst(l) = set_plan_refs(glob,
543 case T_RecursiveUnion:
544 /* This doesn't evaluate targetlist or check quals either */
545 set_dummy_tlist_references(plan, rtoffset);
546 Assert(plan->qual == NIL);
550 BitmapAnd *splan = (BitmapAnd *) plan;
552 /* BitmapAnd works like Append, but has no tlist */
553 Assert(splan->plan.targetlist == NIL);
554 Assert(splan->plan.qual == NIL);
555 foreach(l, splan->bitmapplans)
557 lfirst(l) = set_plan_refs(glob,
565 BitmapOr *splan = (BitmapOr *) plan;
567 /* BitmapOr works like Append, but has no tlist */
568 Assert(splan->plan.targetlist == NIL);
569 Assert(splan->plan.qual == NIL);
570 foreach(l, splan->bitmapplans)
572 lfirst(l) = set_plan_refs(glob,
579 elog(ERROR, "unrecognized node type: %d",
580 (int) nodeTag(plan));
585 * Now recurse into child plans, if any
587 * NOTE: it is essential that we recurse into child plans AFTER we set
588 * subplan references in this plan's tlist and quals. If we did the
589 * reference-adjustments bottom-up, then we would fail to match this
590 * plan's var nodes against the already-modified nodes of the children.
592 plan->lefttree = set_plan_refs(glob, plan->lefttree, rtoffset);
593 plan->righttree = set_plan_refs(glob, plan->righttree, rtoffset);
599 * set_subqueryscan_references
600 * Do set_plan_references processing on a SubqueryScan
602 * We try to strip out the SubqueryScan entirely; if we can't, we have
603 * to do the normal processing on it.
606 set_subqueryscan_references(PlannerGlobal *glob,
612 /* First, recursively process the subplan */
613 plan->subplan = set_plan_references(glob, plan->subplan,
614 plan->subrtable, plan->subrowmark);
616 /* subrtable/subrowmark are no longer needed in the plan tree */
617 plan->subrtable = NIL;
618 plan->subrowmark = NIL;
620 if (trivial_subqueryscan(plan))
623 * We can omit the SubqueryScan node and just pull up the subplan.
628 result = plan->subplan;
630 /* We have to be sure we don't lose any initplans */
631 result->initPlan = list_concat(plan->scan.plan.initPlan,
635 * We also have to transfer the SubqueryScan's result-column names
636 * into the subplan, else columns sent to client will be improperly
637 * labeled if this is the topmost plan level. Copy the "source
638 * column" information too.
640 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
642 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
643 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
645 ctle->resname = ptle->resname;
646 ctle->resorigtbl = ptle->resorigtbl;
647 ctle->resorigcol = ptle->resorigcol;
653 * Keep the SubqueryScan node. We have to do the processing that
654 * set_plan_references would otherwise have done on it. Notice we do
655 * not do set_upper_references() here, because a SubqueryScan will
656 * always have been created with correct references to its subplan's
657 * outputs to begin with.
659 plan->scan.scanrelid += rtoffset;
660 plan->scan.plan.targetlist =
661 fix_scan_list(glob, plan->scan.plan.targetlist, rtoffset);
662 plan->scan.plan.qual =
663 fix_scan_list(glob, plan->scan.plan.qual, rtoffset);
665 result = (Plan *) plan;
672 * trivial_subqueryscan
673 * Detect whether a SubqueryScan can be deleted from the plan tree.
675 * We can delete it if it has no qual to check and the targetlist just
676 * regurgitates the output of the child plan.
679 trivial_subqueryscan(SubqueryScan *plan)
685 if (plan->scan.plan.qual != NIL)
688 if (list_length(plan->scan.plan.targetlist) !=
689 list_length(plan->subplan->targetlist))
690 return false; /* tlists not same length */
693 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
695 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
696 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
698 if (ptle->resjunk != ctle->resjunk)
699 return false; /* tlist doesn't match junk status */
702 * We accept either a Var referencing the corresponding element of the
703 * subplan tlist, or a Const equaling the subplan element. See
704 * generate_setop_tlist() for motivation.
706 if (ptle->expr && IsA(ptle->expr, Var))
708 Var *var = (Var *) ptle->expr;
710 Assert(var->varno == plan->scan.scanrelid);
711 Assert(var->varlevelsup == 0);
712 if (var->varattno != attrno)
713 return false; /* out of order */
715 else if (ptle->expr && IsA(ptle->expr, Const))
717 if (!equal(ptle->expr, ctle->expr))
733 * fix_scan_expr and friends do this enough times that it's worth having
734 * a bespoke routine instead of using the generic copyObject() function.
739 Var *newvar = (Var *) palloc(sizeof(Var));
747 * Do generic set_plan_references processing on an expression node
749 * This is code that is common to all variants of expression-fixing.
750 * We must look up operator opcode info for OpExpr and related nodes,
751 * add OIDs from regclass Const nodes into glob->relationOids,
752 * and add catalog TIDs for user-defined functions into glob->invalItems.
754 * We assume it's okay to update opcode info in-place. So this could possibly
755 * scribble on the planner's input data structures, but it's OK.
758 fix_expr_common(PlannerGlobal *glob, Node *node)
760 /* We assume callers won't call us on a NULL pointer */
761 if (IsA(node, Aggref))
763 record_plan_function_dependency(glob,
764 ((Aggref *) node)->aggfnoid);
766 else if (IsA(node, WindowFunc))
768 record_plan_function_dependency(glob,
769 ((WindowFunc *) node)->winfnoid);
771 else if (IsA(node, FuncExpr))
773 record_plan_function_dependency(glob,
774 ((FuncExpr *) node)->funcid);
776 else if (IsA(node, OpExpr))
778 set_opfuncid((OpExpr *) node);
779 record_plan_function_dependency(glob,
780 ((OpExpr *) node)->opfuncid);
782 else if (IsA(node, DistinctExpr))
784 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
785 record_plan_function_dependency(glob,
786 ((DistinctExpr *) node)->opfuncid);
788 else if (IsA(node, NullIfExpr))
790 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
791 record_plan_function_dependency(glob,
792 ((NullIfExpr *) node)->opfuncid);
794 else if (IsA(node, ScalarArrayOpExpr))
796 set_sa_opfuncid((ScalarArrayOpExpr *) node);
797 record_plan_function_dependency(glob,
798 ((ScalarArrayOpExpr *) node)->opfuncid);
800 else if (IsA(node, ArrayCoerceExpr))
802 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
803 record_plan_function_dependency(glob,
804 ((ArrayCoerceExpr *) node)->elemfuncid);
806 else if (IsA(node, Const))
808 Const *con = (Const *) node;
810 /* Check for regclass reference */
811 if (ISREGCLASSCONST(con))
813 lappend_oid(glob->relationOids,
814 DatumGetObjectId(con->constvalue));
820 * Do set_plan_references processing on a scan-level expression
822 * This consists of incrementing all Vars' varnos by rtoffset,
823 * looking up operator opcode info for OpExpr and related nodes,
824 * and adding OIDs from regclass Const nodes into glob->relationOids.
827 fix_scan_expr(PlannerGlobal *glob, Node *node, int rtoffset)
829 fix_scan_expr_context context;
832 context.rtoffset = rtoffset;
834 if (rtoffset != 0 || glob->lastPHId != 0)
836 return fix_scan_expr_mutator(node, &context);
841 * If rtoffset == 0, we don't need to change any Vars, and if there
842 * are no placeholders anywhere we won't need to remove them. Then
843 * it's OK to just scribble on the input node tree instead of copying
844 * (since the only change, filling in any unset opfuncid fields, is
845 * harmless). This saves just enough cycles to be noticeable on
848 (void) fix_scan_expr_walker(node, &context);
854 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
860 Var *var = copyVar((Var *) node);
862 Assert(var->varlevelsup == 0);
865 * We should not see any Vars marked INNER, but in a nestloop inner
866 * scan there could be OUTER Vars. Leave them alone.
868 Assert(var->varno != INNER);
869 if (var->varno > 0 && var->varno != OUTER)
870 var->varno += context->rtoffset;
871 if (var->varnoold > 0)
872 var->varnoold += context->rtoffset;
875 if (IsA(node, CurrentOfExpr))
877 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
879 Assert(cexpr->cvarno != INNER);
880 Assert(cexpr->cvarno != OUTER);
881 cexpr->cvarno += context->rtoffset;
882 return (Node *) cexpr;
884 if (IsA(node, PlaceHolderVar))
886 /* At scan level, we should always just evaluate the contained expr */
887 PlaceHolderVar *phv = (PlaceHolderVar *) node;
889 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
891 fix_expr_common(context->glob, node);
892 return expression_tree_mutator(node, fix_scan_expr_mutator,
897 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
901 Assert(!IsA(node, PlaceHolderVar));
902 fix_expr_common(context->glob, node);
903 return expression_tree_walker(node, fix_scan_expr_walker,
908 * set_join_references
909 * Modify the target list and quals of a join node to reference its
910 * subplans, by setting the varnos to OUTER or INNER and setting attno
911 * values to the result domain number of either the corresponding outer
912 * or inner join tuple item. Also perform opcode lookup for these
913 * expressions. and add regclass OIDs to glob->relationOids.
915 * In the case of a nestloop with inner indexscan, we will also need to
916 * apply the same transformation to any outer vars appearing in the
917 * quals of the child indexscan. set_inner_join_references does that.
920 set_join_references(PlannerGlobal *glob, Join *join, int rtoffset)
922 Plan *outer_plan = join->plan.lefttree;
923 Plan *inner_plan = join->plan.righttree;
924 indexed_tlist *outer_itlist;
925 indexed_tlist *inner_itlist;
927 outer_itlist = build_tlist_index(outer_plan->targetlist);
928 inner_itlist = build_tlist_index(inner_plan->targetlist);
930 /* All join plans have tlist, qual, and joinqual */
931 join->plan.targetlist = fix_join_expr(glob,
932 join->plan.targetlist,
937 join->plan.qual = fix_join_expr(glob,
943 join->joinqual = fix_join_expr(glob,
950 /* Now do join-type-specific stuff */
951 if (IsA(join, NestLoop))
953 /* This processing is split out to handle possible recursion */
954 set_inner_join_references(glob, inner_plan, outer_itlist);
956 else if (IsA(join, MergeJoin))
958 MergeJoin *mj = (MergeJoin *) join;
960 mj->mergeclauses = fix_join_expr(glob,
967 else if (IsA(join, HashJoin))
969 HashJoin *hj = (HashJoin *) join;
971 hj->hashclauses = fix_join_expr(glob,
984 * set_inner_join_references
985 * Handle join references appearing in an inner indexscan's quals
987 * To handle bitmap-scan plan trees, we have to be able to recurse down
988 * to the bottom BitmapIndexScan nodes; likewise, appendrel indexscans
989 * require recursing through Append nodes. This is split out as a separate
990 * function so that it can recurse.
992 * Note we do *not* apply any rtoffset for non-join Vars; this is because
993 * the quals will be processed again by fix_scan_expr when the set_plan_refs
994 * recursion reaches the inner indexscan, and so we'd have done it twice.
997 set_inner_join_references(PlannerGlobal *glob, Plan *inner_plan,
998 indexed_tlist *outer_itlist)
1000 if (IsA(inner_plan, IndexScan))
1003 * An index is being used to reduce the number of tuples scanned in
1004 * the inner relation. If there are join clauses being used with the
1005 * index, we must update their outer-rel var nodes to refer to the
1006 * outer side of the join.
1008 IndexScan *innerscan = (IndexScan *) inner_plan;
1009 List *indexqualorig = innerscan->indexqualorig;
1011 /* No work needed if indexqual refers only to its own rel... */
1012 if (NumRelids((Node *) indexqualorig) > 1)
1014 Index innerrel = innerscan->scan.scanrelid;
1016 /* only refs to outer vars get changed in the inner qual */
1017 innerscan->indexqualorig = fix_join_expr(glob,
1023 innerscan->indexqual = fix_join_expr(glob,
1024 innerscan->indexqual,
1031 * We must fix the inner qpqual too, if it has join clauses (this
1032 * could happen if special operators are involved: some indexquals
1033 * may get rechecked as qpquals).
1035 if (NumRelids((Node *) inner_plan->qual) > 1)
1036 inner_plan->qual = fix_join_expr(glob,
1044 else if (IsA(inner_plan, BitmapIndexScan))
1047 * Same, but index is being used within a bitmap plan.
1049 BitmapIndexScan *innerscan = (BitmapIndexScan *) inner_plan;
1050 List *indexqualorig = innerscan->indexqualorig;
1052 /* No work needed if indexqual refers only to its own rel... */
1053 if (NumRelids((Node *) indexqualorig) > 1)
1055 Index innerrel = innerscan->scan.scanrelid;
1057 /* only refs to outer vars get changed in the inner qual */
1058 innerscan->indexqualorig = fix_join_expr(glob,
1064 innerscan->indexqual = fix_join_expr(glob,
1065 innerscan->indexqual,
1070 /* no need to fix inner qpqual */
1071 Assert(inner_plan->qual == NIL);
1074 else if (IsA(inner_plan, BitmapHeapScan))
1077 * The inner side is a bitmap scan plan. Fix the top node, and
1078 * recurse to get the lower nodes.
1080 * Note: create_bitmap_scan_plan removes clauses from bitmapqualorig
1081 * if they are duplicated in qpqual, so must test these independently.
1083 BitmapHeapScan *innerscan = (BitmapHeapScan *) inner_plan;
1084 Index innerrel = innerscan->scan.scanrelid;
1085 List *bitmapqualorig = innerscan->bitmapqualorig;
1087 /* only refs to outer vars get changed in the inner qual */
1088 if (NumRelids((Node *) bitmapqualorig) > 1)
1089 innerscan->bitmapqualorig = fix_join_expr(glob,
1097 * We must fix the inner qpqual too, if it has join clauses (this
1098 * could happen if special operators are involved: some indexquals may
1099 * get rechecked as qpquals).
1101 if (NumRelids((Node *) inner_plan->qual) > 1)
1102 inner_plan->qual = fix_join_expr(glob,
1110 set_inner_join_references(glob, inner_plan->lefttree, outer_itlist);
1112 else if (IsA(inner_plan, BitmapAnd))
1114 /* All we need do here is recurse */
1115 BitmapAnd *innerscan = (BitmapAnd *) inner_plan;
1118 foreach(l, innerscan->bitmapplans)
1120 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1123 else if (IsA(inner_plan, BitmapOr))
1125 /* All we need do here is recurse */
1126 BitmapOr *innerscan = (BitmapOr *) inner_plan;
1129 foreach(l, innerscan->bitmapplans)
1131 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1134 else if (IsA(inner_plan, TidScan))
1136 TidScan *innerscan = (TidScan *) inner_plan;
1137 Index innerrel = innerscan->scan.scanrelid;
1139 innerscan->tidquals = fix_join_expr(glob,
1140 innerscan->tidquals,
1146 else if (IsA(inner_plan, Append))
1149 * The inner side is an append plan. Recurse to see if it contains
1150 * indexscans that need to be fixed.
1152 Append *appendplan = (Append *) inner_plan;
1155 foreach(l, appendplan->appendplans)
1157 set_inner_join_references(glob, (Plan *) lfirst(l), outer_itlist);
1160 else if (IsA(inner_plan, Result))
1162 /* Recurse through a gating Result node (similar to Append case) */
1163 Result *result = (Result *) inner_plan;
1165 if (result->plan.lefttree)
1166 set_inner_join_references(glob, result->plan.lefttree, outer_itlist);
1171 * set_upper_references
1172 * Update the targetlist and quals of an upper-level plan node
1173 * to refer to the tuples returned by its lefttree subplan.
1174 * Also perform opcode lookup for these expressions, and
1175 * add regclass OIDs to glob->relationOids.
1177 * This is used for single-input plan types like Agg, Group, Result.
1179 * In most cases, we have to match up individual Vars in the tlist and
1180 * qual expressions with elements of the subplan's tlist (which was
1181 * generated by flatten_tlist() from these selfsame expressions, so it
1182 * should have all the required variables). There is an important exception,
1183 * however: GROUP BY and ORDER BY expressions will have been pushed into the
1184 * subplan tlist unflattened. If these values are also needed in the output
1185 * then we want to reference the subplan tlist element rather than recomputing
1189 set_upper_references(PlannerGlobal *glob, Plan *plan, int rtoffset)
1191 Plan *subplan = plan->lefttree;
1192 indexed_tlist *subplan_itlist;
1193 List *output_targetlist;
1196 subplan_itlist = build_tlist_index(subplan->targetlist);
1198 output_targetlist = NIL;
1199 foreach(l, plan->targetlist)
1201 TargetEntry *tle = (TargetEntry *) lfirst(l);
1204 /* If it's a non-Var sort/group item, first try to match by sortref */
1205 if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
1208 search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
1209 tle->ressortgroupref,
1213 newexpr = fix_upper_expr(glob,
1219 newexpr = fix_upper_expr(glob,
1223 tle = flatCopyTargetEntry(tle);
1224 tle->expr = (Expr *) newexpr;
1225 output_targetlist = lappend(output_targetlist, tle);
1227 plan->targetlist = output_targetlist;
1229 plan->qual = (List *)
1230 fix_upper_expr(glob,
1231 (Node *) plan->qual,
1235 pfree(subplan_itlist);
1239 * set_dummy_tlist_references
1240 * Replace the targetlist of an upper-level plan node with a simple
1241 * list of OUTER references to its child.
1243 * This is used for plan types like Sort and Append that don't evaluate
1244 * their targetlists. Although the executor doesn't care at all what's in
1245 * the tlist, EXPLAIN needs it to be realistic.
1247 * Note: we could almost use set_upper_references() here, but it fails for
1248 * Append for lack of a lefttree subplan. Single-purpose code is faster
1252 set_dummy_tlist_references(Plan *plan, int rtoffset)
1254 List *output_targetlist;
1257 output_targetlist = NIL;
1258 foreach(l, plan->targetlist)
1260 TargetEntry *tle = (TargetEntry *) lfirst(l);
1261 Var *oldvar = (Var *) tle->expr;
1264 newvar = makeVar(OUTER,
1266 exprType((Node *) oldvar),
1267 exprTypmod((Node *) oldvar),
1269 if (IsA(oldvar, Var))
1271 newvar->varnoold = oldvar->varno + rtoffset;
1272 newvar->varoattno = oldvar->varattno;
1276 newvar->varnoold = 0; /* wasn't ever a plain Var */
1277 newvar->varoattno = 0;
1280 tle = flatCopyTargetEntry(tle);
1281 tle->expr = (Expr *) newvar;
1282 output_targetlist = lappend(output_targetlist, tle);
1284 plan->targetlist = output_targetlist;
1286 /* We don't touch plan->qual here */
1291 * build_tlist_index --- build an index data structure for a child tlist
1293 * In most cases, subplan tlists will be "flat" tlists with only Vars,
1294 * so we try to optimize that case by extracting information about Vars
1295 * in advance. Matching a parent tlist to a child is still an O(N^2)
1296 * operation, but at least with a much smaller constant factor than plain
1297 * tlist_member() searches.
1299 * The result of this function is an indexed_tlist struct to pass to
1300 * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1301 * When done, the indexed_tlist may be freed with a single pfree().
1303 static indexed_tlist *
1304 build_tlist_index(List *tlist)
1306 indexed_tlist *itlist;
1310 /* Create data structure with enough slots for all tlist entries */
1311 itlist = (indexed_tlist *)
1312 palloc(offsetof(indexed_tlist, vars) +
1313 list_length(tlist) * sizeof(tlist_vinfo));
1315 itlist->tlist = tlist;
1316 itlist->has_ph_vars = false;
1317 itlist->has_non_vars = false;
1319 /* Find the Vars and fill in the index array */
1320 vinfo = itlist->vars;
1323 TargetEntry *tle = (TargetEntry *) lfirst(l);
1325 if (tle->expr && IsA(tle->expr, Var))
1327 Var *var = (Var *) tle->expr;
1329 vinfo->varno = var->varno;
1330 vinfo->varattno = var->varattno;
1331 vinfo->resno = tle->resno;
1334 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1335 itlist->has_ph_vars = true;
1337 itlist->has_non_vars = true;
1340 itlist->num_vars = (vinfo - itlist->vars);
1346 * build_tlist_index_other_vars --- build a restricted tlist index
1348 * This is like build_tlist_index, but we only index tlist entries that
1349 * are Vars belonging to some rel other than the one specified. We will set
1350 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1351 * (so nothing other than Vars and PlaceHolderVars can be matched).
1353 static indexed_tlist *
1354 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1356 indexed_tlist *itlist;
1360 /* Create data structure with enough slots for all tlist entries */
1361 itlist = (indexed_tlist *)
1362 palloc(offsetof(indexed_tlist, vars) +
1363 list_length(tlist) * sizeof(tlist_vinfo));
1365 itlist->tlist = tlist;
1366 itlist->has_ph_vars = false;
1367 itlist->has_non_vars = false;
1369 /* Find the desired Vars and fill in the index array */
1370 vinfo = itlist->vars;
1373 TargetEntry *tle = (TargetEntry *) lfirst(l);
1375 if (tle->expr && IsA(tle->expr, Var))
1377 Var *var = (Var *) tle->expr;
1379 if (var->varno != ignore_rel)
1381 vinfo->varno = var->varno;
1382 vinfo->varattno = var->varattno;
1383 vinfo->resno = tle->resno;
1387 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1388 itlist->has_ph_vars = true;
1391 itlist->num_vars = (vinfo - itlist->vars);
1397 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1399 * If a match is found, return a copy of the given Var with suitably
1400 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1401 * Also ensure that varnoold is incremented by rtoffset.
1402 * If no match, return NULL.
1405 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1406 Index newvarno, int rtoffset)
1408 Index varno = var->varno;
1409 AttrNumber varattno = var->varattno;
1413 vinfo = itlist->vars;
1414 i = itlist->num_vars;
1417 if (vinfo->varno == varno && vinfo->varattno == varattno)
1420 Var *newvar = copyVar(var);
1422 newvar->varno = newvarno;
1423 newvar->varattno = vinfo->resno;
1424 if (newvar->varnoold > 0)
1425 newvar->varnoold += rtoffset;
1430 return NULL; /* no match */
1434 * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1436 * If a match is found, return a Var constructed to reference the tlist item.
1437 * If no match, return NULL.
1439 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1440 * itlist->has_non_vars
1443 search_indexed_tlist_for_non_var(Node *node,
1444 indexed_tlist *itlist, Index newvarno)
1448 tle = tlist_member(node, itlist->tlist);
1451 /* Found a matching subplan output expression */
1454 newvar = makeVar(newvarno,
1456 exprType((Node *) tle->expr),
1457 exprTypmod((Node *) tle->expr),
1459 newvar->varnoold = 0; /* wasn't ever a plain Var */
1460 newvar->varoattno = 0;
1463 return NULL; /* no match */
1467 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
1468 * (which is assumed not to be just a Var)
1470 * If a match is found, return a Var constructed to reference the tlist item.
1471 * If no match, return NULL.
1473 * This is needed to ensure that we select the right subplan TLE in cases
1474 * where there are multiple textually-equal()-but-volatile sort expressions.
1475 * And it's also faster than search_indexed_tlist_for_non_var.
1478 search_indexed_tlist_for_sortgroupref(Node *node,
1480 indexed_tlist *itlist,
1485 foreach(lc, itlist->tlist)
1487 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1489 /* The equal() check should be redundant, but let's be paranoid */
1490 if (tle->ressortgroupref == sortgroupref &&
1491 equal(node, tle->expr))
1493 /* Found a matching subplan output expression */
1496 newvar = makeVar(newvarno,
1498 exprType((Node *) tle->expr),
1499 exprTypmod((Node *) tle->expr),
1501 newvar->varnoold = 0; /* wasn't ever a plain Var */
1502 newvar->varoattno = 0;
1506 return NULL; /* no match */
1511 * Create a new set of targetlist entries or join qual clauses by
1512 * changing the varno/varattno values of variables in the clauses
1513 * to reference target list values from the outer and inner join
1514 * relation target lists. Also perform opcode lookup and add
1515 * regclass OIDs to glob->relationOids.
1517 * This is used in two different scenarios: a normal join clause, where
1518 * all the Vars in the clause *must* be replaced by OUTER or INNER references;
1519 * and an indexscan being used on the inner side of a nestloop join.
1520 * In the latter case we want to replace the outer-relation Vars by OUTER
1521 * references, while Vars of the inner relation should be adjusted by rtoffset.
1522 * (We also implement RETURNING clause fixup using this second scenario.)
1524 * For a normal join, acceptable_rel should be zero so that any failure to
1525 * match a Var will be reported as an error. For the indexscan case,
1526 * pass inner_itlist = NULL and acceptable_rel = the (not-offseted-yet) ID
1527 * of the inner relation.
1529 * 'clauses' is the targetlist or list of join clauses
1530 * 'outer_itlist' is the indexed target list of the outer join relation
1531 * 'inner_itlist' is the indexed target list of the inner join relation,
1533 * 'acceptable_rel' is either zero or the rangetable index of a relation
1534 * whose Vars may appear in the clause without provoking an error.
1535 * 'rtoffset' is what to add to varno for Vars of acceptable_rel.
1537 * Returns the new expression tree. The original clause structure is
1541 fix_join_expr(PlannerGlobal *glob,
1543 indexed_tlist *outer_itlist,
1544 indexed_tlist *inner_itlist,
1545 Index acceptable_rel,
1548 fix_join_expr_context context;
1550 context.glob = glob;
1551 context.outer_itlist = outer_itlist;
1552 context.inner_itlist = inner_itlist;
1553 context.acceptable_rel = acceptable_rel;
1554 context.rtoffset = rtoffset;
1555 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1559 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1567 Var *var = (Var *) node;
1569 /* First look for the var in the input tlists */
1570 newvar = search_indexed_tlist_for_var(var,
1571 context->outer_itlist,
1575 return (Node *) newvar;
1576 if (context->inner_itlist)
1578 newvar = search_indexed_tlist_for_var(var,
1579 context->inner_itlist,
1583 return (Node *) newvar;
1586 /* If it's for acceptable_rel, adjust and return it */
1587 if (var->varno == context->acceptable_rel)
1590 var->varno += context->rtoffset;
1591 var->varnoold += context->rtoffset;
1592 return (Node *) var;
1595 /* No referent found for Var */
1596 elog(ERROR, "variable not found in subplan target lists");
1598 if (IsA(node, PlaceHolderVar))
1600 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1602 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1603 if (context->outer_itlist->has_ph_vars)
1605 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1606 context->outer_itlist,
1609 return (Node *) newvar;
1611 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1613 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1614 context->inner_itlist,
1617 return (Node *) newvar;
1620 /* If not supplied by input plans, evaluate the contained expr */
1621 return fix_join_expr_mutator((Node *) phv->phexpr, context);
1623 /* Try matching more complex expressions too, if tlists have any */
1624 if (context->outer_itlist->has_non_vars)
1626 newvar = search_indexed_tlist_for_non_var(node,
1627 context->outer_itlist,
1630 return (Node *) newvar;
1632 if (context->inner_itlist && context->inner_itlist->has_non_vars)
1634 newvar = search_indexed_tlist_for_non_var(node,
1635 context->inner_itlist,
1638 return (Node *) newvar;
1640 fix_expr_common(context->glob, node);
1641 return expression_tree_mutator(node,
1642 fix_join_expr_mutator,
1648 * Modifies an expression tree so that all Var nodes reference outputs
1649 * of a subplan. Also performs opcode lookup, and adds regclass OIDs to
1650 * glob->relationOids.
1652 * This is used to fix up target and qual expressions of non-join upper-level
1655 * An error is raised if no matching var can be found in the subplan tlist
1656 * --- so this routine should only be applied to nodes whose subplans'
1657 * targetlists were generated via flatten_tlist() or some such method.
1659 * If itlist->has_non_vars is true, then we try to match whole subexpressions
1660 * against elements of the subplan tlist, so that we can avoid recomputing
1661 * expressions that were already computed by the subplan. (This is relatively
1662 * expensive, so we don't want to try it in the common case where the
1663 * subplan tlist is just a flattened list of Vars.)
1665 * 'node': the tree to be fixed (a target item or qual)
1666 * 'subplan_itlist': indexed target list for subplan
1667 * 'rtoffset': how much to increment varnoold by
1669 * The resulting tree is a copy of the original in which all Var nodes have
1670 * varno = OUTER, varattno = resno of corresponding subplan target.
1671 * The original tree is not modified.
1674 fix_upper_expr(PlannerGlobal *glob,
1676 indexed_tlist *subplan_itlist,
1679 fix_upper_expr_context context;
1681 context.glob = glob;
1682 context.subplan_itlist = subplan_itlist;
1683 context.rtoffset = rtoffset;
1684 return fix_upper_expr_mutator(node, &context);
1688 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1696 Var *var = (Var *) node;
1698 newvar = search_indexed_tlist_for_var(var,
1699 context->subplan_itlist,
1703 elog(ERROR, "variable not found in subplan target list");
1704 return (Node *) newvar;
1706 if (IsA(node, PlaceHolderVar))
1708 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1710 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1711 if (context->subplan_itlist->has_ph_vars)
1713 newvar = search_indexed_tlist_for_non_var((Node *) phv,
1714 context->subplan_itlist,
1717 return (Node *) newvar;
1719 /* If not supplied by input plan, evaluate the contained expr */
1720 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
1722 /* Try matching more complex expressions too, if tlist has any */
1723 if (context->subplan_itlist->has_non_vars)
1725 newvar = search_indexed_tlist_for_non_var(node,
1726 context->subplan_itlist,
1729 return (Node *) newvar;
1731 fix_expr_common(context->glob, node);
1732 return expression_tree_mutator(node,
1733 fix_upper_expr_mutator,
1738 * set_returning_clause_references
1739 * Perform setrefs.c's work on a RETURNING targetlist
1741 * If the query involves more than just the result table, we have to
1742 * adjust any Vars that refer to other tables to reference junk tlist
1743 * entries in the top subplan's targetlist. Vars referencing the result
1744 * table should be left alone, however (the executor will evaluate them
1745 * using the actual heap tuple, after firing triggers if any). In the
1746 * adjusted RETURNING list, result-table Vars will still have their
1747 * original varno, but Vars for other rels will have varno OUTER.
1749 * We also must perform opcode lookup and add regclass OIDs to
1750 * glob->relationOids.
1752 * 'rlist': the RETURNING targetlist to be fixed
1753 * 'topplan': the top subplan node that will be just below the ModifyTable
1754 * node (note it's not yet passed through set_plan_references)
1755 * 'resultRelation': RT index of the associated result relation
1757 * Note: we assume that result relations will have rtoffset zero, that is,
1758 * they are not coming from a subplan.
1761 set_returning_clause_references(PlannerGlobal *glob,
1764 Index resultRelation)
1766 indexed_tlist *itlist;
1769 * We can perform the desired Var fixup by abusing the fix_join_expr
1770 * machinery that normally handles inner indexscan fixup. We search the
1771 * top plan's targetlist for Vars of non-result relations, and use
1772 * fix_join_expr to convert RETURNING Vars into references to those tlist
1773 * entries, while leaving result-rel Vars as-is.
1775 * PlaceHolderVars will also be sought in the targetlist, but no
1776 * more-complex expressions will be. Note that it is not possible for a
1777 * PlaceHolderVar to refer to the result relation, since the result is
1778 * never below an outer join. If that case could happen, we'd have to be
1779 * prepared to pick apart the PlaceHolderVar and evaluate its contained
1780 * expression instead.
1782 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
1784 rlist = fix_join_expr(glob,
1796 /*****************************************************************************
1797 * OPERATOR REGPROC LOOKUP
1798 *****************************************************************************/
1802 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1803 * The given tree can be anything expression_tree_walker handles.
1805 * The argument is modified in-place. (This is OK since we'd want the
1806 * same change for any node, even if it gets visited more than once due to
1807 * shared structure.)
1810 fix_opfuncids(Node *node)
1812 /* This tree walk requires no special setup, so away we go... */
1813 fix_opfuncids_walker(node, NULL);
1817 fix_opfuncids_walker(Node *node, void *context)
1821 if (IsA(node, OpExpr))
1822 set_opfuncid((OpExpr *) node);
1823 else if (IsA(node, DistinctExpr))
1824 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1825 else if (IsA(node, NullIfExpr))
1826 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1827 else if (IsA(node, ScalarArrayOpExpr))
1828 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1829 return expression_tree_walker(node, fix_opfuncids_walker, context);
1834 * Set the opfuncid (procedure OID) in an OpExpr node,
1835 * if it hasn't been set already.
1837 * Because of struct equivalence, this can also be used for
1838 * DistinctExpr and NullIfExpr nodes.
1841 set_opfuncid(OpExpr *opexpr)
1843 if (opexpr->opfuncid == InvalidOid)
1844 opexpr->opfuncid = get_opcode(opexpr->opno);
1849 * As above, for ScalarArrayOpExpr nodes.
1852 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1854 if (opexpr->opfuncid == InvalidOid)
1855 opexpr->opfuncid = get_opcode(opexpr->opno);
1858 /*****************************************************************************
1859 * QUERY DEPENDENCY MANAGEMENT
1860 *****************************************************************************/
1863 * record_plan_function_dependency
1864 * Mark the current plan as depending on a particular function.
1866 * This is exported so that the function-inlining code can record a
1867 * dependency on a function that it's removed from the plan tree.
1870 record_plan_function_dependency(PlannerGlobal *glob, Oid funcid)
1873 * For performance reasons, we don't bother to track built-in functions;
1874 * we just assume they'll never change (or at least not in ways that'd
1875 * invalidate plans using them). For this purpose we can consider a
1876 * built-in function to be one with OID less than FirstBootstrapObjectId.
1877 * Note that the OID generator guarantees never to generate such an OID
1878 * after startup, even at OID wraparound.
1880 if (funcid >= (Oid) FirstBootstrapObjectId)
1882 HeapTuple func_tuple;
1883 PlanInvalItem *inval_item;
1885 func_tuple = SearchSysCache(PROCOID,
1886 ObjectIdGetDatum(funcid),
1888 if (!HeapTupleIsValid(func_tuple))
1889 elog(ERROR, "cache lookup failed for function %u", funcid);
1891 inval_item = makeNode(PlanInvalItem);
1894 * It would work to use any syscache on pg_proc, but plancache.c
1895 * expects us to use PROCOID.
1897 inval_item->cacheId = PROCOID;
1898 inval_item->tupleId = func_tuple->t_self;
1900 glob->invalItems = lappend(glob->invalItems, inval_item);
1902 ReleaseSysCache(func_tuple);
1907 * extract_query_dependencies
1908 * Given a not-yet-planned query or queries (i.e. a Query node or list
1909 * of Query nodes), extract dependencies just as set_plan_references
1912 * This is needed by plancache.c to handle invalidation of cached unplanned
1916 extract_query_dependencies(Node *query,
1917 List **relationOids,
1922 /* Make up a dummy PlannerGlobal so we can use this module's machinery */
1923 MemSet(&glob, 0, sizeof(glob));
1924 glob.type = T_PlannerGlobal;
1925 glob.relationOids = NIL;
1926 glob.invalItems = NIL;
1928 (void) extract_query_dependencies_walker(query, &glob);
1930 *relationOids = glob.relationOids;
1931 *invalItems = glob.invalItems;
1935 extract_query_dependencies_walker(Node *node, PlannerGlobal *context)
1939 Assert(!IsA(node, PlaceHolderVar));
1940 /* Extract function dependencies and check for regclass Consts */
1941 fix_expr_common(context, node);
1942 if (IsA(node, Query))
1944 Query *query = (Query *) node;
1947 if (query->commandType == CMD_UTILITY)
1949 /* Ignore utility statements, except EXPLAIN */
1950 if (IsA(query->utilityStmt, ExplainStmt))
1952 query = (Query *) ((ExplainStmt *) query->utilityStmt)->query;
1953 Assert(IsA(query, Query));
1954 Assert(query->commandType != CMD_UTILITY);
1960 /* Collect relation OIDs in this Query's rtable */
1961 foreach(lc, query->rtable)
1963 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
1965 if (rte->rtekind == RTE_RELATION)
1966 context->relationOids = lappend_oid(context->relationOids,
1970 /* And recurse into the query's subexpressions */
1971 return query_tree_walker(query, extract_query_dependencies_walker,
1972 (void *) context, 0);
1974 return expression_tree_walker(node, extract_query_dependencies_walker,