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