Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
setrefs.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * setrefs.c
4 * Post-processing of a completed plan tree: fix references to subplan
5 * vars, compute regproc values for operators, etc
6 *
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
9 *
10 *
11 * IDENTIFICATION
12 * src/backend/optimizer/plan/setrefs.c
13 *
14 *-------------------------------------------------------------------------
15 */
16#include "postgres.h"
17
18#include "access/transam.h"
19#include "catalog/pg_type.h"
20#include "nodes/makefuncs.h"
21#include "nodes/nodeFuncs.h"
22#include "optimizer/optimizer.h"
23#include "optimizer/pathnode.h"
24#include "optimizer/planmain.h"
25#include "optimizer/planner.h"
26#include "optimizer/subselect.h"
27#include "optimizer/tlist.h"
30#include "tcop/utility.h"
31#include "utils/syscache.h"
32
33
34typedef enum
35{
36 NRM_EQUAL, /* expect exact match of nullingrels */
37 NRM_SUBSET, /* actual Var may have a subset of input */
38 NRM_SUPERSET, /* actual Var may have a superset of input */
40
41typedef struct
42{
43 int varno; /* RT index of Var */
44 AttrNumber varattno; /* attr number of Var */
45 AttrNumber resno; /* TLE position of Var */
46 Bitmapset *varnullingrels; /* Var's varnullingrels */
48
49typedef struct
50{
51 List *tlist; /* underlying target list */
52 int num_vars; /* number of plain Var tlist entries */
53 bool has_ph_vars; /* are there PlaceHolderVar entries? */
54 bool has_non_vars; /* are there other entries? */
55 tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]; /* has num_vars entries */
57
58typedef struct
59{
62 double num_exec;
64
65typedef struct
66{
73 double num_exec;
75
76typedef struct
77{
83 double num_exec;
85
86typedef struct
87{
92
93/* Context info for flatten_rtes_walker() */
94typedef struct
95{
99
100/*
101 * Selecting the best alternative in an AlternativeSubPlan expression requires
102 * estimating how many times that expression will be evaluated. For an
103 * expression in a plan node's targetlist, the plan's estimated number of
104 * output rows is clearly what to use, but for an expression in a qual it's
105 * far less clear. Since AlternativeSubPlans aren't heavily used, we don't
106 * want to expend a lot of cycles making such estimates. What we use is twice
107 * the number of output rows. That's not entirely unfounded: we know that
108 * clause_selectivity() would fall back to a default selectivity estimate
109 * of 0.5 for any SubPlan, so if the qual containing the SubPlan is the last
110 * to be applied (which it likely would be, thanks to order_qual_clauses()),
111 * this matches what we could have estimated in a far more laborious fashion.
112 * Obviously there are many other scenarios, but it's probably not worth the
113 * trouble to try to improve on this estimate, especially not when we don't
114 * have a better estimate for the selectivity of the SubPlan qual itself.
115 */
116#define NUM_EXEC_TLIST(parentplan) ((parentplan)->plan_rows)
117#define NUM_EXEC_QUAL(parentplan) ((parentplan)->plan_rows * 2.0)
118
119/*
120 * Check if a Const node is a regclass value. We accept plain OID too,
121 * since a regclass Const will get folded to that type if it's an argument
122 * to oideq or similar operators. (This might result in some extraneous
123 * values in a plan's list of relation dependencies, but the worst result
124 * would be occasional useless replans.)
125 */
126#define ISREGCLASSCONST(con) \
127 (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
128 !(con)->constisnull)
129
130#define fix_scan_list(root, lst, rtoffset, num_exec) \
131 ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))
132
133static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
134static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
136static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
137 RangeTblEntry *rte);
138static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
141 int rtoffset);
144 int rtoffset);
145static Plan *clean_up_removed_plan_level(Plan *parent, Plan *child);
147 ForeignScan *fscan,
148 int rtoffset);
150 CustomScan *cscan,
151 int rtoffset);
153 Append *aplan,
154 int rtoffset);
156 MergeAppend *mplan,
157 int rtoffset);
158static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset);
159static Relids offset_relid_set(Relids relids, int rtoffset);
160static Node *fix_scan_expr(PlannerInfo *root, Node *node,
161 int rtoffset, double num_exec);
163static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
164static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
165static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
167static Node *convert_combining_aggrefs(Node *node, void *context);
168static void set_dummy_tlist_references(Plan *plan, int rtoffset);
169static indexed_tlist *build_tlist_index(List *tlist);
171 indexed_tlist *itlist,
172 int newvarno,
173 int rtoffset,
174 NullingRelsMatch nrm_match);
176 indexed_tlist *itlist,
177 int newvarno,
178 NullingRelsMatch nrm_match);
180 indexed_tlist *itlist,
181 int newvarno);
183 Index sortgroupref,
184 indexed_tlist *itlist,
185 int newvarno);
187 List *clauses,
188 indexed_tlist *outer_itlist,
189 indexed_tlist *inner_itlist,
190 Index acceptable_rel,
191 int rtoffset,
192 NullingRelsMatch nrm_match,
193 double num_exec);
194static Node *fix_join_expr_mutator(Node *node,
195 fix_join_expr_context *context);
197 Node *node,
198 indexed_tlist *subplan_itlist,
199 int newvarno,
200 int rtoffset,
201 NullingRelsMatch nrm_match,
202 double num_exec);
203static Node *fix_upper_expr_mutator(Node *node,
204 fix_upper_expr_context *context);
206 List *rlist,
207 Plan *topplan,
208 Index resultRelation,
209 int rtoffset);
211 List *runcondition,
212 Plan *plan);
213
214
215/*****************************************************************************
216 *
217 * SUBPLAN REFERENCES
218 *
219 *****************************************************************************/
220
221/*
222 * set_plan_references
223 *
224 * This is the final processing pass of the planner/optimizer. The plan
225 * tree is complete; we just have to adjust some representational details
226 * for the convenience of the executor:
227 *
228 * 1. We flatten the various subquery rangetables into a single list, and
229 * zero out RangeTblEntry fields that are not useful to the executor.
230 *
231 * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
232 *
233 * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
234 * subplans.
235 *
236 * 4. Aggrefs in Agg plan nodes need to be adjusted in some cases involving
237 * partial aggregation or minmax aggregate optimization.
238 *
239 * 5. PARAM_MULTIEXPR Params are replaced by regular PARAM_EXEC Params,
240 * now that we have finished planning all MULTIEXPR subplans.
241 *
242 * 6. AlternativeSubPlan expressions are replaced by just one of their
243 * alternatives, using an estimate of how many times they'll be executed.
244 *
245 * 7. We compute regproc OIDs for operators (ie, we look up the function
246 * that implements each op).
247 *
248 * 8. We create lists of specific objects that the plan depends on.
249 * This will be used by plancache.c to drive invalidation of cached plans.
250 * Relation dependencies are represented by OIDs, and everything else by
251 * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
252 * Currently, relations, user-defined functions, and domains are the only
253 * types of objects that are explicitly tracked this way.
254 *
255 * 9. We assign every plan node in the tree a unique ID.
256 *
257 * We also perform one final optimization step, which is to delete
258 * SubqueryScan, Append, and MergeAppend plan nodes that aren't doing
259 * anything useful. The reason for doing this last is that
260 * it can't readily be done before set_plan_references, because it would
261 * break set_upper_references: the Vars in the child plan's top tlist
262 * wouldn't match up with the Vars in the outer plan tree. A SubqueryScan
263 * serves a necessary function as a buffer between outer query and subquery
264 * variable numbering ... but after we've flattened the rangetable this is
265 * no longer a problem, since then there's only one rtindex namespace.
266 * Likewise, Append and MergeAppend buffer between the parent and child vars
267 * of an appendrel, but we don't need to worry about that once we've done
268 * set_plan_references.
269 *
270 * set_plan_references recursively traverses the whole plan tree.
271 *
272 * The return value is normally the same Plan node passed in, but can be
273 * different when the passed-in Plan is a node we decide isn't needed.
274 *
275 * The flattened rangetable entries are appended to root->glob->finalrtable.
276 * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
277 * RT indexes of ModifyTable result relations to root->glob->resultRelations,
278 * and flattened AppendRelInfos are appended to root->glob->appendRelations.
279 * Plan dependencies are appended to root->glob->relationOids (for relations)
280 * and root->glob->invalItems (for everything else).
281 *
282 * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
283 * to process targetlist and qual expressions. We can assume that the Plan
284 * nodes were just built by the planner and are not multiply referenced, but
285 * it's not so safe to assume that for expression tree nodes.
286 */
287Plan *
289{
290 Plan *result;
291 PlannerGlobal *glob = root->glob;
292 int rtoffset = list_length(glob->finalrtable);
293 ListCell *lc;
294
295 /*
296 * Add all the query's RTEs to the flattened rangetable. The live ones
297 * will have their rangetable indexes increased by rtoffset. (Additional
298 * RTEs, not referenced by the Plan tree, might get added after those.)
299 */
301
302 /*
303 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
304 */
305 foreach(lc, root->rowMarks)
306 {
308 PlanRowMark *newrc;
309
310 /* sanity check on existing row marks */
311 Assert(root->simple_rel_array[rc->rti] != NULL &&
312 root->simple_rte_array[rc->rti] != NULL);
313
314 /* flat copy is enough since all fields are scalars */
315 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
316 memcpy(newrc, rc, sizeof(PlanRowMark));
317
318 /* adjust indexes ... but *not* the rowmarkId */
319 newrc->rti += rtoffset;
320 newrc->prti += rtoffset;
321
322 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
323 }
324
325 /*
326 * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
327 * We assume the AppendRelInfos were built during planning and don't need
328 * to be copied.
329 */
330 foreach(lc, root->append_rel_list)
331 {
333
334 /* adjust RT indexes */
335 appinfo->parent_relid += rtoffset;
336 appinfo->child_relid += rtoffset;
337
338 /*
339 * Rather than adjust the translated_vars entries, just drop 'em.
340 * Neither the executor nor EXPLAIN currently need that data.
341 */
342 appinfo->translated_vars = NIL;
343
344 glob->appendRelations = lappend(glob->appendRelations, appinfo);
345 }
346
347 /* If needed, create workspace for processing AlternativeSubPlans */
348 if (root->hasAlternativeSubPlans)
349 {
350 root->isAltSubplan = (bool *)
351 palloc0(list_length(glob->subplans) * sizeof(bool));
352 root->isUsedSubplan = (bool *)
353 palloc0(list_length(glob->subplans) * sizeof(bool));
354 }
355
356 /* Now fix the Plan tree */
357 result = set_plan_refs(root, plan, rtoffset);
358
359 /*
360 * If we have AlternativeSubPlans, it is likely that we now have some
361 * unreferenced subplans in glob->subplans. To avoid expending cycles on
362 * those subplans later, get rid of them by setting those list entries to
363 * NULL. (Note: we can't do this immediately upon processing an
364 * AlternativeSubPlan, because there may be multiple copies of the
365 * AlternativeSubPlan, and they can get resolved differently.)
366 */
367 if (root->hasAlternativeSubPlans)
368 {
369 foreach(lc, glob->subplans)
370 {
371 int ndx = foreach_current_index(lc);
372
373 /*
374 * If it was used by some AlternativeSubPlan in this query level,
375 * but wasn't selected as best by any AlternativeSubPlan, then we
376 * don't need it. Do not touch subplans that aren't parts of
377 * AlternativeSubPlans.
378 */
379 if (root->isAltSubplan[ndx] && !root->isUsedSubplan[ndx])
380 lfirst(lc) = NULL;
381 }
382 }
383
384 return result;
385}
386
387/*
388 * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
389 *
390 * This can recurse into subquery plans; "recursing" is true if so.
391 *
392 * This also seems like a good place to add the query's RTEPermissionInfos to
393 * the flat rteperminfos.
394 */
395static void
397{
398 PlannerGlobal *glob = root->glob;
399 Index rti;
400 ListCell *lc;
401
402 /*
403 * Add the query's own RTEs to the flattened rangetable.
404 *
405 * At top level, we must add all RTEs so that their indexes in the
406 * flattened rangetable match up with their original indexes. When
407 * recursing, we only care about extracting relation RTEs (and subquery
408 * RTEs that were once relation RTEs).
409 */
410 foreach(lc, root->parse->rtable)
411 {
412 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
413
414 if (!recursing || rte->rtekind == RTE_RELATION ||
415 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
416 add_rte_to_flat_rtable(glob, root->parse->rteperminfos, rte);
417 }
418
419 /*
420 * If there are any dead subqueries, they are not referenced in the Plan
421 * tree, so we must add RTEs contained in them to the flattened rtable
422 * separately. (If we failed to do this, the executor would not perform
423 * expected permission checks for tables mentioned in such subqueries.)
424 *
425 * Note: this pass over the rangetable can't be combined with the previous
426 * one, because that would mess up the numbering of the live RTEs in the
427 * flattened rangetable.
428 */
429 rti = 1;
430 foreach(lc, root->parse->rtable)
431 {
432 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
433
434 /*
435 * We should ignore inheritance-parent RTEs: their contents have been
436 * pulled up into our rangetable already. Also ignore any subquery
437 * RTEs without matching RelOptInfos, as they likewise have been
438 * pulled up.
439 */
440 if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
441 rti < root->simple_rel_array_size)
442 {
443 RelOptInfo *rel = root->simple_rel_array[rti];
444
445 if (rel != NULL)
446 {
447 Assert(rel->relid == rti); /* sanity check on array */
448
449 /*
450 * The subquery might never have been planned at all, if it
451 * was excluded on the basis of self-contradictory constraints
452 * in our query level. In this case apply
453 * flatten_unplanned_rtes.
454 *
455 * If it was planned but the result rel is dummy, we assume
456 * that it has been omitted from our plan tree (see
457 * set_subquery_pathlist), and recurse to pull up its RTEs.
458 *
459 * Otherwise, it should be represented by a SubqueryScan node
460 * somewhere in our plan tree, and we'll pull up its RTEs when
461 * we process that plan node.
462 *
463 * However, if we're recursing, then we should pull up RTEs
464 * whether the subquery is dummy or not, because we've found
465 * that some upper query level is treating this one as dummy,
466 * and so we won't scan this level's plan tree at all.
467 */
468 if (rel->subroot == NULL)
469 flatten_unplanned_rtes(glob, rte);
470 else if (recursing ||
472 UPPERREL_FINAL, NULL)))
474 }
475 }
476 rti++;
477 }
478}
479
480/*
481 * Extract RangeTblEntries from a subquery that was never planned at all
482 */
483
484static void
486{
487 flatten_rtes_walker_context cxt = {glob, rte->subquery};
488
489 /* Use query_tree_walker to find all RTEs in the parse tree */
490 (void) query_tree_walker(rte->subquery,
492 &cxt,
494}
495
496static bool
498{
499 if (node == NULL)
500 return false;
501 if (IsA(node, RangeTblEntry))
502 {
503 RangeTblEntry *rte = (RangeTblEntry *) node;
504
505 /* As above, we need only save relation RTEs and former relations */
506 if (rte->rtekind == RTE_RELATION ||
507 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
508 add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
509 return false;
510 }
511 if (IsA(node, Query))
512 {
513 /*
514 * Recurse into subselects. Must update cxt->query to this query so
515 * that the rtable and rteperminfos correspond with each other.
516 */
517 Query *save_query = cxt->query;
518 bool result;
519
520 cxt->query = (Query *) node;
521 result = query_tree_walker((Query *) node,
523 cxt,
525 cxt->query = save_query;
526 return result;
527 }
529}
530
531/*
532 * Add (a copy of) the given RTE to the final rangetable and also the
533 * corresponding RTEPermissionInfo, if any, to final rteperminfos.
534 *
535 * In the flat rangetable, we zero out substructure pointers that are not
536 * needed by the executor; this reduces the storage space and copying cost
537 * for cached plans. We keep only the ctename, alias, eref Alias fields,
538 * which are needed by EXPLAIN, and perminfoindex which is needed by the
539 * executor to fetch the RTE's RTEPermissionInfo.
540 */
541static void
543 RangeTblEntry *rte)
544{
545 RangeTblEntry *newrte;
546
547 /* flat copy to duplicate all the scalar fields */
548 newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
549 memcpy(newrte, rte, sizeof(RangeTblEntry));
550
551 /* zap unneeded sub-structure */
552 newrte->tablesample = NULL;
553 newrte->subquery = NULL;
554 newrte->joinaliasvars = NIL;
555 newrte->joinleftcols = NIL;
556 newrte->joinrightcols = NIL;
557 newrte->join_using_alias = NULL;
558 newrte->functions = NIL;
559 newrte->tablefunc = NULL;
560 newrte->values_lists = NIL;
561 newrte->coltypes = NIL;
562 newrte->coltypmods = NIL;
563 newrte->colcollations = NIL;
564 newrte->groupexprs = NIL;
565 newrte->securityQuals = NIL;
566
567 glob->finalrtable = lappend(glob->finalrtable, newrte);
568
569 /*
570 * If it's a plain relation RTE (or a subquery that was once a view
571 * reference), add the relation OID to relationOids. Also add its new RT
572 * index to the set of relations to be potentially accessed during
573 * execution.
574 *
575 * We do this even though the RTE might be unreferenced in the plan tree;
576 * this would correspond to cases such as views that were expanded, child
577 * tables that were eliminated by constraint exclusion, etc. Schema
578 * invalidation on such a rel must still force rebuilding of the plan.
579 *
580 * Note we don't bother to avoid making duplicate list entries. We could,
581 * but it would probably cost more cycles than it would save.
582 */
583 if (newrte->rtekind == RTE_RELATION ||
584 (newrte->rtekind == RTE_SUBQUERY && OidIsValid(newrte->relid)))
585 {
586 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
587 glob->allRelids = bms_add_member(glob->allRelids,
588 list_length(glob->finalrtable));
589 }
590
591 /*
592 * Add a copy of the RTEPermissionInfo, if any, corresponding to this RTE
593 * to the flattened global list.
594 */
595 if (rte->perminfoindex > 0)
596 {
597 RTEPermissionInfo *perminfo;
598 RTEPermissionInfo *newperminfo;
599
600 /* Get the existing one from this query's rteperminfos. */
601 perminfo = getRTEPermissionInfo(rteperminfos, newrte);
602
603 /*
604 * Add a new one to finalrteperminfos and copy the contents of the
605 * existing one into it. Note that addRTEPermissionInfo() also
606 * updates newrte->perminfoindex to point to newperminfo in
607 * finalrteperminfos.
608 */
609 newrte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
610 newperminfo = addRTEPermissionInfo(&glob->finalrteperminfos, newrte);
611 memcpy(newperminfo, perminfo, sizeof(RTEPermissionInfo));
612 }
613}
614
615/*
616 * set_plan_refs: recurse through the Plan nodes of a single subquery level
617 */
618static Plan *
620{
621 ListCell *l;
622
623 if (plan == NULL)
624 return NULL;
625
626 /* Assign this node a unique ID. */
627 plan->plan_node_id = root->glob->lastPlanNodeId++;
628
629 /*
630 * Plan-type-specific fixes
631 */
632 switch (nodeTag(plan))
633 {
634 case T_SeqScan:
635 {
636 SeqScan *splan = (SeqScan *) plan;
637
638 splan->scan.scanrelid += rtoffset;
639 splan->scan.plan.targetlist =
640 fix_scan_list(root, splan->scan.plan.targetlist,
641 rtoffset, NUM_EXEC_TLIST(plan));
642 splan->scan.plan.qual =
643 fix_scan_list(root, splan->scan.plan.qual,
644 rtoffset, NUM_EXEC_QUAL(plan));
645 }
646 break;
647 case T_SampleScan:
648 {
649 SampleScan *splan = (SampleScan *) plan;
650
651 splan->scan.scanrelid += rtoffset;
652 splan->scan.plan.targetlist =
653 fix_scan_list(root, splan->scan.plan.targetlist,
654 rtoffset, NUM_EXEC_TLIST(plan));
655 splan->scan.plan.qual =
656 fix_scan_list(root, splan->scan.plan.qual,
657 rtoffset, NUM_EXEC_QUAL(plan));
658 splan->tablesample = (TableSampleClause *)
660 rtoffset, 1);
661 }
662 break;
663 case T_IndexScan:
664 {
665 IndexScan *splan = (IndexScan *) plan;
666
667 splan->scan.scanrelid += rtoffset;
668 splan->scan.plan.targetlist =
669 fix_scan_list(root, splan->scan.plan.targetlist,
670 rtoffset, NUM_EXEC_TLIST(plan));
671 splan->scan.plan.qual =
672 fix_scan_list(root, splan->scan.plan.qual,
673 rtoffset, NUM_EXEC_QUAL(plan));
674 splan->indexqual =
676 rtoffset, 1);
677 splan->indexqualorig =
679 rtoffset, NUM_EXEC_QUAL(plan));
680 splan->indexorderby =
682 rtoffset, 1);
683 splan->indexorderbyorig =
685 rtoffset, NUM_EXEC_QUAL(plan));
686 }
687 break;
688 case T_IndexOnlyScan:
689 {
690 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
691
692 return set_indexonlyscan_references(root, splan, rtoffset);
693 }
694 break;
695 case T_BitmapIndexScan:
696 {
698
699 splan->scan.scanrelid += rtoffset;
700 /* no need to fix targetlist and qual */
701 Assert(splan->scan.plan.targetlist == NIL);
702 Assert(splan->scan.plan.qual == NIL);
703 splan->indexqual =
704 fix_scan_list(root, splan->indexqual, rtoffset, 1);
705 splan->indexqualorig =
707 rtoffset, NUM_EXEC_QUAL(plan));
708 }
709 break;
710 case T_BitmapHeapScan:
711 {
713
714 splan->scan.scanrelid += rtoffset;
715 splan->scan.plan.targetlist =
716 fix_scan_list(root, splan->scan.plan.targetlist,
717 rtoffset, NUM_EXEC_TLIST(plan));
718 splan->scan.plan.qual =
719 fix_scan_list(root, splan->scan.plan.qual,
720 rtoffset, NUM_EXEC_QUAL(plan));
721 splan->bitmapqualorig =
723 rtoffset, NUM_EXEC_QUAL(plan));
724 }
725 break;
726 case T_TidScan:
727 {
728 TidScan *splan = (TidScan *) plan;
729
730 splan->scan.scanrelid += rtoffset;
731 splan->scan.plan.targetlist =
732 fix_scan_list(root, splan->scan.plan.targetlist,
733 rtoffset, NUM_EXEC_TLIST(plan));
734 splan->scan.plan.qual =
735 fix_scan_list(root, splan->scan.plan.qual,
736 rtoffset, NUM_EXEC_QUAL(plan));
737 splan->tidquals =
739 rtoffset, 1);
740 }
741 break;
742 case T_TidRangeScan:
743 {
744 TidRangeScan *splan = (TidRangeScan *) plan;
745
746 splan->scan.scanrelid += rtoffset;
747 splan->scan.plan.targetlist =
748 fix_scan_list(root, splan->scan.plan.targetlist,
749 rtoffset, NUM_EXEC_TLIST(plan));
750 splan->scan.plan.qual =
751 fix_scan_list(root, splan->scan.plan.qual,
752 rtoffset, NUM_EXEC_QUAL(plan));
753 splan->tidrangequals =
755 rtoffset, 1);
756 }
757 break;
758 case T_SubqueryScan:
759 /* Needs special treatment, see comments below */
761 (SubqueryScan *) plan,
762 rtoffset);
763 case T_FunctionScan:
764 {
765 FunctionScan *splan = (FunctionScan *) plan;
766
767 splan->scan.scanrelid += rtoffset;
768 splan->scan.plan.targetlist =
769 fix_scan_list(root, splan->scan.plan.targetlist,
770 rtoffset, NUM_EXEC_TLIST(plan));
771 splan->scan.plan.qual =
772 fix_scan_list(root, splan->scan.plan.qual,
773 rtoffset, NUM_EXEC_QUAL(plan));
774 splan->functions =
775 fix_scan_list(root, splan->functions, rtoffset, 1);
776 }
777 break;
778 case T_TableFuncScan:
779 {
780 TableFuncScan *splan = (TableFuncScan *) plan;
781
782 splan->scan.scanrelid += rtoffset;
783 splan->scan.plan.targetlist =
784 fix_scan_list(root, splan->scan.plan.targetlist,
785 rtoffset, NUM_EXEC_TLIST(plan));
786 splan->scan.plan.qual =
787 fix_scan_list(root, splan->scan.plan.qual,
788 rtoffset, NUM_EXEC_QUAL(plan));
789 splan->tablefunc = (TableFunc *)
790 fix_scan_expr(root, (Node *) splan->tablefunc,
791 rtoffset, 1);
792 }
793 break;
794 case T_ValuesScan:
795 {
796 ValuesScan *splan = (ValuesScan *) plan;
797
798 splan->scan.scanrelid += rtoffset;
799 splan->scan.plan.targetlist =
800 fix_scan_list(root, splan->scan.plan.targetlist,
801 rtoffset, NUM_EXEC_TLIST(plan));
802 splan->scan.plan.qual =
803 fix_scan_list(root, splan->scan.plan.qual,
804 rtoffset, NUM_EXEC_QUAL(plan));
805 splan->values_lists =
807 rtoffset, 1);
808 }
809 break;
810 case T_CteScan:
811 {
812 CteScan *splan = (CteScan *) plan;
813
814 splan->scan.scanrelid += rtoffset;
815 splan->scan.plan.targetlist =
816 fix_scan_list(root, splan->scan.plan.targetlist,
817 rtoffset, NUM_EXEC_TLIST(plan));
818 splan->scan.plan.qual =
819 fix_scan_list(root, splan->scan.plan.qual,
820 rtoffset, NUM_EXEC_QUAL(plan));
821 }
822 break;
823 case T_NamedTuplestoreScan:
824 {
826
827 splan->scan.scanrelid += rtoffset;
828 splan->scan.plan.targetlist =
829 fix_scan_list(root, splan->scan.plan.targetlist,
830 rtoffset, NUM_EXEC_TLIST(plan));
831 splan->scan.plan.qual =
832 fix_scan_list(root, splan->scan.plan.qual,
833 rtoffset, NUM_EXEC_QUAL(plan));
834 }
835 break;
836 case T_WorkTableScan:
837 {
838 WorkTableScan *splan = (WorkTableScan *) plan;
839
840 splan->scan.scanrelid += rtoffset;
841 splan->scan.plan.targetlist =
842 fix_scan_list(root, splan->scan.plan.targetlist,
843 rtoffset, NUM_EXEC_TLIST(plan));
844 splan->scan.plan.qual =
845 fix_scan_list(root, splan->scan.plan.qual,
846 rtoffset, NUM_EXEC_QUAL(plan));
847 }
848 break;
849 case T_ForeignScan:
851 break;
852 case T_CustomScan:
854 break;
855
856 case T_NestLoop:
857 case T_MergeJoin:
858 case T_HashJoin:
859 set_join_references(root, (Join *) plan, rtoffset);
860 break;
861
862 case T_Gather:
863 case T_GatherMerge:
864 {
865 set_upper_references(root, plan, rtoffset);
867 }
868 break;
869
870 case T_Hash:
871 set_hash_references(root, plan, rtoffset);
872 break;
873
874 case T_Memoize:
875 {
876 Memoize *mplan = (Memoize *) plan;
877
878 /*
879 * Memoize does not evaluate its targetlist. It just uses the
880 * same targetlist from its outer subnode.
881 */
883
884 mplan->param_exprs = fix_scan_list(root, mplan->param_exprs,
885 rtoffset,
887 break;
888 }
889
890 case T_Material:
891 case T_Sort:
892 case T_IncrementalSort:
893 case T_Unique:
894 case T_SetOp:
895
896 /*
897 * These plan types don't actually bother to evaluate their
898 * targetlists, because they just return their unmodified input
899 * tuples. Even though the targetlist won't be used by the
900 * executor, we fix it up for possible use by EXPLAIN (not to
901 * mention ease of debugging --- wrong varnos are very confusing).
902 */
904
905 /*
906 * Since these plan types don't check quals either, we should not
907 * find any qual expression attached to them.
908 */
909 Assert(plan->qual == NIL);
910 break;
911 case T_LockRows:
912 {
913 LockRows *splan = (LockRows *) plan;
914
915 /*
916 * Like the plan types above, LockRows doesn't evaluate its
917 * tlist or quals. But we have to fix up the RT indexes in
918 * its rowmarks.
919 */
921 Assert(splan->plan.qual == NIL);
922
923 foreach(l, splan->rowMarks)
924 {
925 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
926
927 rc->rti += rtoffset;
928 rc->prti += rtoffset;
929 }
930 }
931 break;
932 case T_Limit:
933 {
934 Limit *splan = (Limit *) plan;
935
936 /*
937 * Like the plan types above, Limit doesn't evaluate its tlist
938 * or quals. It does have live expressions for limit/offset,
939 * however; and those cannot contain subplan variable refs, so
940 * fix_scan_expr works for them.
941 */
943 Assert(splan->plan.qual == NIL);
944
945 splan->limitOffset =
946 fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
947 splan->limitCount =
948 fix_scan_expr(root, splan->limitCount, rtoffset, 1);
949 }
950 break;
951 case T_Agg:
952 {
953 Agg *agg = (Agg *) plan;
954
955 /*
956 * If this node is combining partial-aggregation results, we
957 * must convert its Aggrefs to contain references to the
958 * partial-aggregate subexpressions that will be available
959 * from the child plan node.
960 */
962 {
963 plan->targetlist = (List *)
964 convert_combining_aggrefs((Node *) plan->targetlist,
965 NULL);
966 plan->qual = (List *)
968 NULL);
969 }
970
971 set_upper_references(root, plan, rtoffset);
972 }
973 break;
974 case T_Group:
975 set_upper_references(root, plan, rtoffset);
976 break;
977 case T_WindowAgg:
978 {
979 WindowAgg *wplan = (WindowAgg *) plan;
980
981 /*
982 * Adjust the WindowAgg's run conditions by swapping the
983 * WindowFuncs references out to instead reference the Var in
984 * the scan slot so that when the executor evaluates the
985 * runCondition, it receives the WindowFunc's value from the
986 * slot that the result has just been stored into rather than
987 * evaluating the WindowFunc all over again.
988 */
990 wplan->runCondition,
991 (Plan *) wplan);
992
993 set_upper_references(root, plan, rtoffset);
994
995 /*
996 * Like Limit node limit/offset expressions, WindowAgg has
997 * frame offset expressions, which cannot contain subplan
998 * variable refs, so fix_scan_expr works for them.
999 */
1000 wplan->startOffset =
1001 fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
1002 wplan->endOffset =
1003 fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
1005 wplan->runCondition,
1006 rtoffset,
1009 wplan->runConditionOrig,
1010 rtoffset,
1012 }
1013 break;
1014 case T_Result:
1015 {
1016 Result *splan = (Result *) plan;
1017
1018 /*
1019 * Result may or may not have a subplan; if not, it's more
1020 * like a scan node than an upper node.
1021 */
1022 if (splan->plan.lefttree != NULL)
1023 set_upper_references(root, plan, rtoffset);
1024 else
1025 {
1026 /*
1027 * The tlist of a childless Result could contain
1028 * unresolved ROWID_VAR Vars, in case it's representing a
1029 * target relation which is completely empty because of
1030 * constraint exclusion. Replace any such Vars by null
1031 * constants, as though they'd been resolved for a leaf
1032 * scan node that doesn't support them. We could have
1033 * fix_scan_expr do this, but since the case is only
1034 * expected to occur here, it seems safer to special-case
1035 * it here and keep the assertions that ROWID_VARs
1036 * shouldn't be seen by fix_scan_expr.
1037 */
1038 foreach(l, splan->plan.targetlist)
1039 {
1040 TargetEntry *tle = (TargetEntry *) lfirst(l);
1041 Var *var = (Var *) tle->expr;
1042
1043 if (var && IsA(var, Var) && var->varno == ROWID_VAR)
1044 tle->expr = (Expr *) makeNullConst(var->vartype,
1045 var->vartypmod,
1046 var->varcollid);
1047 }
1048
1049 splan->plan.targetlist =
1051 rtoffset, NUM_EXEC_TLIST(plan));
1052 splan->plan.qual =
1053 fix_scan_list(root, splan->plan.qual,
1054 rtoffset, NUM_EXEC_QUAL(plan));
1055 }
1056 /* resconstantqual can't contain any subplan variable refs */
1057 splan->resconstantqual =
1058 fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
1059 /* adjust the relids set */
1060 splan->relids = offset_relid_set(splan->relids, rtoffset);
1061 }
1062 break;
1063 case T_ProjectSet:
1064 set_upper_references(root, plan, rtoffset);
1065 break;
1066 case T_ModifyTable:
1067 {
1068 ModifyTable *splan = (ModifyTable *) plan;
1069 Plan *subplan = outerPlan(splan);
1070
1071 Assert(splan->plan.targetlist == NIL);
1072 Assert(splan->plan.qual == NIL);
1073
1074 splan->withCheckOptionLists =
1076 rtoffset, 1);
1077
1078 if (splan->returningLists)
1079 {
1080 List *newRL = NIL;
1081 ListCell *lcrl,
1082 *lcrr;
1083
1084 /*
1085 * Pass each per-resultrel returningList through
1086 * set_returning_clause_references().
1087 */
1089 forboth(lcrl, splan->returningLists,
1090 lcrr, splan->resultRelations)
1091 {
1092 List *rlist = (List *) lfirst(lcrl);
1093 Index resultrel = lfirst_int(lcrr);
1094
1096 rlist,
1097 subplan,
1098 resultrel,
1099 rtoffset);
1100 newRL = lappend(newRL, rlist);
1101 }
1102 splan->returningLists = newRL;
1103
1104 /*
1105 * Set up the visible plan targetlist as being the same as
1106 * the first RETURNING list. This is mostly for the use
1107 * of EXPLAIN; the executor won't execute that targetlist,
1108 * although it does use it to prepare the node's result
1109 * tuple slot. We postpone this step until here so that
1110 * we don't have to do set_returning_clause_references()
1111 * twice on identical targetlists.
1112 */
1113 splan->plan.targetlist = copyObject(linitial(newRL));
1114 }
1115
1116 /*
1117 * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
1118 * join', where the inner side is the EXCLUDED tuple.
1119 * Therefore use fix_join_expr to setup the relevant variables
1120 * to INNER_VAR. We explicitly don't create any OUTER_VARs as
1121 * those are already used by RETURNING and it seems better to
1122 * be non-conflicting.
1123 */
1124 if (splan->onConflictSet)
1125 {
1126 indexed_tlist *itlist;
1127
1128 itlist = build_tlist_index(splan->exclRelTlist);
1129
1130 splan->onConflictSet =
1132 NULL, itlist,
1134 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1135
1136 splan->onConflictWhere = (Node *)
1138 NULL, itlist,
1140 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1141
1142 pfree(itlist);
1143
1144 splan->exclRelTlist =
1145 fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
1146 }
1147
1148 /*
1149 * The MERGE statement produces the target rows by performing
1150 * a right join between the target relation and the source
1151 * relation (which could be a plain relation or a subquery).
1152 * The INSERT and UPDATE actions of the MERGE statement
1153 * require access to the columns from the source relation. We
1154 * arrange things so that the source relation attributes are
1155 * available as INNER_VAR and the target relation attributes
1156 * are available from the scan tuple.
1157 */
1158 if (splan->mergeActionLists != NIL)
1159 {
1160 List *newMJC = NIL;
1161 ListCell *lca,
1162 *lcj,
1163 *lcr;
1164
1165 /*
1166 * Fix the targetList of individual action nodes so that
1167 * the so-called "source relation" Vars are referenced as
1168 * INNER_VAR. Note that for this to work correctly during
1169 * execution, the ecxt_innertuple must be set to the tuple
1170 * obtained by executing the subplan, which is what
1171 * constitutes the "source relation".
1172 *
1173 * We leave the Vars from the result relation (i.e. the
1174 * target relation) unchanged i.e. those Vars would be
1175 * picked from the scan slot. So during execution, we must
1176 * ensure that ecxt_scantuple is setup correctly to refer
1177 * to the tuple from the target relation.
1178 */
1179 indexed_tlist *itlist;
1180
1181 itlist = build_tlist_index(subplan->targetlist);
1182
1184 lcj, splan->mergeJoinConditions,
1185 lcr, splan->resultRelations)
1186 {
1187 List *mergeActionList = lfirst(lca);
1188 Node *mergeJoinCondition = lfirst(lcj);
1189 Index resultrel = lfirst_int(lcr);
1190
1191 foreach(l, mergeActionList)
1192 {
1194
1195 /* Fix targetList of each action. */
1196 action->targetList = fix_join_expr(root,
1197 action->targetList,
1198 NULL, itlist,
1199 resultrel,
1200 rtoffset,
1201 NRM_EQUAL,
1203
1204 /* Fix quals too. */
1205 action->qual = (Node *) fix_join_expr(root,
1206 (List *) action->qual,
1207 NULL, itlist,
1208 resultrel,
1209 rtoffset,
1210 NRM_EQUAL,
1212 }
1213
1214 /* Fix join condition too. */
1215 mergeJoinCondition = (Node *)
1217 (List *) mergeJoinCondition,
1218 NULL, itlist,
1219 resultrel,
1220 rtoffset,
1221 NRM_EQUAL,
1223 newMJC = lappend(newMJC, mergeJoinCondition);
1224 }
1225 splan->mergeJoinConditions = newMJC;
1226 }
1227
1228 splan->nominalRelation += rtoffset;
1229 if (splan->rootRelation)
1230 splan->rootRelation += rtoffset;
1231 splan->exclRelRTI += rtoffset;
1232
1233 foreach(l, splan->resultRelations)
1234 {
1235 lfirst_int(l) += rtoffset;
1236 }
1237 foreach(l, splan->rowMarks)
1238 {
1239 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1240
1241 rc->rti += rtoffset;
1242 rc->prti += rtoffset;
1243 }
1244
1245 /*
1246 * Append this ModifyTable node's final result relation RT
1247 * index(es) to the global list for the plan.
1248 */
1249 root->glob->resultRelations =
1250 list_concat(root->glob->resultRelations,
1251 splan->resultRelations);
1252 if (splan->rootRelation)
1253 {
1254 root->glob->resultRelations =
1255 lappend_int(root->glob->resultRelations,
1256 splan->rootRelation);
1257 }
1258 }
1259 break;
1260 case T_Append:
1261 /* Needs special treatment, see comments below */
1263 (Append *) plan,
1264 rtoffset);
1265 case T_MergeAppend:
1266 /* Needs special treatment, see comments below */
1268 (MergeAppend *) plan,
1269 rtoffset);
1270 case T_RecursiveUnion:
1271 /* This doesn't evaluate targetlist or check quals either */
1273 Assert(plan->qual == NIL);
1274 break;
1275 case T_BitmapAnd:
1276 {
1277 BitmapAnd *splan = (BitmapAnd *) plan;
1278
1279 /* BitmapAnd works like Append, but has no tlist */
1280 Assert(splan->plan.targetlist == NIL);
1281 Assert(splan->plan.qual == NIL);
1282 foreach(l, splan->bitmapplans)
1283 {
1285 (Plan *) lfirst(l),
1286 rtoffset);
1287 }
1288 }
1289 break;
1290 case T_BitmapOr:
1291 {
1292 BitmapOr *splan = (BitmapOr *) plan;
1293
1294 /* BitmapOr works like Append, but has no tlist */
1295 Assert(splan->plan.targetlist == NIL);
1296 Assert(splan->plan.qual == NIL);
1297 foreach(l, splan->bitmapplans)
1298 {
1300 (Plan *) lfirst(l),
1301 rtoffset);
1302 }
1303 }
1304 break;
1305 default:
1306 elog(ERROR, "unrecognized node type: %d",
1307 (int) nodeTag(plan));
1308 break;
1309 }
1310
1311 /*
1312 * Now recurse into child plans, if any
1313 *
1314 * NOTE: it is essential that we recurse into child plans AFTER we set
1315 * subplan references in this plan's tlist and quals. If we did the
1316 * reference-adjustments bottom-up, then we would fail to match this
1317 * plan's var nodes against the already-modified nodes of the children.
1318 */
1319 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1320 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1321
1322 return plan;
1323}
1324
1325/*
1326 * set_indexonlyscan_references
1327 * Do set_plan_references processing on an IndexOnlyScan
1328 *
1329 * This is unlike the handling of a plain IndexScan because we have to
1330 * convert Vars referencing the heap into Vars referencing the index.
1331 * We can use the fix_upper_expr machinery for that, by working from a
1332 * targetlist describing the index columns.
1333 */
1334static Plan *
1337 int rtoffset)
1338{
1339 indexed_tlist *index_itlist;
1340 List *stripped_indextlist;
1341 ListCell *lc;
1342
1343 /*
1344 * Vars in the plan node's targetlist, qual, and recheckqual must only
1345 * reference columns that the index AM can actually return. To ensure
1346 * this, remove non-returnable columns (which are marked as resjunk) from
1347 * the indexed tlist. We can just drop them because the indexed_tlist
1348 * machinery pays attention to TLE resnos, not physical list position.
1349 */
1350 stripped_indextlist = NIL;
1351 foreach(lc, plan->indextlist)
1352 {
1353 TargetEntry *indextle = (TargetEntry *) lfirst(lc);
1354
1355 if (!indextle->resjunk)
1356 stripped_indextlist = lappend(stripped_indextlist, indextle);
1357 }
1358
1359 index_itlist = build_tlist_index(stripped_indextlist);
1360
1361 plan->scan.scanrelid += rtoffset;
1362 plan->scan.plan.targetlist = (List *)
1364 (Node *) plan->scan.plan.targetlist,
1365 index_itlist,
1366 INDEX_VAR,
1367 rtoffset,
1368 NRM_EQUAL,
1369 NUM_EXEC_TLIST((Plan *) plan));
1370 plan->scan.plan.qual = (List *)
1372 (Node *) plan->scan.plan.qual,
1373 index_itlist,
1374 INDEX_VAR,
1375 rtoffset,
1376 NRM_EQUAL,
1377 NUM_EXEC_QUAL((Plan *) plan));
1378 plan->recheckqual = (List *)
1380 (Node *) plan->recheckqual,
1381 index_itlist,
1382 INDEX_VAR,
1383 rtoffset,
1384 NRM_EQUAL,
1385 NUM_EXEC_QUAL((Plan *) plan));
1386 /* indexqual is already transformed to reference index columns */
1387 plan->indexqual = fix_scan_list(root, plan->indexqual,
1388 rtoffset, 1);
1389 /* indexorderby is already transformed to reference index columns */
1390 plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1391 rtoffset, 1);
1392 /* indextlist must NOT be transformed to reference index columns */
1393 plan->indextlist = fix_scan_list(root, plan->indextlist,
1394 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1395
1396 pfree(index_itlist);
1397
1398 return (Plan *) plan;
1399}
1400
1401/*
1402 * set_subqueryscan_references
1403 * Do set_plan_references processing on a SubqueryScan
1404 *
1405 * We try to strip out the SubqueryScan entirely; if we can't, we have
1406 * to do the normal processing on it.
1407 */
1408static Plan *
1411 int rtoffset)
1412{
1413 RelOptInfo *rel;
1414 Plan *result;
1415
1416 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1417 rel = find_base_rel(root, plan->scan.scanrelid);
1418
1419 /* Recursively process the subplan */
1420 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1421
1423 {
1424 /*
1425 * We can omit the SubqueryScan node and just pull up the subplan.
1426 */
1427 result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
1428 }
1429 else
1430 {
1431 /*
1432 * Keep the SubqueryScan node. We have to do the processing that
1433 * set_plan_references would otherwise have done on it. Notice we do
1434 * not do set_upper_references() here, because a SubqueryScan will
1435 * always have been created with correct references to its subplan's
1436 * outputs to begin with.
1437 */
1438 plan->scan.scanrelid += rtoffset;
1439 plan->scan.plan.targetlist =
1440 fix_scan_list(root, plan->scan.plan.targetlist,
1441 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1442 plan->scan.plan.qual =
1443 fix_scan_list(root, plan->scan.plan.qual,
1444 rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1445
1446 result = (Plan *) plan;
1447 }
1448
1449 return result;
1450}
1451
1452/*
1453 * trivial_subqueryscan
1454 * Detect whether a SubqueryScan can be deleted from the plan tree.
1455 *
1456 * We can delete it if it has no qual to check and the targetlist just
1457 * regurgitates the output of the child plan.
1458 *
1459 * This can be called from mark_async_capable_plan(), a helper function for
1460 * create_append_plan(), before set_subqueryscan_references(), to determine
1461 * triviality of a SubqueryScan that is a child of an Append node. So we
1462 * cache the result in the SubqueryScan node to avoid repeated computation.
1463 *
1464 * Note: when called from mark_async_capable_plan(), we determine the result
1465 * before running finalize_plan() on the SubqueryScan node (if needed) and
1466 * set_plan_references() on the subplan tree, but this would be safe, because
1467 * 1) finalize_plan() doesn't modify the tlist or quals for the SubqueryScan
1468 * node (or that for any plan node in the subplan tree), and
1469 * 2) set_plan_references() modifies the tlist for every plan node in the
1470 * subplan tree, but keeps const/resjunk columns as const/resjunk ones and
1471 * preserves the length and order of the tlist, and
1472 * 3) set_plan_references() might delete the topmost plan node like an Append
1473 * or MergeAppend from the subplan tree and pull up the child plan node,
1474 * but in that case, the tlist for the child plan node exactly matches the
1475 * parent.
1476 */
1477bool
1479{
1480 int attrno;
1481 ListCell *lp,
1482 *lc;
1483
1484 /* We might have detected this already; in which case reuse the result */
1485 if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1486 return true;
1487 if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1488 return false;
1489 Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1490 /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1491 plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1492
1493 if (plan->scan.plan.qual != NIL)
1494 return false;
1495
1496 if (list_length(plan->scan.plan.targetlist) !=
1497 list_length(plan->subplan->targetlist))
1498 return false; /* tlists not same length */
1499
1500 attrno = 1;
1501 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1502 {
1503 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
1504 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1505
1506 if (ptle->resjunk != ctle->resjunk)
1507 return false; /* tlist doesn't match junk status */
1508
1509 /*
1510 * We accept either a Var referencing the corresponding element of the
1511 * subplan tlist, or a Const equaling the subplan element. See
1512 * generate_setop_tlist() for motivation.
1513 */
1514 if (ptle->expr && IsA(ptle->expr, Var))
1515 {
1516 Var *var = (Var *) ptle->expr;
1517
1518 Assert(var->varno == plan->scan.scanrelid);
1519 Assert(var->varlevelsup == 0);
1520 if (var->varattno != attrno)
1521 return false; /* out of order */
1522 }
1523 else if (ptle->expr && IsA(ptle->expr, Const))
1524 {
1525 if (!equal(ptle->expr, ctle->expr))
1526 return false;
1527 }
1528 else
1529 return false;
1530
1531 attrno++;
1532 }
1533
1534 /* Re-mark the SubqueryScan as deletable from the plan tree */
1535 plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1536
1537 return true;
1538}
1539
1540/*
1541 * clean_up_removed_plan_level
1542 * Do necessary cleanup when we strip out a SubqueryScan, Append, etc
1543 *
1544 * We are dropping the "parent" plan in favor of returning just its "child".
1545 * A few small tweaks are needed.
1546 */
1547static Plan *
1549{
1550 /*
1551 * We have to be sure we don't lose any initplans, so move any that were
1552 * attached to the parent plan to the child. If any are parallel-unsafe,
1553 * the child is no longer parallel-safe. As a cosmetic matter, also add
1554 * the initplans' run costs to the child's costs.
1555 */
1556 if (parent->initPlan)
1557 {
1558 Cost initplan_cost;
1559 bool unsafe_initplans;
1560
1562 &initplan_cost, &unsafe_initplans);
1563 child->startup_cost += initplan_cost;
1564 child->total_cost += initplan_cost;
1565 if (unsafe_initplans)
1566 child->parallel_safe = false;
1567
1568 /*
1569 * Attach plans this way so that parent's initplans are processed
1570 * before any pre-existing initplans of the child. Probably doesn't
1571 * matter, but let's preserve the ordering just in case.
1572 */
1573 child->initPlan = list_concat(parent->initPlan,
1574 child->initPlan);
1575 }
1576
1577 /*
1578 * We also have to transfer the parent's column labeling info into the
1579 * child, else columns sent to client will be improperly labeled if this
1580 * is the topmost plan level. resjunk and so on may be important too.
1581 */
1583
1584 return child;
1585}
1586
1587/*
1588 * set_foreignscan_references
1589 * Do set_plan_references processing on a ForeignScan
1590 */
1591static void
1593 ForeignScan *fscan,
1594 int rtoffset)
1595{
1596 /* Adjust scanrelid if it's valid */
1597 if (fscan->scan.scanrelid > 0)
1598 fscan->scan.scanrelid += rtoffset;
1599
1600 if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1601 {
1602 /*
1603 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1604 * foreign scan tuple
1605 */
1607
1608 fscan->scan.plan.targetlist = (List *)
1610 (Node *) fscan->scan.plan.targetlist,
1611 itlist,
1612 INDEX_VAR,
1613 rtoffset,
1614 NRM_EQUAL,
1615 NUM_EXEC_TLIST((Plan *) fscan));
1616 fscan->scan.plan.qual = (List *)
1618 (Node *) fscan->scan.plan.qual,
1619 itlist,
1620 INDEX_VAR,
1621 rtoffset,
1622 NRM_EQUAL,
1623 NUM_EXEC_QUAL((Plan *) fscan));
1624 fscan->fdw_exprs = (List *)
1626 (Node *) fscan->fdw_exprs,
1627 itlist,
1628 INDEX_VAR,
1629 rtoffset,
1630 NRM_EQUAL,
1631 NUM_EXEC_QUAL((Plan *) fscan));
1632 fscan->fdw_recheck_quals = (List *)
1634 (Node *) fscan->fdw_recheck_quals,
1635 itlist,
1636 INDEX_VAR,
1637 rtoffset,
1638 NRM_EQUAL,
1639 NUM_EXEC_QUAL((Plan *) fscan));
1640 pfree(itlist);
1641 /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1642 fscan->fdw_scan_tlist =
1643 fix_scan_list(root, fscan->fdw_scan_tlist,
1644 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1645 }
1646 else
1647 {
1648 /*
1649 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1650 * way
1651 */
1652 fscan->scan.plan.targetlist =
1653 fix_scan_list(root, fscan->scan.plan.targetlist,
1654 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1655 fscan->scan.plan.qual =
1656 fix_scan_list(root, fscan->scan.plan.qual,
1657 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1658 fscan->fdw_exprs =
1659 fix_scan_list(root, fscan->fdw_exprs,
1660 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1661 fscan->fdw_recheck_quals =
1662 fix_scan_list(root, fscan->fdw_recheck_quals,
1663 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1664 }
1665
1666 fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1667 fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1668
1669 /* Adjust resultRelation if it's valid */
1670 if (fscan->resultRelation > 0)
1671 fscan->resultRelation += rtoffset;
1672}
1673
1674/*
1675 * set_customscan_references
1676 * Do set_plan_references processing on a CustomScan
1677 */
1678static void
1680 CustomScan *cscan,
1681 int rtoffset)
1682{
1683 ListCell *lc;
1684
1685 /* Adjust scanrelid if it's valid */
1686 if (cscan->scan.scanrelid > 0)
1687 cscan->scan.scanrelid += rtoffset;
1688
1689 if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1690 {
1691 /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1693
1694 cscan->scan.plan.targetlist = (List *)
1696 (Node *) cscan->scan.plan.targetlist,
1697 itlist,
1698 INDEX_VAR,
1699 rtoffset,
1700 NRM_EQUAL,
1701 NUM_EXEC_TLIST((Plan *) cscan));
1702 cscan->scan.plan.qual = (List *)
1704 (Node *) cscan->scan.plan.qual,
1705 itlist,
1706 INDEX_VAR,
1707 rtoffset,
1708 NRM_EQUAL,
1709 NUM_EXEC_QUAL((Plan *) cscan));
1710 cscan->custom_exprs = (List *)
1712 (Node *) cscan->custom_exprs,
1713 itlist,
1714 INDEX_VAR,
1715 rtoffset,
1716 NRM_EQUAL,
1717 NUM_EXEC_QUAL((Plan *) cscan));
1718 pfree(itlist);
1719 /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1720 cscan->custom_scan_tlist =
1721 fix_scan_list(root, cscan->custom_scan_tlist,
1722 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1723 }
1724 else
1725 {
1726 /* Adjust tlist, qual, custom_exprs in the standard way */
1727 cscan->scan.plan.targetlist =
1728 fix_scan_list(root, cscan->scan.plan.targetlist,
1729 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1730 cscan->scan.plan.qual =
1731 fix_scan_list(root, cscan->scan.plan.qual,
1732 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1733 cscan->custom_exprs =
1734 fix_scan_list(root, cscan->custom_exprs,
1735 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1736 }
1737
1738 /* Adjust child plan-nodes recursively, if needed */
1739 foreach(lc, cscan->custom_plans)
1740 {
1741 lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1742 }
1743
1744 cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1745}
1746
1747/*
1748 * register_partpruneinfo
1749 * Subroutine for set_append_references and set_mergeappend_references
1750 *
1751 * Add the PartitionPruneInfo from root->partPruneInfos at the given index
1752 * into PlannerGlobal->partPruneInfos and return its index there.
1753 *
1754 * Also update the RT indexes present in PartitionedRelPruneInfos to add the
1755 * offset.
1756 *
1757 * Finally, if there are initial pruning steps, add the RT indexes of the
1758 * leaf partitions to the set of relations that are prunable at execution
1759 * startup time.
1760 */
1761static int
1762register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
1763{
1764 PlannerGlobal *glob = root->glob;
1765 PartitionPruneInfo *pinfo;
1766 ListCell *l;
1767
1768 Assert(part_prune_index >= 0 &&
1769 part_prune_index < list_length(root->partPruneInfos));
1770 pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
1771 part_prune_index);
1772
1773 pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
1774 foreach(l, pinfo->prune_infos)
1775 {
1776 List *prune_infos = lfirst(l);
1777 ListCell *l2;
1778
1779 foreach(l2, prune_infos)
1780 {
1781 PartitionedRelPruneInfo *prelinfo = lfirst(l2);
1782 int i;
1783
1784 prelinfo->rtindex += rtoffset;
1785 prelinfo->initial_pruning_steps =
1787 rtoffset, 1);
1788 prelinfo->exec_pruning_steps =
1790 rtoffset, 1);
1791
1792 for (i = 0; i < prelinfo->nparts; i++)
1793 {
1794 /*
1795 * Non-leaf partitions and partitions that do not have a
1796 * subplan are not included in this map as mentioned in
1797 * make_partitionedrel_pruneinfo().
1798 */
1799 if (prelinfo->leafpart_rti_map[i])
1800 {
1801 prelinfo->leafpart_rti_map[i] += rtoffset;
1802 if (prelinfo->initial_pruning_steps)
1804 prelinfo->leafpart_rti_map[i]);
1805 }
1806 }
1807 }
1808 }
1809
1810 glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
1811
1812 return list_length(glob->partPruneInfos) - 1;
1813}
1814
1815/*
1816 * set_append_references
1817 * Do set_plan_references processing on an Append
1818 *
1819 * We try to strip out the Append entirely; if we can't, we have
1820 * to do the normal processing on it.
1821 */
1822static Plan *
1824 Append *aplan,
1825 int rtoffset)
1826{
1827 ListCell *l;
1828
1829 /*
1830 * Append, like Sort et al, doesn't actually evaluate its targetlist or
1831 * check quals. If it's got exactly one child plan, then it's not doing
1832 * anything useful at all, and we can strip it out.
1833 */
1834 Assert(aplan->plan.qual == NIL);
1835
1836 /* First, we gotta recurse on the children */
1837 foreach(l, aplan->appendplans)
1838 {
1839 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1840 }
1841
1842 /*
1843 * See if it's safe to get rid of the Append entirely. For this to be
1844 * safe, there must be only one child plan and that child plan's parallel
1845 * awareness must match the Append's. The reason for the latter is that
1846 * if the Append is parallel aware and the child is not, then the calling
1847 * plan may execute the non-parallel aware child multiple times. (If you
1848 * change these rules, update create_append_path to match.)
1849 */
1850 if (list_length(aplan->appendplans) == 1)
1851 {
1852 Plan *p = (Plan *) linitial(aplan->appendplans);
1853
1854 if (p->parallel_aware == aplan->plan.parallel_aware)
1855 return clean_up_removed_plan_level((Plan *) aplan, p);
1856 }
1857
1858 /*
1859 * Otherwise, clean up the Append as needed. It's okay to do this after
1860 * recursing to the children, because set_dummy_tlist_references doesn't
1861 * look at those.
1862 */
1863 set_dummy_tlist_references((Plan *) aplan, rtoffset);
1864
1865 aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1866
1867 /*
1868 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1869 * Also update the RT indexes present in it to add the offset.
1870 */
1871 if (aplan->part_prune_index >= 0)
1872 aplan->part_prune_index =
1873 register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
1874
1875 /* We don't need to recurse to lefttree or righttree ... */
1876 Assert(aplan->plan.lefttree == NULL);
1877 Assert(aplan->plan.righttree == NULL);
1878
1879 return (Plan *) aplan;
1880}
1881
1882/*
1883 * set_mergeappend_references
1884 * Do set_plan_references processing on a MergeAppend
1885 *
1886 * We try to strip out the MergeAppend entirely; if we can't, we have
1887 * to do the normal processing on it.
1888 */
1889static Plan *
1891 MergeAppend *mplan,
1892 int rtoffset)
1893{
1894 ListCell *l;
1895
1896 /*
1897 * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1898 * or check quals. If it's got exactly one child plan, then it's not
1899 * doing anything useful at all, and we can strip it out.
1900 */
1901 Assert(mplan->plan.qual == NIL);
1902
1903 /* First, we gotta recurse on the children */
1904 foreach(l, mplan->mergeplans)
1905 {
1906 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1907 }
1908
1909 /*
1910 * See if it's safe to get rid of the MergeAppend entirely. For this to
1911 * be safe, there must be only one child plan and that child plan's
1912 * parallel awareness must match the MergeAppend's. The reason for the
1913 * latter is that if the MergeAppend is parallel aware and the child is
1914 * not, then the calling plan may execute the non-parallel aware child
1915 * multiple times. (If you change these rules, update
1916 * create_merge_append_path to match.)
1917 */
1918 if (list_length(mplan->mergeplans) == 1)
1919 {
1920 Plan *p = (Plan *) linitial(mplan->mergeplans);
1921
1922 if (p->parallel_aware == mplan->plan.parallel_aware)
1923 return clean_up_removed_plan_level((Plan *) mplan, p);
1924 }
1925
1926 /*
1927 * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1928 * after recursing to the children, because set_dummy_tlist_references
1929 * doesn't look at those.
1930 */
1931 set_dummy_tlist_references((Plan *) mplan, rtoffset);
1932
1933 mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
1934
1935 /*
1936 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1937 * Also update the RT indexes present in it to add the offset.
1938 */
1939 if (mplan->part_prune_index >= 0)
1940 mplan->part_prune_index =
1941 register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
1942
1943 /* We don't need to recurse to lefttree or righttree ... */
1944 Assert(mplan->plan.lefttree == NULL);
1945 Assert(mplan->plan.righttree == NULL);
1946
1947 return (Plan *) mplan;
1948}
1949
1950/*
1951 * set_hash_references
1952 * Do set_plan_references processing on a Hash node
1953 */
1954static void
1956{
1957 Hash *hplan = (Hash *) plan;
1958 Plan *outer_plan = plan->lefttree;
1959 indexed_tlist *outer_itlist;
1960
1961 /*
1962 * Hash's hashkeys are used when feeding tuples into the hashtable,
1963 * therefore have them reference Hash's outer plan (which itself is the
1964 * inner plan of the HashJoin).
1965 */
1966 outer_itlist = build_tlist_index(outer_plan->targetlist);
1967 hplan->hashkeys = (List *)
1969 (Node *) hplan->hashkeys,
1970 outer_itlist,
1971 OUTER_VAR,
1972 rtoffset,
1973 NRM_EQUAL,
1975
1976 /* Hash doesn't project */
1978
1979 /* Hash nodes don't have their own quals */
1980 Assert(plan->qual == NIL);
1981}
1982
1983/*
1984 * offset_relid_set
1985 * Apply rtoffset to the members of a Relids set.
1986 */
1987static Relids
1988offset_relid_set(Relids relids, int rtoffset)
1989{
1990 Relids result = NULL;
1991 int rtindex;
1992
1993 /* If there's no offset to apply, we needn't recompute the value */
1994 if (rtoffset == 0)
1995 return relids;
1996 rtindex = -1;
1997 while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
1998 result = bms_add_member(result, rtindex + rtoffset);
1999 return result;
2000}
2001
2002/*
2003 * copyVar
2004 * Copy a Var node.
2005 *
2006 * fix_scan_expr and friends do this enough times that it's worth having
2007 * a bespoke routine instead of using the generic copyObject() function.
2008 */
2009static inline Var *
2011{
2012 Var *newvar = (Var *) palloc(sizeof(Var));
2013
2014 *newvar = *var;
2015 return newvar;
2016}
2017
2018/*
2019 * fix_expr_common
2020 * Do generic set_plan_references processing on an expression node
2021 *
2022 * This is code that is common to all variants of expression-fixing.
2023 * We must look up operator opcode info for OpExpr and related nodes,
2024 * add OIDs from regclass Const nodes into root->glob->relationOids, and
2025 * add PlanInvalItems for user-defined functions into root->glob->invalItems.
2026 * We also fill in column index lists for GROUPING() expressions.
2027 *
2028 * We assume it's okay to update opcode info in-place. So this could possibly
2029 * scribble on the planner's input data structures, but it's OK.
2030 */
2031static void
2033{
2034 /* We assume callers won't call us on a NULL pointer */
2035 if (IsA(node, Aggref))
2036 {
2038 ((Aggref *) node)->aggfnoid);
2039 }
2040 else if (IsA(node, WindowFunc))
2041 {
2043 ((WindowFunc *) node)->winfnoid);
2044 }
2045 else if (IsA(node, FuncExpr))
2046 {
2048 ((FuncExpr *) node)->funcid);
2049 }
2050 else if (IsA(node, OpExpr))
2051 {
2052 set_opfuncid((OpExpr *) node);
2054 ((OpExpr *) node)->opfuncid);
2055 }
2056 else if (IsA(node, DistinctExpr))
2057 {
2058 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2060 ((DistinctExpr *) node)->opfuncid);
2061 }
2062 else if (IsA(node, NullIfExpr))
2063 {
2064 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2066 ((NullIfExpr *) node)->opfuncid);
2067 }
2068 else if (IsA(node, ScalarArrayOpExpr))
2069 {
2070 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2071
2072 set_sa_opfuncid(saop);
2073 record_plan_function_dependency(root, saop->opfuncid);
2074
2075 if (OidIsValid(saop->hashfuncid))
2076 record_plan_function_dependency(root, saop->hashfuncid);
2077
2078 if (OidIsValid(saop->negfuncid))
2079 record_plan_function_dependency(root, saop->negfuncid);
2080 }
2081 else if (IsA(node, Const))
2082 {
2083 Const *con = (Const *) node;
2084
2085 /* Check for regclass reference */
2086 if (ISREGCLASSCONST(con))
2087 root->glob->relationOids =
2088 lappend_oid(root->glob->relationOids,
2089 DatumGetObjectId(con->constvalue));
2090 }
2091 else if (IsA(node, GroupingFunc))
2092 {
2093 GroupingFunc *g = (GroupingFunc *) node;
2094 AttrNumber *grouping_map = root->grouping_map;
2095
2096 /* If there are no grouping sets, we don't need this. */
2097
2098 Assert(grouping_map || g->cols == NIL);
2099
2100 if (grouping_map)
2101 {
2102 ListCell *lc;
2103 List *cols = NIL;
2104
2105 foreach(lc, g->refs)
2106 {
2107 cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2108 }
2109
2110 Assert(!g->cols || equal(cols, g->cols));
2111
2112 if (!g->cols)
2113 g->cols = cols;
2114 }
2115 }
2116}
2117
2118/*
2119 * fix_param_node
2120 * Do set_plan_references processing on a Param
2121 *
2122 * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
2123 * root->multiexpr_params; otherwise no change is needed.
2124 * Just for paranoia's sake, we make a copy of the node in either case.
2125 */
2126static Node *
2128{
2129 if (p->paramkind == PARAM_MULTIEXPR)
2130 {
2131 int subqueryid = p->paramid >> 16;
2132 int colno = p->paramid & 0xFFFF;
2133 List *params;
2134
2135 if (subqueryid <= 0 ||
2136 subqueryid > list_length(root->multiexpr_params))
2137 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2138 params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2139 if (colno <= 0 || colno > list_length(params))
2140 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2141 return copyObject(list_nth(params, colno - 1));
2142 }
2143 return (Node *) copyObject(p);
2144}
2145
2146/*
2147 * fix_alternative_subplan
2148 * Do set_plan_references processing on an AlternativeSubPlan
2149 *
2150 * Choose one of the alternative implementations and return just that one,
2151 * discarding the rest of the AlternativeSubPlan structure.
2152 * Note: caller must still recurse into the result!
2153 *
2154 * We don't make any attempt to fix up cost estimates in the parent plan
2155 * node or higher-level nodes.
2156 */
2157static Node *
2159 double num_exec)
2160{
2161 SubPlan *bestplan = NULL;
2162 Cost bestcost = 0;
2163 ListCell *lc;
2164
2165 /*
2166 * Compute the estimated cost of each subplan assuming num_exec
2167 * executions, and keep the cheapest one. In event of exact equality of
2168 * estimates, we prefer the later plan; this is a bit arbitrary, but in
2169 * current usage it biases us to break ties against fast-start subplans.
2170 */
2171 Assert(asplan->subplans != NIL);
2172
2173 foreach(lc, asplan->subplans)
2174 {
2175 SubPlan *curplan = (SubPlan *) lfirst(lc);
2176 Cost curcost;
2177
2178 curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
2179 if (bestplan == NULL || curcost <= bestcost)
2180 {
2181 bestplan = curplan;
2182 bestcost = curcost;
2183 }
2184
2185 /* Also mark all subplans that are in AlternativeSubPlans */
2186 root->isAltSubplan[curplan->plan_id - 1] = true;
2187 }
2188
2189 /* Mark the subplan we selected */
2190 root->isUsedSubplan[bestplan->plan_id - 1] = true;
2191
2192 return (Node *) bestplan;
2193}
2194
2195/*
2196 * fix_scan_expr
2197 * Do set_plan_references processing on a scan-level expression
2198 *
2199 * This consists of incrementing all Vars' varnos by rtoffset,
2200 * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
2201 * replacing Aggref nodes that should be replaced by initplan output Params,
2202 * choosing the best implementation for AlternativeSubPlans,
2203 * looking up operator opcode info for OpExpr and related nodes,
2204 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
2205 *
2206 * 'node': the expression to be modified
2207 * 'rtoffset': how much to increment varnos by
2208 * 'num_exec': estimated number of executions of expression
2209 *
2210 * The expression tree is either copied-and-modified, or modified in-place
2211 * if that seems safe.
2212 */
2213static Node *
2214fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
2215{
2216 fix_scan_expr_context context;
2217
2218 context.root = root;
2219 context.rtoffset = rtoffset;
2220 context.num_exec = num_exec;
2221
2222 if (rtoffset != 0 ||
2223 root->multiexpr_params != NIL ||
2224 root->glob->lastPHId != 0 ||
2225 root->minmax_aggs != NIL ||
2226 root->hasAlternativeSubPlans)
2227 {
2228 return fix_scan_expr_mutator(node, &context);
2229 }
2230 else
2231 {
2232 /*
2233 * If rtoffset == 0, we don't need to change any Vars, and if there
2234 * are no MULTIEXPR subqueries then we don't need to replace
2235 * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2236 * we won't need to remove them, and if there are no minmax Aggrefs we
2237 * won't need to replace them, and if there are no AlternativeSubPlans
2238 * we won't need to remove them. Then it's OK to just scribble on the
2239 * input node tree instead of copying (since the only change, filling
2240 * in any unset opfuncid fields, is harmless). This saves just enough
2241 * cycles to be noticeable on trivial queries.
2242 */
2243 (void) fix_scan_expr_walker(node, &context);
2244 return node;
2245 }
2246}
2247
2248static Node *
2250{
2251 if (node == NULL)
2252 return NULL;
2253 if (IsA(node, Var))
2254 {
2255 Var *var = copyVar((Var *) node);
2256
2257 Assert(var->varlevelsup == 0);
2258
2259 /*
2260 * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2261 * But an indexqual expression could contain INDEX_VAR Vars.
2262 */
2263 Assert(var->varno != INNER_VAR);
2264 Assert(var->varno != OUTER_VAR);
2265 Assert(var->varno != ROWID_VAR);
2266 if (!IS_SPECIAL_VARNO(var->varno))
2267 var->varno += context->rtoffset;
2268 if (var->varnosyn > 0)
2269 var->varnosyn += context->rtoffset;
2270 return (Node *) var;
2271 }
2272 if (IsA(node, Param))
2273 return fix_param_node(context->root, (Param *) node);
2274 if (IsA(node, Aggref))
2275 {
2276 Aggref *aggref = (Aggref *) node;
2277 Param *aggparam;
2278
2279 /* See if the Aggref should be replaced by a Param */
2280 aggparam = find_minmax_agg_replacement_param(context->root, aggref);
2281 if (aggparam != NULL)
2282 {
2283 /* Make a copy of the Param for paranoia's sake */
2284 return (Node *) copyObject(aggparam);
2285 }
2286 /* If no match, just fall through to process it normally */
2287 }
2288 if (IsA(node, CurrentOfExpr))
2289 {
2290 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2291
2292 Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2293 cexpr->cvarno += context->rtoffset;
2294 return (Node *) cexpr;
2295 }
2296 if (IsA(node, PlaceHolderVar))
2297 {
2298 /* At scan level, we should always just evaluate the contained expr */
2299 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2300
2301 /* XXX can we assert something about phnullingrels? */
2302 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2303 }
2304 if (IsA(node, AlternativeSubPlan))
2306 (AlternativeSubPlan *) node,
2307 context->num_exec),
2308 context);
2309 fix_expr_common(context->root, node);
2310 return expression_tree_mutator(node, fix_scan_expr_mutator, context);
2311}
2312
2313static bool
2315{
2316 if (node == NULL)
2317 return false;
2318 Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
2319 Assert(!IsA(node, PlaceHolderVar));
2320 Assert(!IsA(node, AlternativeSubPlan));
2321 fix_expr_common(context->root, node);
2322 return expression_tree_walker(node, fix_scan_expr_walker, context);
2323}
2324
2325/*
2326 * set_join_references
2327 * Modify the target list and quals of a join node to reference its
2328 * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
2329 * attno values to the result domain number of either the corresponding
2330 * outer or inner join tuple item. Also perform opcode lookup for these
2331 * expressions, and add regclass OIDs to root->glob->relationOids.
2332 */
2333static void
2335{
2336 Plan *outer_plan = join->plan.lefttree;
2337 Plan *inner_plan = join->plan.righttree;
2338 indexed_tlist *outer_itlist;
2339 indexed_tlist *inner_itlist;
2340
2341 outer_itlist = build_tlist_index(outer_plan->targetlist);
2342 inner_itlist = build_tlist_index(inner_plan->targetlist);
2343
2344 /*
2345 * First process the joinquals (including merge or hash clauses). These
2346 * are logically below the join so they can always use all values
2347 * available from the input tlists. It's okay to also handle
2348 * NestLoopParams now, because those couldn't refer to nullable
2349 * subexpressions.
2350 */
2351 join->joinqual = fix_join_expr(root,
2352 join->joinqual,
2353 outer_itlist,
2354 inner_itlist,
2355 (Index) 0,
2356 rtoffset,
2357 NRM_EQUAL,
2358 NUM_EXEC_QUAL((Plan *) join));
2359
2360 /* Now do join-type-specific stuff */
2361 if (IsA(join, NestLoop))
2362 {
2363 NestLoop *nl = (NestLoop *) join;
2364 ListCell *lc;
2365
2366 foreach(lc, nl->nestParams)
2367 {
2368 NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
2369
2370 /*
2371 * Because we don't reparameterize parameterized paths to match
2372 * the outer-join level at which they are used, Vars seen in the
2373 * NestLoopParam expression may have nullingrels that are just a
2374 * subset of those in the Vars actually available from the outer
2375 * side. (Lateral references can also cause this, as explained in
2376 * the comments for identify_current_nestloop_params.) Not
2377 * checking this exactly is a bit grotty, but the work needed to
2378 * make things match up perfectly seems well out of proportion to
2379 * the value.
2380 */
2381 nlp->paramval = (Var *) fix_upper_expr(root,
2382 (Node *) nlp->paramval,
2383 outer_itlist,
2384 OUTER_VAR,
2385 rtoffset,
2386 NRM_SUBSET,
2387 NUM_EXEC_TLIST(outer_plan));
2388 /* Check we replaced any PlaceHolderVar with simple Var */
2389 if (!(IsA(nlp->paramval, Var) &&
2390 nlp->paramval->varno == OUTER_VAR))
2391 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2392 }
2393 }
2394 else if (IsA(join, MergeJoin))
2395 {
2396 MergeJoin *mj = (MergeJoin *) join;
2397
2399 mj->mergeclauses,
2400 outer_itlist,
2401 inner_itlist,
2402 (Index) 0,
2403 rtoffset,
2404 NRM_EQUAL,
2405 NUM_EXEC_QUAL((Plan *) join));
2406 }
2407 else if (IsA(join, HashJoin))
2408 {
2409 HashJoin *hj = (HashJoin *) join;
2410
2412 hj->hashclauses,
2413 outer_itlist,
2414 inner_itlist,
2415 (Index) 0,
2416 rtoffset,
2417 NRM_EQUAL,
2418 NUM_EXEC_QUAL((Plan *) join));
2419
2420 /*
2421 * HashJoin's hashkeys are used to look for matching tuples from its
2422 * outer plan (not the Hash node!) in the hashtable.
2423 */
2424 hj->hashkeys = (List *) fix_upper_expr(root,
2425 (Node *) hj->hashkeys,
2426 outer_itlist,
2427 OUTER_VAR,
2428 rtoffset,
2429 NRM_EQUAL,
2430 NUM_EXEC_QUAL((Plan *) join));
2431 }
2432
2433 /*
2434 * Now we need to fix up the targetlist and qpqual, which are logically
2435 * above the join. This means that, if it's not an inner join, any Vars
2436 * and PHVs appearing here should have nullingrels that include the
2437 * effects of the outer join, ie they will have nullingrels equal to the
2438 * input Vars' nullingrels plus the bit added by the outer join. We don't
2439 * currently have enough info available here to identify what that should
2440 * be, so we just tell fix_join_expr to accept superset nullingrels
2441 * matches instead of exact ones.
2442 */
2443 join->plan.targetlist = fix_join_expr(root,
2444 join->plan.targetlist,
2445 outer_itlist,
2446 inner_itlist,
2447 (Index) 0,
2448 rtoffset,
2450 NUM_EXEC_TLIST((Plan *) join));
2451 join->plan.qual = fix_join_expr(root,
2452 join->plan.qual,
2453 outer_itlist,
2454 inner_itlist,
2455 (Index) 0,
2456 rtoffset,
2458 NUM_EXEC_QUAL((Plan *) join));
2459
2460 pfree(outer_itlist);
2461 pfree(inner_itlist);
2462}
2463
2464/*
2465 * set_upper_references
2466 * Update the targetlist and quals of an upper-level plan node
2467 * to refer to the tuples returned by its lefttree subplan.
2468 * Also perform opcode lookup for these expressions, and
2469 * add regclass OIDs to root->glob->relationOids.
2470 *
2471 * This is used for single-input plan types like Agg, Group, Result.
2472 *
2473 * In most cases, we have to match up individual Vars in the tlist and
2474 * qual expressions with elements of the subplan's tlist (which was
2475 * generated by flattening these selfsame expressions, so it should have all
2476 * the required variables). There is an important exception, however:
2477 * depending on where we are in the plan tree, sort/group columns may have
2478 * been pushed into the subplan tlist unflattened. If these values are also
2479 * needed in the output then we want to reference the subplan tlist element
2480 * rather than recomputing the expression.
2481 */
2482static void
2484{
2485 Plan *subplan = plan->lefttree;
2486 indexed_tlist *subplan_itlist;
2487 List *output_targetlist;
2488 ListCell *l;
2489
2490 subplan_itlist = build_tlist_index(subplan->targetlist);
2491
2492 /*
2493 * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2494 * in the targetlist and quals should have nullingrels that include the
2495 * effects of the grouping step, ie they will have nullingrels equal to
2496 * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2497 * step. In order to perform exact nullingrels matches, we remove the RT
2498 * index of the grouping step first.
2499 */
2500 if (IsA(plan, Agg) &&
2501 root->group_rtindex > 0 &&
2502 ((Agg *) plan)->groupingSets)
2503 {
2504 plan->targetlist = (List *)
2505 remove_nulling_relids((Node *) plan->targetlist,
2506 bms_make_singleton(root->group_rtindex),
2507 NULL);
2508 plan->qual = (List *)
2510 bms_make_singleton(root->group_rtindex),
2511 NULL);
2512 }
2513
2514 output_targetlist = NIL;
2515 foreach(l, plan->targetlist)
2516 {
2517 TargetEntry *tle = (TargetEntry *) lfirst(l);
2518 Node *newexpr;
2519
2520 /* If it's a sort/group item, first try to match by sortref */
2521 if (tle->ressortgroupref != 0)
2522 {
2523 newexpr = (Node *)
2525 tle->ressortgroupref,
2526 subplan_itlist,
2527 OUTER_VAR);
2528 if (!newexpr)
2529 newexpr = fix_upper_expr(root,
2530 (Node *) tle->expr,
2531 subplan_itlist,
2532 OUTER_VAR,
2533 rtoffset,
2534 NRM_EQUAL,
2536 }
2537 else
2538 newexpr = fix_upper_expr(root,
2539 (Node *) tle->expr,
2540 subplan_itlist,
2541 OUTER_VAR,
2542 rtoffset,
2543 NRM_EQUAL,
2545 tle = flatCopyTargetEntry(tle);
2546 tle->expr = (Expr *) newexpr;
2547 output_targetlist = lappend(output_targetlist, tle);
2548 }
2549 plan->targetlist = output_targetlist;
2550
2551 plan->qual = (List *)
2553 (Node *) plan->qual,
2554 subplan_itlist,
2555 OUTER_VAR,
2556 rtoffset,
2557 NRM_EQUAL,
2559
2560 pfree(subplan_itlist);
2561}
2562
2563/*
2564 * set_param_references
2565 * Initialize the initParam list in Gather or Gather merge node such that
2566 * it contains reference of all the params that needs to be evaluated
2567 * before execution of the node. It contains the initplan params that are
2568 * being passed to the plan nodes below it.
2569 */
2570static void
2572{
2574
2575 if (plan->lefttree->extParam)
2576 {
2577 PlannerInfo *proot;
2578 Bitmapset *initSetParam = NULL;
2579 ListCell *l;
2580
2581 for (proot = root; proot != NULL; proot = proot->parent_root)
2582 {
2583 foreach(l, proot->init_plans)
2584 {
2585 SubPlan *initsubplan = (SubPlan *) lfirst(l);
2586 ListCell *l2;
2587
2588 foreach(l2, initsubplan->setParam)
2589 {
2590 initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2591 }
2592 }
2593 }
2594
2595 /*
2596 * Remember the list of all external initplan params that are used by
2597 * the children of Gather or Gather merge node.
2598 */
2599 if (IsA(plan, Gather))
2600 ((Gather *) plan)->initParam =
2601 bms_intersect(plan->lefttree->extParam, initSetParam);
2602 else
2603 ((GatherMerge *) plan)->initParam =
2604 bms_intersect(plan->lefttree->extParam, initSetParam);
2605 }
2606}
2607
2608/*
2609 * Recursively scan an expression tree and convert Aggrefs to the proper
2610 * intermediate form for combining aggregates. This means (1) replacing each
2611 * one's argument list with a single argument that is the original Aggref
2612 * modified to show partial aggregation and (2) changing the upper Aggref to
2613 * show combining aggregation.
2614 *
2615 * After this step, set_upper_references will replace the partial Aggrefs
2616 * with Vars referencing the lower Agg plan node's outputs, so that the final
2617 * form seen by the executor is a combining Aggref with a Var as input.
2618 *
2619 * It's rather messy to postpone this step until setrefs.c; ideally it'd be
2620 * done in createplan.c. The difficulty is that once we modify the Aggref
2621 * expressions, they will no longer be equal() to their original form and
2622 * so cross-plan-node-level matches will fail. So this has to happen after
2623 * the plan node above the Agg has resolved its subplan references.
2624 */
2625static Node *
2626convert_combining_aggrefs(Node *node, void *context)
2627{
2628 if (node == NULL)
2629 return NULL;
2630 if (IsA(node, Aggref))
2631 {
2632 Aggref *orig_agg = (Aggref *) node;
2633 Aggref *child_agg;
2634 Aggref *parent_agg;
2635
2636 /* Assert we've not chosen to partial-ize any unsupported cases */
2637 Assert(orig_agg->aggorder == NIL);
2638 Assert(orig_agg->aggdistinct == NIL);
2639
2640 /*
2641 * Since aggregate calls can't be nested, we needn't recurse into the
2642 * arguments. But for safety, flat-copy the Aggref node itself rather
2643 * than modifying it in-place.
2644 */
2645 child_agg = makeNode(Aggref);
2646 memcpy(child_agg, orig_agg, sizeof(Aggref));
2647
2648 /*
2649 * For the parent Aggref, we want to copy all the fields of the
2650 * original aggregate *except* the args list, which we'll replace
2651 * below, and the aggfilter expression, which should be applied only
2652 * by the child not the parent. Rather than explicitly knowing about
2653 * all the other fields here, we can momentarily modify child_agg to
2654 * provide a suitable source for copyObject.
2655 */
2656 child_agg->args = NIL;
2657 child_agg->aggfilter = NULL;
2658 parent_agg = copyObject(child_agg);
2659 child_agg->args = orig_agg->args;
2660 child_agg->aggfilter = orig_agg->aggfilter;
2661
2662 /*
2663 * Now, set up child_agg to represent the first phase of partial
2664 * aggregation. For now, assume serialization is required.
2665 */
2667
2668 /*
2669 * And set up parent_agg to represent the second phase.
2670 */
2671 parent_agg->args = list_make1(makeTargetEntry((Expr *) child_agg,
2672 1, NULL, false));
2674
2675 return (Node *) parent_agg;
2676 }
2678}
2679
2680/*
2681 * set_dummy_tlist_references
2682 * Replace the targetlist of an upper-level plan node with a simple
2683 * list of OUTER_VAR references to its child.
2684 *
2685 * This is used for plan types like Sort and Append that don't evaluate
2686 * their targetlists. Although the executor doesn't care at all what's in
2687 * the tlist, EXPLAIN needs it to be realistic.
2688 *
2689 * Note: we could almost use set_upper_references() here, but it fails for
2690 * Append for lack of a lefttree subplan. Single-purpose code is faster
2691 * anyway.
2692 */
2693static void
2695{
2696 List *output_targetlist;
2697 ListCell *l;
2698
2699 output_targetlist = NIL;
2700 foreach(l, plan->targetlist)
2701 {
2702 TargetEntry *tle = (TargetEntry *) lfirst(l);
2703 Var *oldvar = (Var *) tle->expr;
2704 Var *newvar;
2705
2706 /*
2707 * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2708 * as Consts, not Vars referencing Consts. Here, there's no speed
2709 * advantage to be had, but it makes EXPLAIN output look cleaner, and
2710 * again it avoids confusing the executor.
2711 */
2712 if (IsA(oldvar, Const))
2713 {
2714 /* just reuse the existing TLE node */
2715 output_targetlist = lappend(output_targetlist, tle);
2716 continue;
2717 }
2718
2719 newvar = makeVar(OUTER_VAR,
2720 tle->resno,
2721 exprType((Node *) oldvar),
2722 exprTypmod((Node *) oldvar),
2723 exprCollation((Node *) oldvar),
2724 0);
2725 if (IsA(oldvar, Var) &&
2726 oldvar->varnosyn > 0)
2727 {
2728 newvar->varnosyn = oldvar->varnosyn + rtoffset;
2729 newvar->varattnosyn = oldvar->varattnosyn;
2730 }
2731 else
2732 {
2733 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2734 newvar->varattnosyn = 0;
2735 }
2736
2737 tle = flatCopyTargetEntry(tle);
2738 tle->expr = (Expr *) newvar;
2739 output_targetlist = lappend(output_targetlist, tle);
2740 }
2741 plan->targetlist = output_targetlist;
2742
2743 /* We don't touch plan->qual here */
2744}
2745
2746
2747/*
2748 * build_tlist_index --- build an index data structure for a child tlist
2749 *
2750 * In most cases, subplan tlists will be "flat" tlists with only Vars,
2751 * so we try to optimize that case by extracting information about Vars
2752 * in advance. Matching a parent tlist to a child is still an O(N^2)
2753 * operation, but at least with a much smaller constant factor than plain
2754 * tlist_member() searches.
2755 *
2756 * The result of this function is an indexed_tlist struct to pass to
2757 * search_indexed_tlist_for_var() and siblings.
2758 * When done, the indexed_tlist may be freed with a single pfree().
2759 */
2760static indexed_tlist *
2762{
2763 indexed_tlist *itlist;
2764 tlist_vinfo *vinfo;
2765 ListCell *l;
2766
2767 /* Create data structure with enough slots for all tlist entries */
2768 itlist = (indexed_tlist *)
2769 palloc(offsetof(indexed_tlist, vars) +
2770 list_length(tlist) * sizeof(tlist_vinfo));
2771
2772 itlist->tlist = tlist;
2773 itlist->has_ph_vars = false;
2774 itlist->has_non_vars = false;
2775
2776 /* Find the Vars and fill in the index array */
2777 vinfo = itlist->vars;
2778 foreach(l, tlist)
2779 {
2780 TargetEntry *tle = (TargetEntry *) lfirst(l);
2781
2782 if (tle->expr && IsA(tle->expr, Var))
2783 {
2784 Var *var = (Var *) tle->expr;
2785
2786 vinfo->varno = var->varno;
2787 vinfo->varattno = var->varattno;
2788 vinfo->resno = tle->resno;
2789 vinfo->varnullingrels = var->varnullingrels;
2790 vinfo++;
2791 }
2792 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2793 itlist->has_ph_vars = true;
2794 else
2795 itlist->has_non_vars = true;
2796 }
2797
2798 itlist->num_vars = (vinfo - itlist->vars);
2799
2800 return itlist;
2801}
2802
2803/*
2804 * build_tlist_index_other_vars --- build a restricted tlist index
2805 *
2806 * This is like build_tlist_index, but we only index tlist entries that
2807 * are Vars belonging to some rel other than the one specified. We will set
2808 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
2809 * (so nothing other than Vars and PlaceHolderVars can be matched).
2810 */
2811static indexed_tlist *
2812build_tlist_index_other_vars(List *tlist, int ignore_rel)
2813{
2814 indexed_tlist *itlist;
2815 tlist_vinfo *vinfo;
2816 ListCell *l;
2817
2818 /* Create data structure with enough slots for all tlist entries */
2819 itlist = (indexed_tlist *)
2820 palloc(offsetof(indexed_tlist, vars) +
2821 list_length(tlist) * sizeof(tlist_vinfo));
2822
2823 itlist->tlist = tlist;
2824 itlist->has_ph_vars = false;
2825 itlist->has_non_vars = false;
2826
2827 /* Find the desired Vars and fill in the index array */
2828 vinfo = itlist->vars;
2829 foreach(l, tlist)
2830 {
2831 TargetEntry *tle = (TargetEntry *) lfirst(l);
2832
2833 if (tle->expr && IsA(tle->expr, Var))
2834 {
2835 Var *var = (Var *) tle->expr;
2836
2837 if (var->varno != ignore_rel)
2838 {
2839 vinfo->varno = var->varno;
2840 vinfo->varattno = var->varattno;
2841 vinfo->resno = tle->resno;
2842 vinfo->varnullingrels = var->varnullingrels;
2843 vinfo++;
2844 }
2845 }
2846 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2847 itlist->has_ph_vars = true;
2848 }
2849
2850 itlist->num_vars = (vinfo - itlist->vars);
2851
2852 return itlist;
2853}
2854
2855/*
2856 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
2857 *
2858 * If a match is found, return a copy of the given Var with suitably
2859 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
2860 * Also ensure that varnosyn is incremented by rtoffset.
2861 * If no match, return NULL.
2862 *
2863 * We cross-check the varnullingrels of the subplan output Var based on
2864 * nrm_match. Most call sites should pass NRM_EQUAL indicating we expect
2865 * an exact match. However, there are places where we haven't cleaned
2866 * things up completely, and we have to settle for allowing subset or
2867 * superset matches.
2868 */
2869static Var *
2871 int newvarno, int rtoffset,
2872 NullingRelsMatch nrm_match)
2873{
2874 int varno = var->varno;
2875 AttrNumber varattno = var->varattno;
2876 tlist_vinfo *vinfo;
2877 int i;
2878
2879 vinfo = itlist->vars;
2880 i = itlist->num_vars;
2881 while (i-- > 0)
2882 {
2883 if (vinfo->varno == varno && vinfo->varattno == varattno)
2884 {
2885 /* Found a match */
2886 Var *newvar = copyVar(var);
2887
2888 /*
2889 * Verify that we kept all the nullingrels machinations straight.
2890 *
2891 * XXX we skip the check for system columns and whole-row Vars.
2892 * That's because such Vars might be row identity Vars, which are
2893 * generated without any varnullingrels. It'd be hard to do
2894 * otherwise, since they're normally made very early in planning,
2895 * when we haven't looked at the jointree yet and don't know which
2896 * joins might null such Vars. Doesn't seem worth the expense to
2897 * make them fully valid. (While it's slightly annoying that we
2898 * thereby lose checking for user-written references to such
2899 * columns, it seems unlikely that a bug in nullingrels logic
2900 * would affect only system columns.)
2901 */
2902 if (!(varattno <= 0 ||
2903 (nrm_match == NRM_SUBSET ?
2904 bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2905 nrm_match == NRM_SUPERSET ?
2906 bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2907 bms_equal(vinfo->varnullingrels, var->varnullingrels))))
2908 elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2909 bmsToString(var->varnullingrels),
2911 varno, varattno);
2912
2913 newvar->varno = newvarno;
2914 newvar->varattno = vinfo->resno;
2915 if (newvar->varnosyn > 0)
2916 newvar->varnosyn += rtoffset;
2917 return newvar;
2918 }
2919 vinfo++;
2920 }
2921 return NULL; /* no match */
2922}
2923
2924/*
2925 * search_indexed_tlist_for_phv --- find a PlaceHolderVar in an indexed tlist
2926 *
2927 * If a match is found, return a Var constructed to reference the tlist item.
2928 * If no match, return NULL.
2929 *
2930 * Cross-check phnullingrels as in search_indexed_tlist_for_var.
2931 *
2932 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars.
2933 */
2934static Var *
2936 indexed_tlist *itlist, int newvarno,
2937 NullingRelsMatch nrm_match)
2938{
2939 ListCell *lc;
2940
2941 foreach(lc, itlist->tlist)
2942 {
2943 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2944
2945 if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2946 {
2947 PlaceHolderVar *subphv = (PlaceHolderVar *) tle->expr;
2948 Var *newvar;
2949
2950 /*
2951 * Analogously to search_indexed_tlist_for_var, we match on phid
2952 * only. We don't use equal(), partially for speed but mostly
2953 * because phnullingrels might not be exactly equal.
2954 */
2955 if (phv->phid != subphv->phid)
2956 continue;
2957
2958 /* Verify that we kept all the nullingrels machinations straight */
2959 if (!(nrm_match == NRM_SUBSET ?
2961 nrm_match == NRM_SUPERSET ?
2963 bms_equal(subphv->phnullingrels, phv->phnullingrels)))
2964 elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
2966 bmsToString(subphv->phnullingrels),
2967 phv->phid);
2968
2969 /* Found a matching subplan output expression */
2970 newvar = makeVarFromTargetEntry(newvarno, tle);
2971 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2972 newvar->varattnosyn = 0;
2973 return newvar;
2974 }
2975 }
2976 return NULL; /* no match */
2977}
2978
2979/*
2980 * search_indexed_tlist_for_non_var --- find a non-Var/PHV in an indexed tlist
2981 *
2982 * If a match is found, return a Var constructed to reference the tlist item.
2983 * If no match, return NULL.
2984 *
2985 * NOTE: it is a waste of time to call this unless itlist->has_non_vars.
2986 */
2987static Var *
2989 indexed_tlist *itlist, int newvarno)
2990{
2991 TargetEntry *tle;
2992
2993 /*
2994 * If it's a simple Const, replacing it with a Var is silly, even if there
2995 * happens to be an identical Const below; a Var is more expensive to
2996 * execute than a Const. What's more, replacing it could confuse some
2997 * places in the executor that expect to see simple Consts for, eg,
2998 * dropped columns.
2999 */
3000 if (IsA(node, Const))
3001 return NULL;
3002
3003 tle = tlist_member(node, itlist->tlist);
3004 if (tle)
3005 {
3006 /* Found a matching subplan output expression */
3007 Var *newvar;
3008
3009 newvar = makeVarFromTargetEntry(newvarno, tle);
3010 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3011 newvar->varattnosyn = 0;
3012 return newvar;
3013 }
3014 return NULL; /* no match */
3015}
3016
3017/*
3018 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
3019 *
3020 * If a match is found, return a Var constructed to reference the tlist item.
3021 * If no match, return NULL.
3022 *
3023 * This is needed to ensure that we select the right subplan TLE in cases
3024 * where there are multiple textually-equal()-but-volatile sort expressions.
3025 * And it's also faster than search_indexed_tlist_for_non_var.
3026 */
3027static Var *
3029 Index sortgroupref,
3030 indexed_tlist *itlist,
3031 int newvarno)
3032{
3033 ListCell *lc;
3034
3035 foreach(lc, itlist->tlist)
3036 {
3037 TargetEntry *tle = (TargetEntry *) lfirst(lc);
3038
3039 /*
3040 * Usually the equal() check is redundant, but in setop plans it may
3041 * not be, since prepunion.c assigns ressortgroupref equal to the
3042 * column resno without regard to whether that matches the topmost
3043 * level's sortgrouprefs and without regard to whether any implicit
3044 * coercions are added in the setop tree. We might have to clean that
3045 * up someday; but for now, just ignore any false matches.
3046 */
3047 if (tle->ressortgroupref == sortgroupref &&
3048 equal(node, tle->expr))
3049 {
3050 /* Found a matching subplan output expression */
3051 Var *newvar;
3052
3053 newvar = makeVarFromTargetEntry(newvarno, tle);
3054 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3055 newvar->varattnosyn = 0;
3056 return newvar;
3057 }
3058 }
3059 return NULL; /* no match */
3060}
3061
3062/*
3063 * fix_join_expr
3064 * Create a new set of targetlist entries or join qual clauses by
3065 * changing the varno/varattno values of variables in the clauses
3066 * to reference target list values from the outer and inner join
3067 * relation target lists. Also perform opcode lookup and add
3068 * regclass OIDs to root->glob->relationOids.
3069 *
3070 * This is used in four different scenarios:
3071 * 1) a normal join clause, where all the Vars in the clause *must* be
3072 * replaced by OUTER_VAR or INNER_VAR references. In this case
3073 * acceptable_rel should be zero so that any failure to match a Var will be
3074 * reported as an error.
3075 * 2) RETURNING clauses, which may contain both Vars of the target relation
3076 * and Vars of other relations. In this case we want to replace the
3077 * other-relation Vars by OUTER_VAR references, while leaving target Vars
3078 * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
3079 * target relation should be passed.
3080 * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are
3081 * to be replaced with INNER_VAR references, while leaving target Vars (the
3082 * to-be-updated relation) alone. Correspondingly inner_itlist is to be
3083 * EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
3084 * relation.
3085 * 4) MERGE. In this case, references to the source relation are to be
3086 * replaced with INNER_VAR references, leaving Vars of the target
3087 * relation (the to-be-modified relation) alone. So inner_itlist is to be
3088 * the source relation elements, outer_itlist = NULL and acceptable_rel
3089 * the target relation.
3090 *
3091 * 'clauses' is the targetlist or list of join clauses
3092 * 'outer_itlist' is the indexed target list of the outer join relation,
3093 * or NULL
3094 * 'inner_itlist' is the indexed target list of the inner join relation,
3095 * or NULL
3096 * 'acceptable_rel' is either zero or the rangetable index of a relation
3097 * whose Vars may appear in the clause without provoking an error
3098 * 'rtoffset': how much to increment varnos by
3099 * 'nrm_match': as for search_indexed_tlist_for_var()
3100 * 'num_exec': estimated number of executions of expression
3101 *
3102 * Returns the new expression tree. The original clause structure is
3103 * not modified.
3104 */
3105static List *
3107 List *clauses,
3108 indexed_tlist *outer_itlist,
3109 indexed_tlist *inner_itlist,
3110 Index acceptable_rel,
3111 int rtoffset,
3112 NullingRelsMatch nrm_match,
3113 double num_exec)
3114{
3115 fix_join_expr_context context;
3116
3117 context.root = root;
3118 context.outer_itlist = outer_itlist;
3119 context.inner_itlist = inner_itlist;
3120 context.acceptable_rel = acceptable_rel;
3121 context.rtoffset = rtoffset;
3122 context.nrm_match = nrm_match;
3123 context.num_exec = num_exec;
3124 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3125}
3126
3127static Node *
3129{
3130 Var *newvar;
3131
3132 if (node == NULL)
3133 return NULL;
3134 if (IsA(node, Var))
3135 {
3136 Var *var = (Var *) node;
3137
3138 /*
3139 * Verify that Vars with non-default varreturningtype only appear in
3140 * the RETURNING list, and refer to the target relation.
3141 */
3143 {
3144 if (context->inner_itlist != NULL ||
3145 context->outer_itlist == NULL ||
3146 context->acceptable_rel == 0)
3147 elog(ERROR, "variable returning old/new found outside RETURNING list");
3148 if (var->varno != context->acceptable_rel)
3149 elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
3150 var->varno, context->acceptable_rel);
3151 }
3152
3153 /* Look for the var in the input tlists, first in the outer */
3154 if (context->outer_itlist)
3155 {
3156 newvar = search_indexed_tlist_for_var(var,
3157 context->outer_itlist,
3158 OUTER_VAR,
3159 context->rtoffset,
3160 context->nrm_match);
3161 if (newvar)
3162 return (Node *) newvar;
3163 }
3164
3165 /* then in the inner. */
3166 if (context->inner_itlist)
3167 {
3168 newvar = search_indexed_tlist_for_var(var,
3169 context->inner_itlist,
3170 INNER_VAR,
3171 context->rtoffset,
3172 context->nrm_match);
3173 if (newvar)
3174 return (Node *) newvar;
3175 }
3176
3177 /* If it's for acceptable_rel, adjust and return it */
3178 if (var->varno == context->acceptable_rel)
3179 {
3180 var = copyVar(var);
3181 var->varno += context->rtoffset;
3182 if (var->varnosyn > 0)
3183 var->varnosyn += context->rtoffset;
3184 return (Node *) var;
3185 }
3186
3187 /* No referent found for Var */
3188 elog(ERROR, "variable not found in subplan target lists");
3189 }
3190 if (IsA(node, PlaceHolderVar))
3191 {
3192 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3193
3194 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3195 if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3196 {
3197 newvar = search_indexed_tlist_for_phv(phv,
3198 context->outer_itlist,
3199 OUTER_VAR,
3200 context->nrm_match);
3201 if (newvar)
3202 return (Node *) newvar;
3203 }
3204 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3205 {
3206 newvar = search_indexed_tlist_for_phv(phv,
3207 context->inner_itlist,
3208 INNER_VAR,
3209 context->nrm_match);
3210 if (newvar)
3211 return (Node *) newvar;
3212 }
3213
3214 /* If not supplied by input plans, evaluate the contained expr */
3215 /* XXX can we assert something about phnullingrels? */
3216 return fix_join_expr_mutator((Node *) phv->phexpr, context);
3217 }
3218 /* Try matching more complex expressions too, if tlists have any */
3219 if (context->outer_itlist && context->outer_itlist->has_non_vars)
3220 {
3221 newvar = search_indexed_tlist_for_non_var((Expr *) node,
3222 context->outer_itlist,
3223 OUTER_VAR);
3224 if (newvar)
3225 return (Node *) newvar;
3226 }
3227 if (context->inner_itlist && context->inner_itlist->has_non_vars)
3228 {
3229 newvar = search_indexed_tlist_for_non_var((Expr *) node,
3230 context->inner_itlist,
3231 INNER_VAR);
3232 if (newvar)
3233 return (Node *) newvar;
3234 }
3235 /* Special cases (apply only AFTER failing to match to lower tlist) */
3236 if (IsA(node, Param))
3237 return fix_param_node(context->root, (Param *) node);
3238 if (IsA(node, AlternativeSubPlan))
3240 (AlternativeSubPlan *) node,
3241 context->num_exec),
3242 context);
3243 fix_expr_common(context->root, node);
3244 return expression_tree_mutator(node, fix_join_expr_mutator, context);
3245}
3246
3247/*
3248 * fix_upper_expr
3249 * Modifies an expression tree so that all Var nodes reference outputs
3250 * of a subplan. Also looks for Aggref nodes that should be replaced
3251 * by initplan output Params. Also performs opcode lookup, and adds
3252 * regclass OIDs to root->glob->relationOids.
3253 *
3254 * This is used to fix up target and qual expressions of non-join upper-level
3255 * plan nodes, as well as index-only scan nodes.
3256 *
3257 * An error is raised if no matching var can be found in the subplan tlist
3258 * --- so this routine should only be applied to nodes whose subplans'
3259 * targetlists were generated by flattening the expressions used in the
3260 * parent node.
3261 *
3262 * If itlist->has_non_vars is true, then we try to match whole subexpressions
3263 * against elements of the subplan tlist, so that we can avoid recomputing
3264 * expressions that were already computed by the subplan. (This is relatively
3265 * expensive, so we don't want to try it in the common case where the
3266 * subplan tlist is just a flattened list of Vars.)
3267 *
3268 * 'node': the tree to be fixed (a target item or qual)
3269 * 'subplan_itlist': indexed target list for subplan (or index)
3270 * 'newvarno': varno to use for Vars referencing tlist elements
3271 * 'rtoffset': how much to increment varnos by
3272 * 'nrm_match': as for search_indexed_tlist_for_var()
3273 * 'num_exec': estimated number of executions of expression
3274 *
3275 * The resulting tree is a copy of the original in which all Var nodes have
3276 * varno = newvarno, varattno = resno of corresponding targetlist element.
3277 * The original tree is not modified.
3278 */
3279static Node *
3281 Node *node,
3282 indexed_tlist *subplan_itlist,
3283 int newvarno,
3284 int rtoffset,
3285 NullingRelsMatch nrm_match,
3286 double num_exec)
3287{
3288 fix_upper_expr_context context;
3289
3290 context.root = root;
3291 context.subplan_itlist = subplan_itlist;
3292 context.newvarno = newvarno;
3293 context.rtoffset = rtoffset;
3294 context.nrm_match = nrm_match;
3295 context.num_exec = num_exec;
3296 return fix_upper_expr_mutator(node, &context);
3297}
3298
3299static Node *
3301{
3302 Var *newvar;
3303
3304 if (node == NULL)
3305 return NULL;
3306 if (IsA(node, Var))
3307 {
3308 Var *var = (Var *) node;
3309
3310 newvar = search_indexed_tlist_for_var(var,
3311 context->subplan_itlist,
3312 context->newvarno,
3313 context->rtoffset,
3314 context->nrm_match);
3315 if (!newvar)
3316 elog(ERROR, "variable not found in subplan target list");
3317 return (Node *) newvar;
3318 }
3319 if (IsA(node, PlaceHolderVar))
3320 {
3321 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3322
3323 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3324 if (context->subplan_itlist->has_ph_vars)
3325 {
3326 newvar = search_indexed_tlist_for_phv(phv,
3327 context->subplan_itlist,
3328 context->newvarno,
3329 context->nrm_match);
3330 if (newvar)
3331 return (Node *) newvar;
3332 }
3333 /* If not supplied by input plan, evaluate the contained expr */
3334 /* XXX can we assert something about phnullingrels? */
3335 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3336 }
3337 /* Try matching more complex expressions too, if tlist has any */
3338 if (context->subplan_itlist->has_non_vars)
3339 {
3340 newvar = search_indexed_tlist_for_non_var((Expr *) node,
3341 context->subplan_itlist,
3342 context->newvarno);
3343 if (newvar)
3344 return (Node *) newvar;
3345 }
3346 /* Special cases (apply only AFTER failing to match to lower tlist) */
3347 if (IsA(node, Param))
3348 return fix_param_node(context->root, (Param *) node);
3349 if (IsA(node, Aggref))
3350 {
3351 Aggref *aggref = (Aggref *) node;
3352 Param *aggparam;
3353
3354 /* See if the Aggref should be replaced by a Param */
3355 aggparam = find_minmax_agg_replacement_param(context->root, aggref);
3356 if (aggparam != NULL)
3357 {
3358 /* Make a copy of the Param for paranoia's sake */
3359 return (Node *) copyObject(aggparam);
3360 }
3361 /* If no match, just fall through to process it normally */
3362 }
3363 if (IsA(node, AlternativeSubPlan))
3365 (AlternativeSubPlan *) node,
3366 context->num_exec),
3367 context);
3368 fix_expr_common(context->root, node);
3369 return expression_tree_mutator(node, fix_upper_expr_mutator, context);
3370}
3371
3372/*
3373 * set_returning_clause_references
3374 * Perform setrefs.c's work on a RETURNING targetlist
3375 *
3376 * If the query involves more than just the result table, we have to
3377 * adjust any Vars that refer to other tables to reference junk tlist
3378 * entries in the top subplan's targetlist. Vars referencing the result
3379 * table should be left alone, however (the executor will evaluate them
3380 * using the actual heap tuple, after firing triggers if any). In the
3381 * adjusted RETURNING list, result-table Vars will have their original
3382 * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
3383 *
3384 * We also must perform opcode lookup and add regclass OIDs to
3385 * root->glob->relationOids.
3386 *
3387 * 'rlist': the RETURNING targetlist to be fixed
3388 * 'topplan': the top subplan node that will be just below the ModifyTable
3389 * node (note it's not yet passed through set_plan_refs)
3390 * 'resultRelation': RT index of the associated result relation
3391 * 'rtoffset': how much to increment varnos by
3392 *
3393 * Note: the given 'root' is for the parent query level, not the 'topplan'.
3394 * This does not matter currently since we only access the dependency-item
3395 * lists in root->glob, but it would need some hacking if we wanted a root
3396 * that actually matches the subplan.
3397 *
3398 * Note: resultRelation is not yet adjusted by rtoffset.
3399 */
3400static List *
3402 List *rlist,
3403 Plan *topplan,
3404 Index resultRelation,
3405 int rtoffset)
3406{
3407 indexed_tlist *itlist;
3408
3409 /*
3410 * We can perform the desired Var fixup by abusing the fix_join_expr
3411 * machinery that formerly handled inner indexscan fixup. We search the
3412 * top plan's targetlist for Vars of non-result relations, and use
3413 * fix_join_expr to convert RETURNING Vars into references to those tlist
3414 * entries, while leaving result-rel Vars as-is.
3415 *
3416 * PlaceHolderVars will also be sought in the targetlist, but no
3417 * more-complex expressions will be. Note that it is not possible for a
3418 * PlaceHolderVar to refer to the result relation, since the result is
3419 * never below an outer join. If that case could happen, we'd have to be
3420 * prepared to pick apart the PlaceHolderVar and evaluate its contained
3421 * expression instead.
3422 */
3423 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3424
3425 rlist = fix_join_expr(root,
3426 rlist,
3427 itlist,
3428 NULL,
3429 resultRelation,
3430 rtoffset,
3431 NRM_EQUAL,
3432 NUM_EXEC_TLIST(topplan));
3433
3434 pfree(itlist);
3435
3436 return rlist;
3437}
3438
3439/*
3440 * fix_windowagg_condition_expr_mutator
3441 * Mutator function for replacing WindowFuncs with the corresponding Var
3442 * in the targetlist which references that WindowFunc.
3443 */
3444static Node *
3447{
3448 if (node == NULL)
3449 return NULL;
3450
3451 if (IsA(node, WindowFunc))
3452 {
3453 Var *newvar;
3454
3455 newvar = search_indexed_tlist_for_non_var((Expr *) node,
3456 context->subplan_itlist,
3457 context->newvarno);
3458 if (newvar)
3459 return (Node *) newvar;
3460 elog(ERROR, "WindowFunc not found in subplan target lists");
3461 }
3462
3463 return expression_tree_mutator(node,
3465 context);
3466}
3467
3468/*
3469 * fix_windowagg_condition_expr
3470 * Converts references in 'runcondition' so that any WindowFunc
3471 * references are swapped out for a Var which references the matching
3472 * WindowFunc in 'subplan_itlist'.
3473 */
3474static List *
3476 List *runcondition,
3477 indexed_tlist *subplan_itlist)
3478{
3480
3481 context.root = root;
3482 context.subplan_itlist = subplan_itlist;
3483 context.newvarno = 0;
3484
3485 return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3486 &context);
3487}
3488
3489/*
3490 * set_windowagg_runcondition_references
3491 * Converts references in 'runcondition' so that any WindowFunc
3492 * references are swapped out for a Var which references the matching
3493 * WindowFunc in 'plan' targetlist.
3494 */
3495static List *
3497 List *runcondition,
3498 Plan *plan)
3499{
3500 List *newlist;
3501 indexed_tlist *itlist;
3502
3503 itlist = build_tlist_index(plan->targetlist);
3504
3505 newlist = fix_windowagg_condition_expr(root, runcondition, itlist);
3506
3507 pfree(itlist);
3508
3509 return newlist;
3510}
3511
3512/*
3513 * find_minmax_agg_replacement_param
3514 * If the given Aggref is one that we are optimizing into a subquery
3515 * (cf. planagg.c), then return the Param that should replace it.
3516 * Else return NULL.
3517 *
3518 * This is exported so that SS_finalize_plan can use it before setrefs.c runs.
3519 * Note that it will not find anything until we have built a Plan from a
3520 * MinMaxAggPath, as root->minmax_aggs will never be filled otherwise.
3521 */
3522Param *
3524{
3525 if (root->minmax_aggs != NIL &&
3526 list_length(aggref->args) == 1)
3527 {
3528 TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
3529 ListCell *lc;
3530
3531 foreach(lc, root->minmax_aggs)
3532 {
3533 MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3534
3535 if (mminfo->aggfnoid == aggref->aggfnoid &&
3536 equal(mminfo->target, curTarget->expr))
3537 return mminfo->param;
3538 }
3539 }
3540 return NULL;
3541}
3542
3543
3544/*****************************************************************************
3545 * QUERY DEPENDENCY MANAGEMENT
3546 *****************************************************************************/
3547
3548/*
3549 * record_plan_function_dependency
3550 * Mark the current plan as depending on a particular function.
3551 *
3552 * This is exported so that the function-inlining code can record a
3553 * dependency on a function that it's removed from the plan tree.
3554 */
3555void
3557{
3558 /*
3559 * For performance reasons, we don't bother to track built-in functions;
3560 * we just assume they'll never change (or at least not in ways that'd
3561 * invalidate plans using them). For this purpose we can consider a
3562 * built-in function to be one with OID less than FirstUnpinnedObjectId.
3563 * Note that the OID generator guarantees never to generate such an OID
3564 * after startup, even at OID wraparound.
3565 */
3566 if (funcid >= (Oid) FirstUnpinnedObjectId)
3567 {
3568 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3569
3570 /*
3571 * It would work to use any syscache on pg_proc, but the easiest is
3572 * PROCOID since we already have the function's OID at hand. Note
3573 * that plancache.c knows we use PROCOID.
3574 */
3575 inval_item->cacheId = PROCOID;
3576 inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
3577 ObjectIdGetDatum(funcid));
3578
3579 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3580 }
3581}
3582
3583/*
3584 * record_plan_type_dependency
3585 * Mark the current plan as depending on a particular type.
3586 *
3587 * This is exported so that eval_const_expressions can record a
3588 * dependency on a domain that it's removed a CoerceToDomain node for.
3589 *
3590 * We don't currently need to record dependencies on domains that the
3591 * plan contains CoerceToDomain nodes for, though that might change in
3592 * future. Hence, this isn't actually called in this module, though
3593 * someday fix_expr_common might call it.
3594 */
3595void
3597{
3598 /*
3599 * As in record_plan_function_dependency, ignore the possibility that
3600 * someone would change a built-in domain.
3601 */
3602 if (typid >= (Oid) FirstUnpinnedObjectId)
3603 {
3604 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3605
3606 /*
3607 * It would work to use any syscache on pg_type, but the easiest is
3608 * TYPEOID since we already have the type's OID at hand. Note that
3609 * plancache.c knows we use TYPEOID.
3610 */
3611 inval_item->cacheId = TYPEOID;
3612 inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
3613 ObjectIdGetDatum(typid));
3614
3615 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3616 }
3617}
3618
3619/*
3620 * extract_query_dependencies
3621 * Given a rewritten, but not yet planned, query or queries
3622 * (i.e. a Query node or list of Query nodes), extract dependencies
3623 * just as set_plan_references would do. Also detect whether any
3624 * rewrite steps were affected by RLS.
3625 *
3626 * This is needed by plancache.c to handle invalidation of cached unplanned
3627 * queries.
3628 *
3629 * Note: this does not go through eval_const_expressions, and hence doesn't
3630 * reflect its additions of inlined functions and elided CoerceToDomain nodes
3631 * to the invalItems list. This is obviously OK for functions, since we'll
3632 * see them in the original query tree anyway. For domains, it's OK because
3633 * we don't care about domains unless they get elided. That is, a plan might
3634 * have domain dependencies that the query tree doesn't.
3635 */
3636void
3638 List **relationOids,
3639 List **invalItems,
3640 bool *hasRowSecurity)
3641{
3642 PlannerGlobal glob;
3644
3645 /* Make up dummy planner state so we can use this module's machinery */
3646 MemSet(&glob, 0, sizeof(glob));
3647 glob.type = T_PlannerGlobal;
3648 glob.relationOids = NIL;
3649 glob.invalItems = NIL;
3650 /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3651 glob.dependsOnRole = false;
3652
3653 MemSet(&root, 0, sizeof(root));
3654 root.type = T_PlannerInfo;
3655 root.glob = &glob;
3656
3658
3659 *relationOids = glob.relationOids;
3660 *invalItems = glob.invalItems;
3661 *hasRowSecurity = glob.dependsOnRole;
3662}
3663
3664/*
3665 * Tree walker for extract_query_dependencies.
3666 *
3667 * This is exported so that expression_planner_with_deps can call it on
3668 * simple expressions (post-planning, not before planning, in that case).
3669 * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
3670 * and invalItems lists are added to as needed.
3671 */
3672bool
3674{
3675 if (node == NULL)
3676 return false;
3677 Assert(!IsA(node, PlaceHolderVar));
3678 if (IsA(node, Query))
3679 {
3680 Query *query = (Query *) node;
3681 ListCell *lc;
3682
3683 if (query->commandType == CMD_UTILITY)
3684 {
3685 /*
3686 * This logic must handle any utility command for which parse
3687 * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3688 *
3689 * Notably, CALL requires its own processing.
3690 */
3691 if (IsA(query->utilityStmt, CallStmt))
3692 {
3693 CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3694
3695 /* We need not examine funccall, just the transformed exprs */
3696 (void) extract_query_dependencies_walker((Node *) callstmt->funcexpr,
3697 context);
3698 (void) extract_query_dependencies_walker((Node *) callstmt->outargs,
3699 context);
3700 return false;
3701 }
3702
3703 /*
3704 * Ignore other utility statements, except those (such as EXPLAIN)
3705 * that contain a parsed-but-not-planned query. For those, we
3706 * just need to transfer our attention to the contained query.
3707 */
3708 query = UtilityContainsQuery(query->utilityStmt);
3709 if (query == NULL)
3710 return false;
3711 }
3712
3713 /* Remember if any Query has RLS quals applied by rewriter */
3714 if (query->hasRowSecurity)
3715 context->glob->dependsOnRole = true;
3716
3717 /* Collect relation OIDs in this Query's rtable */
3718 foreach(lc, query->rtable)
3719 {
3720 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3721
3722 if (rte->rtekind == RTE_RELATION ||
3723 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3724 (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
3725 context->glob->relationOids =
3726 lappend_oid(context->glob->relationOids, rte->relid);
3727 }
3728
3729 /* And recurse into the query's subexpressions */
3731 context, 0);
3732 }
3733 /* Extract function dependencies and check for regclass Consts */
3734 fix_expr_common(context, node);
3736 context);
3737}
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:292
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:470
unsigned int Index
Definition: c.h:619
#define MemSet(start, val, len)
Definition: c.h:1019
#define OidIsValid(objectId)
Definition: c.h:774
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Assert(PointerIsAligned(start, uint64))
int i
Definition: isn.c:77
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * lappend_int(List *list, int datum)
Definition: list.c:357
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
Datum lca(PG_FUNCTION_ARGS)
Definition: ltree_op.c:571
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:107
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:388
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:289
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition: makefuncs.c:322
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
void * palloc(Size size)
Definition: mcxt.c:1365
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1883
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1872
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define QTW_EXAMINE_RTES_BEFORE
Definition: nodeFuncs.h:27
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define copyObject(obj)
Definition: nodes.h:232
double Cost
Definition: nodes.h:261
#define nodeTag(nodeptr)
Definition: nodes.h:139
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:395
@ CMD_UTILITY
Definition: nodes.h:280
@ AGGSPLIT_FINAL_DESERIAL
Definition: nodes.h:391
@ AGGSPLIT_INITIAL_SERIAL
Definition: nodes.h:389
#define makeNode(_type_)
Definition: nodes.h:161
@ JOIN_INNER
Definition: nodes.h:303
char * bmsToString(const Bitmapset *bms)
Definition: outfuncs.c:822
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1049
@ RTE_SUBQUERY
Definition: parsenodes.h:1043
@ RTE_RELATION
Definition: parsenodes.h:1042
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:2105
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define lfirst_int(lc)
Definition: pg_list.h:173
#define list_make1(x1)
Definition: pg_list.h:212
#define linitial_int(l)
Definition: pg_list.h:179
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:563
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define linitial(l)
Definition: pg_list.h:178
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
#define plan(x)
Definition: pg_regress.c:161
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:5718
@ SUBQUERY_SCAN_NONTRIVIAL
Definition: plannodes.h:742
@ SUBQUERY_SCAN_UNKNOWN
Definition: plannodes.h:740
@ SUBQUERY_SCAN_TRIVIAL
Definition: plannodes.h:741
#define outerPlan(node)
Definition: plannodes.h:252
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:252
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
unsigned int Oid
Definition: postgres_ext.h:32
#define ROWID_VAR
Definition: primnodes.h:245
@ PARAM_MULTIEXPR
Definition: primnodes.h:387
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:247
@ VAR_RETURNING_DEFAULT
Definition: primnodes.h:256
#define OUTER_VAR
Definition: primnodes.h:243
#define INNER_VAR
Definition: primnodes.h:242
#define INDEX_VAR
Definition: primnodes.h:244
tree ctl root
Definition: radixtree.h:1857
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:416
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1464
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
NullingRelsMatch
Definition: setrefs.c:35
@ NRM_EQUAL
Definition: setrefs.c:36
@ NRM_SUPERSET
Definition: setrefs.c:38
@ NRM_SUBSET
Definition: setrefs.c:37
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition: setrefs.c:3596
#define NUM_EXEC_QUAL(parentplan)
Definition: setrefs.c:117
static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:1955
static void fix_expr_common(PlannerInfo *root, Node *node)
Definition: setrefs.c:2032
static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
Definition: setrefs.c:396
static Node * fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
Definition: setrefs.c:3128
static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos, RangeTblEntry *rte)
Definition: setrefs.c:542
static Plan * set_append_references(PlannerInfo *root, Append *aplan, int rtoffset)
Definition: setrefs.c:1823
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:288
static Plan * set_mergeappend_references(PlannerInfo *root, MergeAppend *mplan, int rtoffset)
Definition: setrefs.c:1890
static List * set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, int rtoffset)
Definition: setrefs.c:3401
static Node * fix_param_node(PlannerInfo *root, Param *p)
Definition: setrefs.c:2127
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3556
static Relids offset_relid_set(Relids relids, int rtoffset)
Definition: setrefs.c:1988
static bool flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt)
Definition: setrefs.c:497
static indexed_tlist * build_tlist_index(List *tlist)
Definition: setrefs.c:2761
static List * set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, Plan *plan)
Definition: setrefs.c:3496
bool trivial_subqueryscan(SubqueryScan *plan)
Definition: setrefs.c:1478
static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:2483
static Var * search_indexed_tlist_for_sortgroupref(Expr *node, Index sortgroupref, indexed_tlist *itlist, int newvarno)
Definition: setrefs.c:3028
static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
Definition: setrefs.c:485
static Node * fix_upper_expr(PlannerInfo *root, Node *node, indexed_tlist *subplan_itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
Definition: setrefs.c:3280
static void set_param_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:2571
static Var * search_indexed_tlist_for_non_var(Expr *node, indexed_tlist *itlist, int newvarno)
Definition: setrefs.c:2988
static Node * fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
Definition: setrefs.c:3300
Param * find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
Definition: setrefs.c:3523
static Node * fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
Definition: setrefs.c:2249
static void set_foreignscan_references(PlannerInfo *root, ForeignScan *fscan, int rtoffset)
Definition: setrefs.c:1592
static Plan * set_subqueryscan_references(PlannerInfo *root, SubqueryScan *plan, int rtoffset)
Definition: setrefs.c:1409
static Var * search_indexed_tlist_for_phv(PlaceHolderVar *phv, indexed_tlist *itlist, int newvarno, NullingRelsMatch nrm_match)
Definition: setrefs.c:2935
static Plan * set_indexonlyscan_references(PlannerInfo *root, IndexOnlyScan *plan, int rtoffset)
Definition: setrefs.c:1335
static List * fix_join_expr(PlannerInfo *root, List *clauses, indexed_tlist *outer_itlist, indexed_tlist *inner_itlist, Index acceptable_rel, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
Definition: setrefs.c:3106
static Node * convert_combining_aggrefs(Node *node, void *context)
Definition: setrefs.c:2626
static void set_dummy_tlist_references(Plan *plan, int rtoffset)
Definition: setrefs.c:2694
static int register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
Definition: setrefs.c:1762
static void set_customscan_references(PlannerInfo *root, CustomScan *cscan, int rtoffset)
Definition: setrefs.c:1679
#define ISREGCLASSCONST(con)
Definition: setrefs.c:126
void extract_query_dependencies(Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
Definition: setrefs.c:3637
static Node * fix_windowagg_condition_expr_mutator(Node *node, fix_windowagg_cond_context *context)
Definition: setrefs.c:3445
static Var * copyVar(Var *var)
Definition: setrefs.c:2010
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3673
static List * fix_windowagg_condition_expr(PlannerInfo *root, List *runcondition, indexed_tlist *subplan_itlist)
Definition: setrefs.c:3475
#define NUM_EXEC_TLIST(parentplan)
Definition: setrefs.c:116
static Node * fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan, double num_exec)
Definition: setrefs.c:2158
static void set_join_references(PlannerInfo *root, Join *join, int rtoffset)
Definition: setrefs.c:2334
static indexed_tlist * build_tlist_index_other_vars(List *tlist, int ignore_rel)
Definition: setrefs.c:2812
static Plan * clean_up_removed_plan_level(Plan *parent, Plan *child)
Definition: setrefs.c:1548
static Node * fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
Definition: setrefs.c:2214
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:619
static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
Definition: setrefs.c:2314
static Var * search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match)
Definition: setrefs.c:2870
#define fix_scan_list(root, lst, rtoffset, num_exec)
Definition: setrefs.c:130
AggSplit aggsplit
Definition: plannodes.h:1189
Oid aggfnoid
Definition: primnodes.h:463
List * aggdistinct
Definition: primnodes.h:493
List * args
Definition: primnodes.h:487
Expr * aggfilter
Definition: primnodes.h:496
List * aggorder
Definition: primnodes.h:490
Index child_relid
Definition: pathnodes.h:3105
List * translated_vars
Definition: pathnodes.h:3132
Index parent_relid
Definition: pathnodes.h:3104
int part_prune_index
Definition: plannodes.h:401
Bitmapset * apprelids
Definition: plannodes.h:385
Plan plan
Definition: plannodes.h:383
List * appendplans
Definition: plannodes.h:386
Plan plan
Definition: plannodes.h:484
List * bitmapplans
Definition: plannodes.h:485
List * bitmapqualorig
Definition: plannodes.h:686
List * indexqualorig
Definition: plannodes.h:670
List * indexqual
Definition: plannodes.h:668
List * bitmapplans
Definition: plannodes.h:500
Plan plan
Definition: plannodes.h:498
FuncExpr * funcexpr
Definition: parsenodes.h:3643
List * outargs
Definition: parsenodes.h:3645
Scan scan
Definition: plannodes.h:793
List * custom_scan_tlist
Definition: plannodes.h:916
Scan scan
Definition: plannodes.h:906
Bitmapset * custom_relids
Definition: plannodes.h:918
List * custom_plans
Definition: plannodes.h:910
Bitmapset * fs_relids
Definition: plannodes.h:882
Bitmapset * fs_base_relids
Definition: plannodes.h:884
Index resultRelation
Definition: plannodes.h:868
List * fdw_scan_tlist
Definition: plannodes.h:878
List * functions
Definition: plannodes.h:760
List * hashclauses
Definition: plannodes.h:1039
List * hashkeys
Definition: plannodes.h:1047
List * hashkeys
Definition: plannodes.h:1402
List * indexorderby
Definition: plannodes.h:586
Scan scan
Definition: plannodes.h:578
List * indexqualorig
Definition: plannodes.h:584
List * indexqual
Definition: plannodes.h:582
List * indexorderbyorig
Definition: plannodes.h:588
List * joinqual
Definition: plannodes.h:964
JoinType jointype
Definition: plannodes.h:961
Plan plan
Definition: plannodes.h:1472
Node * limitCount
Definition: plannodes.h:1478
Node * limitOffset
Definition: plannodes.h:1475
Definition: pg_list.h:54
List * rowMarks
Definition: plannodes.h:1458
Plan plan
Definition: plannodes.h:1456
List * param_exprs
Definition: plannodes.h:1077
int part_prune_index
Definition: plannodes.h:440
Bitmapset * apprelids
Definition: plannodes.h:414
List * mergeplans
Definition: plannodes.h:416
List * mergeclauses
Definition: plannodes.h:1015
Param * param
Definition: pathnodes.h:3268
Expr * target
Definition: pathnodes.h:3253
Index nominalRelation
Definition: plannodes.h:329
List * mergeJoinConditions
Definition: plannodes.h:371
List * resultRelations
Definition: plannodes.h:335
List * onConflictSet
Definition: plannodes.h:359
List * exclRelTlist
Definition: plannodes.h:367
List * mergeActionLists
Definition: plannodes.h:369
List * returningLists
Definition: plannodes.h:345
List * withCheckOptionLists
Definition: plannodes.h:339
Index rootRelation
Definition: plannodes.h:331
Node * onConflictWhere
Definition: plannodes.h:363
List * rowMarks
Definition: plannodes.h:351
Index exclRelRTI
Definition: plannodes.h:365
Var * paramval
Definition: plannodes.h:993
List * nestParams
Definition: plannodes.h:982
Definition: nodes.h:135
int paramid
Definition: primnodes.h:396
ParamKind paramkind
Definition: primnodes.h:395
Bitmapset * relids
Definition: plannodes.h:1640
Relids phnullingrels
Definition: pathnodes.h:2931
uint32 hashValue
Definition: plannodes.h:1797
Index prti
Definition: plannodes.h:1585
struct Plan * lefttree
Definition: plannodes.h:224
Cost total_cost
Definition: plannodes.h:190
struct Plan * righttree
Definition: plannodes.h:225
bool parallel_aware
Definition: plannodes.h:204
Cost startup_cost
Definition: plannodes.h:188
List * qual
Definition: plannodes.h:222
bool parallel_safe
Definition: plannodes.h:206
List * targetlist
Definition: plannodes.h:220
List * initPlan
Definition: plannodes.h:227
Bitmapset * prunableRelids
Definition: pathnodes.h:130
List * subplans
Definition: pathnodes.h:105
bool dependsOnRole
Definition: pathnodes.h:169
Bitmapset * allRelids
Definition: pathnodes.h:123
List * appendRelations
Definition: pathnodes.h:142
List * finalrowmarks
Definition: pathnodes.h:136
List * invalItems
Definition: pathnodes.h:151
List * relationOids
Definition: pathnodes.h:148
List * finalrteperminfos
Definition: pathnodes.h:133
List * partPruneInfos
Definition: pathnodes.h:145
List * finalrtable
Definition: pathnodes.h:117
List * init_plans
Definition: pathnodes.h:317
PlannerGlobal * glob
Definition: pathnodes.h:223
List * rtable
Definition: parsenodes.h:175
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:141
TableFunc * tablefunc
Definition: parsenodes.h:1214
struct TableSampleClause * tablesample
Definition: parsenodes.h:1128
Query * subquery
Definition: parsenodes.h:1134
List * values_lists
Definition: parsenodes.h:1220
List * functions
Definition: parsenodes.h:1207
RTEKind rtekind
Definition: parsenodes.h:1077
Index relid
Definition: pathnodes.h:954
PlannerInfo * subroot
Definition: pathnodes.h:985
Node * resconstantqual
Definition: plannodes.h:290
Bitmapset * relids
Definition: plannodes.h:291
Plan plan
Definition: plannodes.h:288
struct TableSampleClause * tablesample
Definition: plannodes.h:536
Scan scan
Definition: plannodes.h:534
Index scanrelid
Definition: plannodes.h:516
Scan scan
Definition: plannodes.h:525
int plan_id
Definition: primnodes.h:1089
List * setParam
Definition: primnodes.h:1107
Cost startup_cost
Definition: primnodes.h:1112
Cost per_call_cost
Definition: primnodes.h:1113
TableFunc * tablefunc
Definition: plannodes.h:784
Expr * expr
Definition: primnodes.h:2225
AttrNumber resno
Definition: primnodes.h:2227
Index ressortgroupref
Definition: primnodes.h:2231
List * tidrangequals
Definition: plannodes.h:715
Scan scan
Definition: plannodes.h:699
List * tidquals
Definition: plannodes.h:701
Scan scan
Definition: plannodes.h:771
List * values_lists
Definition: plannodes.h:773
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
int varno
Definition: primnodes.h:269
VarReturningType varreturningtype
Definition: primnodes.h:297
Index varlevelsup
Definition: primnodes.h:294
Node * endOffset
Definition: plannodes.h:1264
List * runConditionOrig
Definition: plannodes.h:1270
Node * startOffset
Definition: plannodes.h:1261
List * runCondition
Definition: plannodes.h:1267
NullingRelsMatch nrm_match
Definition: setrefs.c:72
indexed_tlist * outer_itlist
Definition: setrefs.c:68
PlannerInfo * root
Definition: setrefs.c:67
indexed_tlist * inner_itlist
Definition: setrefs.c:69
PlannerInfo * root
Definition: setrefs.c:60
indexed_tlist * subplan_itlist
Definition: setrefs.c:79
PlannerInfo * root
Definition: setrefs.c:78
NullingRelsMatch nrm_match
Definition: setrefs.c:82
indexed_tlist * subplan_itlist
Definition: setrefs.c:89
PlannerInfo * root
Definition: setrefs.c:88
PlannerGlobal * glob
Definition: setrefs.c:96
tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]
Definition: setrefs.c:55
bool has_ph_vars
Definition: setrefs.c:53
bool has_non_vars
Definition: setrefs.c:54
int num_vars
Definition: setrefs.c:52
List * tlist
Definition: setrefs.c:51
AttrNumber resno
Definition: setrefs.c:45
Bitmapset * varnullingrels
Definition: setrefs.c:46
int varno
Definition: setrefs.c:43
AttrNumber varattno
Definition: setrefs.c:44
Definition: regcomp.c:282
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2346
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:118
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition: tlist.c:79
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:318
#define FirstUnpinnedObjectId
Definition: transam.h:196
Query * UtilityContainsQuery(Node *parsetree)
Definition: utility.c:2171