Debian Codegraph @

src/backend/rewrite/rewriteManip.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * rewriteManip.c
4 *
5 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
6 * Portions Copyright (c) 1994, Regents of the University of California
7 *
8 *
9 * IDENTIFICATION
10 * src/backend/rewrite/rewriteManip.c
11 *
12 *-------------------------------------------------------------------------
13 */
14 #include "postgres.h"
15
16 #include "catalog/pg_type.h"
17 #include "nodes/makefuncs.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/pathnodes.h"
20 #include "nodes/plannodes.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_relation.h"
23 #include "parser/parsetree.h"
24 #include "rewrite/rewriteManip.h"
25 #include "utils/lsyscache.h"
26
27
28 typedef struct
29 {
30 int sublevels_up;
31 } contain_aggs_of_level_context;
32
33 typedef struct
34 {
35 int agg_location;
36 int sublevels_up;
37 } locate_agg_of_level_context;
38
39 typedef struct
40 {
41 int win_location;
42 } locate_windowfunc_context;
43
44 typedef struct
45 {
46 const Bitmapset *target_relids;
47 const Bitmapset *added_relids;
48 int sublevels_up;
49 } add_nulling_relids_context;
50
51 typedef struct
52 {
53 const Bitmapset *removable_relids;
54 const Bitmapset *except_relids;
55 int sublevels_up;
56 } remove_nulling_relids_context;
57
58 static bool contain_aggs_of_level_walker(Node *node,
59 contain_aggs_of_level_context *context);
60 static bool locate_agg_of_level_walker(Node *node,
61 locate_agg_of_level_context *context);
62 static bool contain_windowfuncs_walker(Node *node, void *context);
63 static bool locate_windowfunc_walker(Node *node,
64 locate_windowfunc_context *context);
65 static bool checkExprHasSubLink_walker(Node *node, void *context);
66 static Relids offset_relid_set(Relids relids, int offset);
67 static Node *add_nulling_relids_mutator(Node *node,
68 add_nulling_relids_context *context);
69 static Node *remove_nulling_relids_mutator(Node *node,
70 remove_nulling_relids_context *context);
71
72
73 /*
74 * contain_aggs_of_level -
75 * Check if an expression contains an aggregate function call of a
76 * specified query level.
77 *
78 * The objective of this routine is to detect whether there are aggregates
79 * belonging to the given query level. Aggregates belonging to subqueries
80 * or outer queries do NOT cause a true result. We must recurse into
81 * subqueries to detect outer-reference aggregates that logically belong to
82 * the specified query level.
83 */
84 bool
85 contain_aggs_of_level(Node *node, int levelsup)
86 {
87 contain_aggs_of_level_context context;
88
89 context.sublevels_up = levelsup;
90
91 /*
92 * Must be prepared to start with a Query or a bare expression tree; if
93 * it's a Query, we don't want to increment sublevels_up.
94 */
95 return query_or_expression_tree_walker(node,
96 contain_aggs_of_level_walker,
97 &context,
98 0);
99 }
100
101 static bool
102 contain_aggs_of_level_walker(Node *node,
103 contain_aggs_of_level_context *context)
104 {
105 if (node == NULL)
106 return false;
107 if (IsA(node, Aggref))
108 {
109 if (((Aggref *) node)->agglevelsup == context->sublevels_up)
110 return true; /* abort the tree traversal and return true */
111 /* else fall through to examine argument */
112 }
113 if (IsA(node, GroupingFunc))
114 {
115 if (((GroupingFunc *) node)->agglevelsup == context->sublevels_up)
116 return true;
117 /* else fall through to examine argument */
118 }
119 if (IsA(node, Query))
120 {
121 /* Recurse into subselects */
122 bool result;
123
124 context->sublevels_up++;
125 result = query_tree_walker((Query *) node,
126 contain_aggs_of_level_walker,
127 context, 0);
128 context->sublevels_up--;
129 return result;
130 }
131 return expression_tree_walker(node, contain_aggs_of_level_walker,
132 context);
133 }
134
135 /*
136 * locate_agg_of_level -
137 * Find the parse location of any aggregate of the specified query level.
138 *
139 * Returns -1 if no such agg is in the querytree, or if they all have
140 * unknown parse location. (The former case is probably caller error,
141 * but we don't bother to distinguish it from the latter case.)
142 *
143 * Note: it might seem appropriate to merge this functionality into
144 * contain_aggs_of_level, but that would complicate that function's API.
145 * Currently, the only uses of this function are for error reporting,
146 * and so shaving cycles probably isn't very important.
147 */
148 int
149 locate_agg_of_level(Node *node, int levelsup)
150 {
151 locate_agg_of_level_context context;
152
153 context.agg_location = -1; /* in case we find nothing */
154 context.sublevels_up = levelsup;
155
156 /*
157 * Must be prepared to start with a Query or a bare expression tree; if
158 * it's a Query, we don't want to increment sublevels_up.
159 */
160 (void) query_or_expression_tree_walker(node,
161 locate_agg_of_level_walker,
162 &context,
163 0);
164
165 return context.agg_location;
166 }
167
168 static bool
169 locate_agg_of_level_walker(Node *node,
170 locate_agg_of_level_context *context)
171 {
172 if (node == NULL)
173 return false;
174 if (IsA(node, Aggref))
175 {
176 if (((Aggref *) node)->agglevelsup == context->sublevels_up &&
177 ((Aggref *) node)->location >= 0)
178 {
179 context->agg_location = ((Aggref *) node)->location;
180 return true; /* abort the tree traversal and return true */
181 }
182 /* else fall through to examine argument */
183 }
184 if (IsA(node, GroupingFunc))
185 {
186 if (((GroupingFunc *) node)->agglevelsup == context->sublevels_up &&
187 ((GroupingFunc *) node)->location >= 0)
188 {
189 context->agg_location = ((GroupingFunc *) node)->location;
190 return true; /* abort the tree traversal and return true */
191 }
192 }
193 if (IsA(node, Query))
194 {
195 /* Recurse into subselects */
196 bool result;
197
198 context->sublevels_up++;
199 result = query_tree_walker((Query *) node,
200 locate_agg_of_level_walker,
201 context, 0);
202 context->sublevels_up--;
203 return result;
204 }
205 return expression_tree_walker(node, locate_agg_of_level_walker, context);
206 }
207
208 /*
209 * contain_windowfuncs -
210 * Check if an expression contains a window function call of the
211 * current query level.
212 */
213 bool
214 contain_windowfuncs(Node *node)
215 {
216 /*
217 * Must be prepared to start with a Query or a bare expression tree; if
218 * it's a Query, we don't want to increment sublevels_up.
219 */
220 return query_or_expression_tree_walker(node,
221 contain_windowfuncs_walker,
222 NULL,
223 0);
224 }
225
226 static bool
227 contain_windowfuncs_walker(Node *node, void *context)
228 {
229 if (node == NULL)
230 return false;
231 if (IsA(node, WindowFunc))
232 return true; /* abort the tree traversal and return true */
233 /* Mustn't recurse into subselects */
234 return expression_tree_walker(node, contain_windowfuncs_walker, context);
235 }
236
237 /*
238 * locate_windowfunc -
239 * Find the parse location of any windowfunc of the current query level.
240 *
241 * Returns -1 if no such windowfunc is in the querytree, or if they all have
242 * unknown parse location. (The former case is probably caller error,
243 * but we don't bother to distinguish it from the latter case.)
244 *
245 * Note: it might seem appropriate to merge this functionality into
246 * contain_windowfuncs, but that would complicate that function's API.
247 * Currently, the only uses of this function are for error reporting,
248 * and so shaving cycles probably isn't very important.
249 */
250 int
251 locate_windowfunc(Node *node)
252 {
253 locate_windowfunc_context context;
254
255 context.win_location = -1; /* in case we find nothing */
256
257 /*
258 * Must be prepared to start with a Query or a bare expression tree; if
259 * it's a Query, we don't want to increment sublevels_up.
260 */
261 (void) query_or_expression_tree_walker(node,
262 locate_windowfunc_walker,
263 &context,
264 0);
265
266 return context.win_location;
267 }
268
269 static bool
270 locate_windowfunc_walker(Node *node, locate_windowfunc_context *context)
271 {
272 if (node == NULL)
273 return false;
274 if (IsA(node, WindowFunc))
275 {
276 if (((WindowFunc *) node)->location >= 0)
277 {
278 context->win_location = ((WindowFunc *) node)->location;
279 return true; /* abort the tree traversal and return true */
280 }
281 /* else fall through to examine argument */
282 }
283 /* Mustn't recurse into subselects */
284 return expression_tree_walker(node, locate_windowfunc_walker, context);
285 }
286
287 /*
288 * checkExprHasSubLink -
289 * Check if an expression contains a SubLink.
290 */
291 bool
292 checkExprHasSubLink(Node *node)
293 {
294 /*
295 * If a Query is passed, examine it --- but we should not recurse into
296 * sub-Queries that are in its rangetable or CTE list.
297 */
298 return query_or_expression_tree_walker(node,
299 checkExprHasSubLink_walker,
300 NULL,
301 QTW_IGNORE_RC_SUBQUERIES);
302 }
303
304 static bool
305 checkExprHasSubLink_walker(Node *node, void *context)
306 {
307 if (node == NULL)
308 return false;
309 if (IsA(node, SubLink))
310 return true; /* abort the tree traversal and return true */
311 return expression_tree_walker(node, checkExprHasSubLink_walker, context);
312 }
313
314 /*
315 * Check for MULTIEXPR Param within expression tree
316 *
317 * We intentionally don't descend into SubLinks: only Params at the current
318 * query level are of interest.
319 */
320 static bool
321 contains_multiexpr_param(Node *node, void *context)
322 {
323 if (node == NULL)
324 return false;
325 if (IsA(node, Param))
326 {
327 if (((Param *) node)->paramkind == PARAM_MULTIEXPR)
328 return true; /* abort the tree traversal and return true */
329 return false;
330 }
331 return expression_tree_walker(node, contains_multiexpr_param, context);
332 }
333
334 /*
335 * CombineRangeTables
336 * Adds the RTEs of 'src_rtable' into 'dst_rtable'
337 *
338 * This also adds the RTEPermissionInfos of 'src_perminfos' (belonging to the
339 * RTEs in 'src_rtable') into *dst_perminfos and also updates perminfoindex of
340 * the RTEs in 'src_rtable' to now point to the perminfos' indexes in
341 * *dst_perminfos.
342 *
343 * Note that this changes both 'dst_rtable' and 'dst_perminfos' destructively,
344 * so the caller should have better passed safe-to-modify copies.
345 */
346 void
347 CombineRangeTables(List **dst_rtable, List **dst_perminfos,
348 List *src_rtable, List *src_perminfos)
349 {
350 ListCell *l;
351 int offset = list_length(*dst_perminfos);
352
353 if (offset > 0)
354 {
355 foreach(l, src_rtable)
356 {
357 RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
358
359 if (rte->perminfoindex > 0)
360 rte->perminfoindex += offset;
361 }
362 }
363
364 *dst_perminfos = list_concat(*dst_perminfos, src_perminfos);
365 *dst_rtable = list_concat(*dst_rtable, src_rtable);
366 }
367
368 /*
369 * OffsetVarNodes - adjust Vars when appending one query's RT to another
370 *
371 * Find all Var nodes in the given tree with varlevelsup == sublevels_up,
372 * and increment their varno fields (rangetable indexes) by 'offset'.
373 * The varnosyn fields are adjusted similarly. Also, adjust other nodes
374 * that contain rangetable indexes, such as RangeTblRef and JoinExpr.
375 *
376 * NOTE: although this has the form of a walker, we cheat and modify the
377 * nodes in-place. The given expression tree should have been copied
378 * earlier to ensure that no unwanted side-effects occur!
379 */
380
381 typedef struct
382 {
383 int offset;
384 int sublevels_up;
385 } OffsetVarNodes_context;
386
387 static bool
388 OffsetVarNodes_walker(Node *node, OffsetVarNodes_context *context)
389 {
390 if (node == NULL)
391 return false;
392 if (IsA(node, Var))
393 {
394 Var *var = (Var *) node;
395
396 if (var->varlevelsup == context->sublevels_up)
397 {
398 var->varno += context->offset;
399 var->varnullingrels = offset_relid_set(var->varnullingrels,
400 context->offset);
401 if (var->varnosyn > 0)
402 var->varnosyn += context->offset;
403 }
404 return false;
405 }
406 if (IsA(node, CurrentOfExpr))
407 {
408 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
409
410 if (context->sublevels_up == 0)
411 cexpr->cvarno += context->offset;
412 return false;
413 }
414 if (IsA(node, RangeTblRef))
415 {
416 RangeTblRef *rtr = (RangeTblRef *) node;
417
418 if (context->sublevels_up == 0)
419 rtr->rtindex += context->offset;
420 /* the subquery itself is visited separately */
421 return false;
422 }
423 if (IsA(node, JoinExpr))
424 {
425 JoinExpr *j = (JoinExpr *) node;
426
427 if (j->rtindex && context->sublevels_up == 0)
428 j->rtindex += context->offset;
429 /* fall through to examine children */
430 }
431 if (IsA(node, PlaceHolderVar))
432 {
433 PlaceHolderVar *phv = (PlaceHolderVar *) node;
434
435 if (phv->phlevelsup == context->sublevels_up)
436 {
437 phv->phrels = offset_relid_set(phv->phrels,
438 context->offset);
439 phv->phnullingrels = offset_relid_set(phv->phnullingrels,
440 context->offset);
441 }
442 /* fall through to examine children */
443 }
444 if (IsA(node, AppendRelInfo))
445 {
446 AppendRelInfo *appinfo = (AppendRelInfo *) node;
447
448 if (context->sublevels_up == 0)
449 {
450 appinfo->parent_relid += context->offset;
451 appinfo->child_relid += context->offset;
452 }
453 /* fall through to examine children */
454 }
455 /* Shouldn't need to handle other planner auxiliary nodes here */
456 Assert(!IsA(node, PlanRowMark));
457 Assert(!IsA(node, SpecialJoinInfo));
458 Assert(!IsA(node, PlaceHolderInfo));
459 Assert(!IsA(node, MinMaxAggInfo));
460
461 if (IsA(node, Query))
462 {
463 /* Recurse into subselects */
464 bool result;
465
466 context->sublevels_up++;
467 result = query_tree_walker((Query *) node, OffsetVarNodes_walker,
468 context, 0);
469 context->sublevels_up--;
470 return result;
471 }
472 return expression_tree_walker(node, OffsetVarNodes_walker, context);
473 }
474
475 void
476 OffsetVarNodes(Node *node, int offset, int sublevels_up)
477 {
478 OffsetVarNodes_context context;
479
480 context.offset = offset;
481 context.sublevels_up = sublevels_up;
482
483 /*
484 * Must be prepared to start with a Query or a bare expression tree; if
485 * it's a Query, go straight to query_tree_walker to make sure that
486 * sublevels_up doesn't get incremented prematurely.
487 */
488 if (node && IsA(node, Query))
489 {
490 Query *qry = (Query *) node;
491
492 /*
493 * If we are starting at a Query, and sublevels_up is zero, then we
494 * must also fix rangetable indexes in the Query itself --- namely
495 * resultRelation, mergeTargetRelation, exclRelIndex and rowMarks
496 * entries. sublevels_up cannot be zero when recursing into a
497 * subquery, so there's no need to have the same logic inside
498 * OffsetVarNodes_walker.
499 */
500 if (sublevels_up == 0)
501 {
502 ListCell *l;
503
504 if (qry->resultRelation)
505 qry->resultRelation += offset;
506
507 if (qry->mergeTargetRelation)
508 qry->mergeTargetRelation += offset;
509
510 if (qry->onConflict && qry->onConflict->exclRelIndex)
511 qry->onConflict->exclRelIndex += offset;
512
513 foreach(l, qry->rowMarks)
514 {
515 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
516
517 rc->rti += offset;
518 }
519 }
520 query_tree_walker(qry, OffsetVarNodes_walker, &context, 0);
521 }
522 else
523 OffsetVarNodes_walker(node, &context);
524 }
525
526 static Relids
527 offset_relid_set(Relids relids, int offset)
528 {
529 Relids result = NULL;
530 int rtindex;
531
532 rtindex = -1;
533 while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
534 result = bms_add_member(result, rtindex + offset);
535 return result;
536 }
537
538 /*
539 * ChangeVarNodes - adjust Var nodes for a specific change of RT index
540 *
541 * Find all Var nodes in the given tree belonging to a specific relation
542 * (identified by sublevels_up and rt_index), and change their varno fields
543 * to 'new_index'. The varnosyn fields are changed too. Also, adjust other
544 * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr.
545 *
546 * NOTE: although this has the form of a walker, we cheat and modify the
547 * nodes in-place. The given expression tree should have been copied
548 * earlier to ensure that no unwanted side-effects occur!
549 */
550
551 static bool
552 ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context)
553 {
554 if (node == NULL)
555 return false;
556
557 if (context->callback && context->callback(node, context))
558 return false;
559
560 if (IsA(node, Var))
561 {
562 Var *var = (Var *) node;
563
564 if (var->varlevelsup == context->sublevels_up)
565 {
566 if (var->varno == context->rt_index)
567 var->varno = context->new_index;
568 var->varnullingrels = adjust_relid_set(var->varnullingrels,
569 context->rt_index,
570 context->new_index);
571 if (var->varnosyn == context->rt_index)
572 var->varnosyn = context->new_index;
573 }
574 return false;
575 }
576 if (IsA(node, CurrentOfExpr))
577 {
578 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
579
580 if (context->sublevels_up == 0 &&
581 cexpr->cvarno == context->rt_index)
582 cexpr->cvarno = context->new_index;
583 return false;
584 }
585 if (IsA(node, RangeTblRef))
586 {
587 RangeTblRef *rtr = (RangeTblRef *) node;
588
589 if (context->sublevels_up == 0 &&
590 rtr->rtindex == context->rt_index)
591 rtr->rtindex = context->new_index;
592 /* the subquery itself is visited separately */
593 return false;
594 }
595 if (IsA(node, JoinExpr))
596 {
597 JoinExpr *j = (JoinExpr *) node;
598
599 if (context->sublevels_up == 0 &&
600 j->rtindex == context->rt_index)
601 j->rtindex = context->new_index;
602 /* fall through to examine children */
603 }
604 if (IsA(node, PlaceHolderVar))
605 {
606 PlaceHolderVar *phv = (PlaceHolderVar *) node;
607
608 if (phv->phlevelsup == context->sublevels_up)
609 {
610 phv->phrels = adjust_relid_set(phv->phrels,
611 context->rt_index,
612 context->new_index);
613 phv->phnullingrels = adjust_relid_set(phv->phnullingrels,
614 context->rt_index,
615 context->new_index);
616 }
617 /* fall through to examine children */
618 }
619 if (IsA(node, PlanRowMark))
620 {
621 PlanRowMark *rowmark = (PlanRowMark *) node;
622
623 if (context->sublevels_up == 0)
624 {
625 if (rowmark->rti == context->rt_index)
626 rowmark->rti = context->new_index;
627 if (rowmark->prti == context->rt_index)
628 rowmark->prti = context->new_index;
629 }
630 return false;
631 }
632 if (IsA(node, AppendRelInfo))
633 {
634 AppendRelInfo *appinfo = (AppendRelInfo *) node;
635
636 if (context->sublevels_up == 0)
637 {
638 if (appinfo->parent_relid == context->rt_index)
639 appinfo->parent_relid = context->new_index;
640 if (appinfo->child_relid == context->rt_index)
641 appinfo->child_relid = context->new_index;
642 }
643 /* fall through to examine children */
644 }
645 /* Shouldn't need to handle other planner auxiliary nodes here */
646 Assert(!IsA(node, SpecialJoinInfo));
647 Assert(!IsA(node, PlaceHolderInfo));
648 Assert(!IsA(node, MinMaxAggInfo));
649
650 if (IsA(node, Query))
651 {
652 /* Recurse into subselects */
653 bool result;
654
655 context->sublevels_up++;
656 result = query_tree_walker((Query *) node, ChangeVarNodes_walker,
657 context, 0);
658 context->sublevels_up--;
659 return result;
660 }
661 return expression_tree_walker(node, ChangeVarNodes_walker, context);
662 }
663
664 /*
665 * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an additional
666 * 'callback' param
667 *
668 * ChangeVarNodes changes a given node and all of its underlying nodes. This
669 * version of function additionally takes a callback, which has a chance to
670 * process a node before ChangeVarNodes_walker. A callback returns a boolean
671 * value indicating if the given node should be skipped from further processing
672 * by ChangeVarNodes_walker. The callback is called only for expressions and
673 * other children nodes of a Query processed by a walker. Initial processing
674 * of the root Query node doesn't invoke the callback.
675 */
676 void
677 ChangeVarNodesExtended(Node *node, int rt_index, int new_index,
678 int sublevels_up, ChangeVarNodes_callback callback)
679 {
680 ChangeVarNodes_context context;
681
682 context.rt_index = rt_index;
683 context.new_index = new_index;
684 context.sublevels_up = sublevels_up;
685 context.callback = callback;
686
687 /*
688 * Must be prepared to start with a Query or a bare expression tree; if
689 * it's a Query, go straight to query_tree_walker to make sure that
690 * sublevels_up doesn't get incremented prematurely.
691 */
692 if (node && IsA(node, Query))
693 {
694 Query *qry = (Query *) node;
695
696 /*
697 * If we are starting at a Query, and sublevels_up is zero, then we
698 * must also fix rangetable indexes in the Query itself --- namely
699 * resultRelation, mergeTargetRelation, exclRelIndex and rowMarks
700 * entries. sublevels_up cannot be zero when recursing into a
701 * subquery, so there's no need to have the same logic inside
702 * ChangeVarNodes_walker.
703 */
704 if (sublevels_up == 0)
705 {
706 ListCell *l;
707
708 if (qry->resultRelation == rt_index)
709 qry->resultRelation = new_index;
710
711 if (qry->mergeTargetRelation == rt_index)
712 qry->mergeTargetRelation = new_index;
713
714 /* this is unlikely to ever be used, but ... */
715 if (qry->onConflict && qry->onConflict->exclRelIndex == rt_index)
716 qry->onConflict->exclRelIndex = new_index;
717
718 foreach(l, qry->rowMarks)
719 {
720 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
721
722 if (rc->rti == rt_index)
723 rc->rti = new_index;
724 }
725 }
726 query_tree_walker(qry, ChangeVarNodes_walker, &context, 0);
727 }
728 else
729 ChangeVarNodes_walker(node, &context);
730 }
731
732 void
733 ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
734 {
735 ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL);
736 }
737
738 /*
739 * ChangeVarNodesWalkExpression - process subexpression within a callback
740 * function passed to ChangeVarNodesExtended.
741 *
742 * This is intended to be used by a callback that needs to recursively
743 * process subexpressions of some node being visited by an outer
744 * ChangeVarNodesExtended call, instead of relying on ChangeVarNodes_walker's
745 * default recursion. We invoke ChangeVarNodes_walker directly rather than
746 * via expression_tree_walker, because expression_tree_walker only visits
747 * child nodes and would fail to process the passed node itself --
748 * for example, a bare Var node would not get its varno adjusted.
749 *
750 * Because this calls ChangeVarNodes_walker directly, if the passed node is
751 * a Query, it will be treated as a sub-Query: sublevels_up is incremented
752 * before recursing into it, and Query-level fields (resultRelation,
753 * mergeTargetRelation, rowMarks, etc.) will not be adjusted. Do not apply
754 * this to a top-level Query node; use ChangeVarNodesExtended for that.
755 */
756 bool
757 ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context)
758 {
759 return ChangeVarNodes_walker(node, context);
760 }
761
762 /*
763 * adjust_relid_set - substitute newrelid for oldrelid in a Relid set
764 *
765 * Attempt to remove oldrelid from a Relid set (as long as it's not a special
766 * varno). If oldrelid was found and removed, insert newrelid into a Relid
767 * set (as long as it's not a special varno). Therefore, when oldrelid is
768 * a special varno, this function does nothing. When newrelid is a special
769 * varno, this function behaves as delete.
770 */
771 Relids
772 adjust_relid_set(Relids relids, int oldrelid, int newrelid)
773 {
774 if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids))
775 {
776 /* Ensure we have a modifiable copy */
777 relids = bms_copy(relids);
778 /* Remove old, add new */
779 relids = bms_del_member(relids, oldrelid);
780 if (!IS_SPECIAL_VARNO(newrelid))
781 relids = bms_add_member(relids, newrelid);
782 }
783 return relids;
784 }
785
786 /*
787 * IncrementVarSublevelsUp - adjust Var nodes when pushing them down in tree
788 *
789 * Find all Var nodes in the given tree having varlevelsup >= min_sublevels_up,
790 * and add delta_sublevels_up to their varlevelsup value. This is needed when
791 * an expression that's correct for some nesting level is inserted into a
792 * subquery. Ordinarily the initial call has min_sublevels_up == 0 so that
793 * all Vars are affected. The point of min_sublevels_up is that we can
794 * increment it when we recurse into a sublink, so that local variables in
795 * that sublink are not affected, only outer references to vars that belong
796 * to the expression's original query level or parents thereof.
797 *
798 * Likewise for other nodes containing levelsup fields, such as Aggref.
799 *
800 * NOTE: although this has the form of a walker, we cheat and modify the
801 * Var nodes in-place. The given expression tree should have been copied
802 * earlier to ensure that no unwanted side-effects occur!
803 */
804
805 typedef struct
806 {
807 int delta_sublevels_up;
808 int min_sublevels_up;
809 } IncrementVarSublevelsUp_context;
810
811 static bool
812 IncrementVarSublevelsUp_walker(Node *node,
813 IncrementVarSublevelsUp_context *context)
814 {
815 if (node == NULL)
816 return false;
817 if (IsA(node, Var))
818 {
819 Var *var = (Var *) node;
820
821 if (var->varlevelsup >= context->min_sublevels_up)
822 var->varlevelsup += context->delta_sublevels_up;
823 return false; /* done here */
824 }
825 if (IsA(node, CurrentOfExpr))
826 {
827 /* this should not happen */
828 if (context->min_sublevels_up == 0)
829 elog(ERROR, "cannot push down CurrentOfExpr");
830 return false;
831 }
832 if (IsA(node, Aggref))
833 {
834 Aggref *agg = (Aggref *) node;
835
836 if (agg->agglevelsup >= context->min_sublevels_up)
837 agg->agglevelsup += context->delta_sublevels_up;
838 /* fall through to recurse into argument */
839 }
840 if (IsA(node, GroupingFunc))
841 {
842 GroupingFunc *grp = (GroupingFunc *) node;
843
844 if (grp->agglevelsup >= context->min_sublevels_up)
845 grp->agglevelsup += context->delta_sublevels_up;
846 /* fall through to recurse into argument */
847 }
848 if (IsA(node, PlaceHolderVar))
849 {
850 PlaceHolderVar *phv = (PlaceHolderVar *) node;
851
852 if (phv->phlevelsup >= context->min_sublevels_up)
853 phv->phlevelsup += context->delta_sublevels_up;
854 /* fall through to recurse into argument */
855 }
856 if (IsA(node, ReturningExpr))
857 {
858 ReturningExpr *rexpr = (ReturningExpr *) node;
859
860 if (rexpr->retlevelsup >= context->min_sublevels_up)
861 rexpr->retlevelsup += context->delta_sublevels_up;
862 /* fall through to recurse into argument */
863 }
864 if (IsA(node, RangeTblEntry))
865 {
866 RangeTblEntry *rte = (RangeTblEntry *) node;
867
868 if (rte->rtekind == RTE_CTE)
869 {
870 if (rte->ctelevelsup >= context->min_sublevels_up)
871 rte->ctelevelsup += context->delta_sublevels_up;
872 }
873 return false; /* allow range_table_walker to continue */
874 }
875 if (IsA(node, Query))
876 {
877 /* Recurse into subselects */
878 bool result;
879
880 context->min_sublevels_up++;
881 result = query_tree_walker((Query *) node,
882 IncrementVarSublevelsUp_walker,
883 context,
884 QTW_EXAMINE_RTES_BEFORE);
885 context->min_sublevels_up--;
886 return result;
887 }
888 return expression_tree_walker(node, IncrementVarSublevelsUp_walker, context);
889 }
890
891 void
892 IncrementVarSublevelsUp(Node *node, int delta_sublevels_up,
893 int min_sublevels_up)
894 {
895 IncrementVarSublevelsUp_context context;
896
897 context.delta_sublevels_up = delta_sublevels_up;
898 context.min_sublevels_up = min_sublevels_up;
899
900 /*
901 * Must be prepared to start with a Query or a bare expression tree; if
902 * it's a Query, we don't want to increment sublevels_up.
903 */
904 query_or_expression_tree_walker(node,
905 IncrementVarSublevelsUp_walker,
906 &context,
907 QTW_EXAMINE_RTES_BEFORE);
908 }
909
910 /*
911 * IncrementVarSublevelsUp_rtable -
912 * Same as IncrementVarSublevelsUp, but to be invoked on a range table.
913 */
914 void
915 IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up,
916 int min_sublevels_up)
917 {
918 IncrementVarSublevelsUp_context context;
919
920 context.delta_sublevels_up = delta_sublevels_up;
921 context.min_sublevels_up = min_sublevels_up;
922
923 range_table_walker(rtable,
924 IncrementVarSublevelsUp_walker,
925 &context,
926 QTW_EXAMINE_RTES_BEFORE);
927 }
928
929 /*
930 * SetVarReturningType - adjust Var nodes for a specified varreturningtype.
931 *
932 * Find all Var nodes referring to the specified result relation in the given
933 * expression and set their varreturningtype to the specified value.
934 *
935 * NOTE: although this has the form of a walker, we cheat and modify the
936 * Var nodes in-place. The given expression tree should have been copied
937 * earlier to ensure that no unwanted side-effects occur!
938 */
939
940 typedef struct
941 {
942 int result_relation;
943 int sublevels_up;
944 VarReturningType returning_type;
945 } SetVarReturningType_context;
946
947 static bool
948 SetVarReturningType_walker(Node *node, SetVarReturningType_context *context)
949 {
950 if (node == NULL)
951 return false;
952 if (IsA(node, Var))
953 {
954 Var *var = (Var *) node;
955
956 if (var->varno == context->result_relation &&
957 var->varlevelsup == context->sublevels_up)
958 var->varreturningtype = context->returning_type;
959
960 return false;
961 }
962
963 if (IsA(node, Query))
964 {
965 /* Recurse into subselects */
966 bool result;
967
968 context->sublevels_up++;
969 result = query_tree_walker((Query *) node, SetVarReturningType_walker,
970 context, 0);
971 context->sublevels_up--;
972 return result;
973 }
974 return expression_tree_walker(node, SetVarReturningType_walker, context);
975 }
976
977 static void
978 SetVarReturningType(Node *node, int result_relation, int sublevels_up,
979 VarReturningType returning_type)
980 {
981 SetVarReturningType_context context;
982
983 context.result_relation = result_relation;
984 context.sublevels_up = sublevels_up;
985 context.returning_type = returning_type;
986
987 /* Expect to start with an expression */
988 SetVarReturningType_walker(node, &context);
989 }
990
991 /*
992 * rangeTableEntry_used - detect whether an RTE is referenced somewhere
993 * in var nodes or join or setOp trees of a query or expression.
994 */
995
996 typedef struct
997 {
998 int rt_index;
999 int sublevels_up;
1000 } rangeTableEntry_used_context;
1001
1002 static bool
1003 rangeTableEntry_used_walker(Node *node,
1004 rangeTableEntry_used_context *context)
1005 {
1006 if (node == NULL)
1007 return false;
1008 if (IsA(node, Var))
1009 {
1010 Var *var = (Var *) node;
1011
1012 if (var->varlevelsup == context->sublevels_up &&
1013 (var->varno == context->rt_index ||
1014 bms_is_member(context->rt_index, var->varnullingrels)))
1015 return true;
1016 return false;
1017 }
1018 if (IsA(node, CurrentOfExpr))
1019 {
1020 CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
1021
1022 if (context->sublevels_up == 0 &&
1023 cexpr->cvarno == context->rt_index)
1024 return true;
1025 return false;
1026 }
1027 if (IsA(node, RangeTblRef))
1028 {
1029 RangeTblRef *rtr = (RangeTblRef *) node;
1030
1031 if (rtr->rtindex == context->rt_index &&
1032 context->sublevels_up == 0)
1033 return true;
1034 /* the subquery itself is visited separately */
1035 return false;
1036 }
1037 if (IsA(node, JoinExpr))
1038 {
1039 JoinExpr *j = (JoinExpr *) node;
1040
1041 if (j->rtindex == context->rt_index &&
1042 context->sublevels_up == 0)
1043 return true;
1044 /* fall through to examine children */
1045 }
1046 /* Shouldn't need to handle planner auxiliary nodes here */
1047 Assert(!IsA(node, PlaceHolderVar));
1048 Assert(!IsA(node, PlanRowMark));
1049 Assert(!IsA(node, SpecialJoinInfo));
1050 Assert(!IsA(node, AppendRelInfo));
1051 Assert(!IsA(node, PlaceHolderInfo));
1052 Assert(!IsA(node, MinMaxAggInfo));
1053
1054 if (IsA(node, Query))
1055 {
1056 /* Recurse into subselects */
1057 bool result;
1058
1059 context->sublevels_up++;
1060 result = query_tree_walker((Query *) node, rangeTableEntry_used_walker,
1061 context, 0);
1062 context->sublevels_up--;
1063 return result;
1064 }
1065 return expression_tree_walker(node, rangeTableEntry_used_walker, context);
1066 }
1067
1068 bool
1069 rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
1070 {
1071 rangeTableEntry_used_context context;
1072
1073 context.rt_index = rt_index;
1074 context.sublevels_up = sublevels_up;
1075
1076 /*
1077 * Must be prepared to start with a Query or a bare expression tree; if
1078 * it's a Query, we don't want to increment sublevels_up.
1079 */
1080 return query_or_expression_tree_walker(node,
1081 rangeTableEntry_used_walker,
1082 &context,
1083 0);
1084 }
1085
1086
1087 /*
1088 * If the given Query is an INSERT ... SELECT construct, extract and
1089 * return the sub-Query node that represents the SELECT part. Otherwise
1090 * return the given Query.
1091 *
1092 * If subquery_ptr is not NULL, then *subquery_ptr is set to the location
1093 * of the link to the SELECT subquery inside parsetree, or NULL if not an
1094 * INSERT ... SELECT.
1095 *
1096 * This is a hack needed because transformations on INSERT ... SELECTs that
1097 * appear in rule actions should be applied to the source SELECT, not to the
1098 * INSERT part. Perhaps this can be cleaned up with redesigned querytrees.
1099 */
1100 Query *
1101 getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
1102 {
1103 Query *selectquery;
1104 RangeTblEntry *selectrte;
1105 RangeTblRef *rtr;
1106
1107 if (subquery_ptr)
1108 *subquery_ptr = NULL;
1109
1110 if (parsetree == NULL)
1111 return parsetree;
1112 if (parsetree->commandType != CMD_INSERT)
1113 return parsetree;
1114
1115 /*
1116 * Currently, this is ONLY applied to rule-action queries, and so we
1117 * expect to find the OLD and NEW placeholder entries in the given query.
1118 * If they're not there, it must be an INSERT/SELECT in which they've been
1119 * pushed down to the SELECT.
1120 */
1121 if (list_length(parsetree->rtable) >= 2 &&
1122 strcmp(rt_fetch(PRS2_OLD_VARNO, parsetree->rtable)->eref->aliasname,
1123 "old") == 0 &&
1124 strcmp(rt_fetch(PRS2_NEW_VARNO, parsetree->rtable)->eref->aliasname,
1125 "new") == 0)
1126 return parsetree;
1127 Assert(parsetree->jointree && IsA(parsetree->jointree, FromExpr));
1128 if (list_length(parsetree->jointree->fromlist) != 1)
1129 elog(ERROR, "expected to find SELECT subquery");
1130 rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
1131 if (!IsA(rtr, RangeTblRef))
1132 elog(ERROR, "expected to find SELECT subquery");
1133 selectrte = rt_fetch(rtr->rtindex, parsetree->rtable);
1134 if (!(selectrte->rtekind == RTE_SUBQUERY &&
1135 selectrte->subquery &&
1136 IsA(selectrte->subquery, Query) &&
1137 selectrte->subquery->commandType == CMD_SELECT))
1138 elog(ERROR, "expected to find SELECT subquery");
1139 selectquery = selectrte->subquery;
1140 if (list_length(selectquery->rtable) >= 2 &&
1141 strcmp(rt_fetch(PRS2_OLD_VARNO, selectquery->rtable)->eref->aliasname,
1142 "old") == 0 &&
1143 strcmp(rt_fetch(PRS2_NEW_VARNO, selectquery->rtable)->eref->aliasname,
1144 "new") == 0)
1145 {
1146 if (subquery_ptr)
1147 *subquery_ptr = &(selectrte->subquery);
1148 return selectquery;
1149 }
1150 elog(ERROR, "could not find rule placeholders");
1151 return NULL; /* not reached */
1152 }
1153
1154
1155 /*
1156 * Add the given qualifier condition to the query's WHERE clause
1157 */
1158 void
1159 AddQual(Query *parsetree, Node *qual)
1160 {
1161 Node *copy;
1162
1163 if (qual == NULL)
1164 return;
1165
1166 if (parsetree->commandType == CMD_UTILITY)
1167 {
1168 /*
1169 * There's noplace to put the qual on a utility statement.
1170 *
1171 * If it's a NOTIFY, silently ignore the qual; this means that the
1172 * NOTIFY will execute, whether or not there are any qualifying rows.
1173 * While clearly wrong, this is much more useful than refusing to
1174 * execute the rule at all, and extra NOTIFY events are harmless for
1175 * typical uses of NOTIFY.
1176 *
1177 * If it isn't a NOTIFY, error out, since unconditional execution of
1178 * other utility stmts is unlikely to be wanted. (This case is not
1179 * currently allowed anyway, but keep the test for safety.)
1180 */
1181 if (parsetree->utilityStmt && IsA(parsetree->utilityStmt, NotifyStmt))
1182 return;
1183 else
1184 ereport(ERROR,
1185 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1186 errmsg("conditional utility statements are not implemented")));
1187 }
1188
1189 if (parsetree->setOperations != NULL)
1190 {
1191 /*
1192 * There's noplace to put the qual on a setop statement, either. (This
1193 * could be fixed, but right now the planner simply ignores any qual
1194 * condition on a setop query.)
1195 */
1196 ereport(ERROR,
1197 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1198 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1199 }
1200
1201 /* INTERSECT wants the original, but we need to copy - Jan */
1202 copy = copyObject(qual);
1203
1204 parsetree->jointree->quals = make_and_qual(parsetree->jointree->quals,
1205 copy);
1206
1207 /*
1208 * We had better not have stuck an aggregate into the WHERE clause.
1209 */
1210 Assert(!contain_aggs_of_level(copy, 0));
1211
1212 /*
1213 * Make sure query is marked correctly if added qual has sublinks. Need
1214 * not search qual when query is already marked.
1215 */
1216 if (!parsetree->hasSubLinks)
1217 parsetree->hasSubLinks = checkExprHasSubLink(copy);
1218 }
1219
1220
1221 /*
1222 * Invert the given clause and add it to the WHERE qualifications of the
1223 * given querytree. Inversion means "x IS NOT TRUE", not just "NOT x",
1224 * else we will do the wrong thing when x evaluates to NULL.
1225 */
1226 void
1227 AddInvertedQual(Query *parsetree, Node *qual)
1228 {
1229 BooleanTest *invqual;
1230
1231 if (qual == NULL)
1232 return;
1233
1234 /* Need not copy input qual, because AddQual will... */
1235 invqual = makeNode(BooleanTest);
1236 invqual->arg = (Expr *) qual;
1237 invqual->booltesttype = IS_NOT_TRUE;
1238 invqual->location = -1;
1239
1240 AddQual(parsetree, (Node *) invqual);
1241 }
1242
1243
1244 /*
1245 * add_nulling_relids() finds Vars and PlaceHolderVars that belong to any
1246 * of the target_relids, and adds added_relids to their varnullingrels
1247 * and phnullingrels fields. If target_relids is NULL, all level-zero
1248 * Vars and PHVs are modified.
1249 */
1250 Node *
1251 add_nulling_relids(Node *node,
1252 const Bitmapset *target_relids,
1253 const Bitmapset *added_relids)
1254 {
1255 add_nulling_relids_context context;
1256
1257 context.target_relids = target_relids;
1258 context.added_relids = added_relids;
1259 context.sublevels_up = 0;
1260 return query_or_expression_tree_mutator(node,
1261 add_nulling_relids_mutator,
1262 &context,
1263 0);
1264 }
1265
1266 static Node *
1267 add_nulling_relids_mutator(Node *node,
1268 add_nulling_relids_context *context)
1269 {
1270 if (node == NULL)
1271 return NULL;
1272 if (IsA(node, Var))
1273 {
1274 Var *var = (Var *) node;
1275
1276 if (var->varlevelsup == context->sublevels_up &&
1277 (context->target_relids == NULL ||
1278 bms_is_member(var->varno, context->target_relids)))
1279 {
1280 Relids newnullingrels = bms_union(var->varnullingrels,
1281 context->added_relids);
1282
1283 /* Copy the Var ... */
1284 var = copyObject(var);
1285 /* ... and replace the copy's varnullingrels field */
1286 var->varnullingrels = newnullingrels;
1287 return (Node *) var;
1288 }
1289 /* Otherwise fall through to copy the Var normally */
1290 }
1291 else if (IsA(node, PlaceHolderVar))
1292 {
1293 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1294
1295 if (phv->phlevelsup == context->sublevels_up &&
1296 (context->target_relids == NULL ||
1297 bms_overlap(phv->phrels, context->target_relids)))
1298 {
1299 Relids newnullingrels = bms_union(phv->phnullingrels,
1300 context->added_relids);
1301
1302 /*
1303 * We don't modify the contents of the PHV's expression, only add
1304 * to phnullingrels. This corresponds to assuming that the PHV
1305 * will be evaluated at the same level as before, then perhaps be
1306 * nulled as it bubbles up. Hence, just flat-copy the node ...
1307 */
1308 phv = makeNode(PlaceHolderVar);
1309 memcpy(phv, node, sizeof(PlaceHolderVar));
1310 /* ... and replace the copy's phnullingrels field */
1311 phv->phnullingrels = newnullingrels;
1312 return (Node *) phv;
1313 }
1314 /* Otherwise fall through to copy the PlaceHolderVar normally */
1315 }
1316 else if (IsA(node, Query))
1317 {
1318 /* Recurse into RTE or sublink subquery */
1319 Query *newnode;
1320
1321 context->sublevels_up++;
1322 newnode = query_tree_mutator((Query *) node,
1323 add_nulling_relids_mutator,
1324 context,
1325 0);
1326 context->sublevels_up--;
1327 return (Node *) newnode;
1328 }
1329 return expression_tree_mutator(node, add_nulling_relids_mutator, context);
1330 }
1331
1332 /*
1333 * remove_nulling_relids() removes mentions of the specified RT index(es)
1334 * in Var.varnullingrels and PlaceHolderVar.phnullingrels fields within
1335 * the given expression, except in nodes belonging to rels listed in
1336 * except_relids.
1337 */
1338 Node *
1339 remove_nulling_relids(Node *node,
1340 const Bitmapset *removable_relids,
1341 const Bitmapset *except_relids)
1342 {
1343 remove_nulling_relids_context context;
1344
1345 context.removable_relids = removable_relids;
1346 context.except_relids = except_relids;
1347 context.sublevels_up = 0;
1348 return query_or_expression_tree_mutator(node,
1349 remove_nulling_relids_mutator,
1350 &context,
1351 0);
1352 }
1353
1354 static Node *
1355 remove_nulling_relids_mutator(Node *node,
1356 remove_nulling_relids_context *context)
1357 {
1358 if (node == NULL)
1359 return NULL;
1360 if (IsA(node, Var))
1361 {
1362 Var *var = (Var *) node;
1363
1364 if (var->varlevelsup == context->sublevels_up &&
1365 !bms_is_member(var->varno, context->except_relids) &&
1366 bms_overlap(var->varnullingrels, context->removable_relids))
1367 {
1368 /* Copy the Var ... */
1369 var = copyObject(var);
1370 /* ... and replace the copy's varnullingrels field */
1371 var->varnullingrels = bms_difference(var->varnullingrels,
1372 context->removable_relids);
1373 return (Node *) var;
1374 }
1375 /* Otherwise fall through to copy the Var normally */
1376 }
1377 else if (IsA(node, PlaceHolderVar))
1378 {
1379 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1380
1381 if (phv->phlevelsup == context->sublevels_up &&
1382 !bms_overlap(phv->phrels, context->except_relids))
1383 {
1384 /*
1385 * Note: it might seem desirable to remove the PHV altogether if
1386 * phnullingrels goes to empty. Currently we dare not do that
1387 * because we use PHVs in some cases to enforce separate identity
1388 * of subexpressions; see wrap_option usages in prepjointree.c.
1389 */
1390 /* Copy the PlaceHolderVar and mutate what's below ... */
1391 phv = (PlaceHolderVar *)
1392 expression_tree_mutator(node,
1393 remove_nulling_relids_mutator,
1394 context);
1395 /* ... and replace the copy's phnullingrels field */
1396 phv->phnullingrels = bms_difference(phv->phnullingrels,
1397 context->removable_relids);
1398 /* We must also update phrels, if it contains a removable RTI */
1399 phv->phrels = bms_difference(phv->phrels,
1400 context->removable_relids);
1401 Assert(!bms_is_empty(phv->phrels));
1402 return (Node *) phv;
1403 }
1404 /* Otherwise fall through to copy the PlaceHolderVar normally */
1405 }
1406 else if (IsA(node, Query))
1407 {
1408 /* Recurse into RTE or sublink subquery */
1409 Query *newnode;
1410
1411 context->sublevels_up++;
1412 newnode = query_tree_mutator((Query *) node,
1413 remove_nulling_relids_mutator,
1414 context,
1415 0);
1416 context->sublevels_up--;
1417 return (Node *) newnode;
1418 }
1419 return expression_tree_mutator(node, remove_nulling_relids_mutator, context);
1420 }
1421
1422
1423 /*
1424 * replace_rte_variables() finds all Vars in an expression tree
1425 * that reference a particular RTE, and replaces them with substitute
1426 * expressions obtained from a caller-supplied callback function.
1427 *
1428 * When invoking replace_rte_variables on a portion of a Query, pass the
1429 * address of the containing Query's hasSubLinks field as outer_hasSubLinks.
1430 * Otherwise, pass NULL, but inserting a SubLink into a non-Query expression
1431 * will then cause an error.
1432 *
1433 * Note: the business with inserted_sublink is needed to update hasSubLinks
1434 * in subqueries when the replacement adds a subquery inside a subquery.
1435 * Messy, isn't it? We do not need to do similar pushups for hasAggs,
1436 * because it isn't possible for this transformation to insert a level-zero
1437 * aggregate reference into a subquery --- it could only insert outer aggs.
1438 * Likewise for hasWindowFuncs.
1439 *
1440 * Note: usually, we'd not expose the mutator function or context struct
1441 * for a function like this. We do so because callbacks often find it
1442 * convenient to recurse directly to the mutator on sub-expressions of
1443 * what they will return.
1444 */
1445 Node *
1446 replace_rte_variables(Node *node, int target_varno, int sublevels_up,
1447 replace_rte_variables_callback callback,
1448 void *callback_arg,
1449 bool *outer_hasSubLinks)
1450 {
1451 Node *result;
1452 replace_rte_variables_context context;
1453
1454 context.callback = callback;
1455 context.callback_arg = callback_arg;
1456 context.target_varno = target_varno;
1457 context.sublevels_up = sublevels_up;
1458
1459 /*
1460 * We try to initialize inserted_sublink to true if there is no need to
1461 * detect new sublinks because the query already has some.
1462 */
1463 if (node && IsA(node, Query))
1464 context.inserted_sublink = ((Query *) node)->hasSubLinks;
1465 else if (outer_hasSubLinks)
1466 context.inserted_sublink = *outer_hasSubLinks;
1467 else
1468 context.inserted_sublink = false;
1469
1470 /*
1471 * Must be prepared to start with a Query or a bare expression tree; if
1472 * it's a Query, we don't want to increment sublevels_up.
1473 */
1474 result = query_or_expression_tree_mutator(node,
1475 replace_rte_variables_mutator,
1476 &context,
1477 0);
1478
1479 if (context.inserted_sublink)
1480 {
1481 if (result && IsA(result, Query))
1482 ((Query *) result)->hasSubLinks = true;
1483 else if (outer_hasSubLinks)
1484 *outer_hasSubLinks = true;
1485 else
1486 elog(ERROR, "replace_rte_variables inserted a SubLink, but has noplace to record it");
1487 }
1488
1489 return result;
1490 }
1491
1492 Node *
1493 replace_rte_variables_mutator(Node *node,
1494 replace_rte_variables_context *context)
1495 {
1496 if (node == NULL)
1497 return NULL;
1498 if (IsA(node, Var))
1499 {
1500 Var *var = (Var *) node;
1501
1502 if (var->varno == context->target_varno &&
1503 var->varlevelsup == context->sublevels_up)
1504 {
1505 /* Found a matching variable, make the substitution */
1506 Node *newnode;
1507
1508 newnode = context->callback(var, context);
1509 /* Detect if we are adding a sublink to query */
1510 if (!context->inserted_sublink)
1511 context->inserted_sublink = checkExprHasSubLink(newnode);
1512 return newnode;
1513 }
1514 /* otherwise fall through to copy the var normally */
1515 }
1516 else if (IsA(node, Query))
1517 {
1518 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1519 Query *newnode;
1520 bool save_inserted_sublink;
1521
1522 context->sublevels_up++;
1523 save_inserted_sublink = context->inserted_sublink;
1524 context->inserted_sublink = ((Query *) node)->hasSubLinks;
1525 newnode = query_tree_mutator((Query *) node,
1526 replace_rte_variables_mutator,
1527 context,
1528 0);
1529 newnode->hasSubLinks |= context->inserted_sublink;
1530 context->inserted_sublink = save_inserted_sublink;
1531 context->sublevels_up--;
1532 return (Node *) newnode;
1533 }
1534 return expression_tree_mutator(node, replace_rte_variables_mutator, context);
1535 }
1536
1537
1538 /*
1539 * map_variable_attnos() finds all user-column Vars in an expression tree
1540 * that reference a particular RTE, and adjusts their varattnos according
1541 * to the given mapping array (varattno n is replaced by attno_map[n-1]).
1542 * Vars for system columns are not modified.
1543 *
1544 * A zero in the mapping array represents a dropped column, which should not
1545 * appear in the expression.
1546 *
1547 * If the expression tree contains a whole-row Var for the target RTE,
1548 * *found_whole_row is set to true. In addition, if to_rowtype is
1549 * not InvalidOid, we replace the Var with a Var of that vartype, inserting
1550 * a ConvertRowtypeExpr to map back to the rowtype expected by the expression.
1551 * (Therefore, to_rowtype had better be a child rowtype of the rowtype of the
1552 * RTE we're changing references to.) Callers that don't provide to_rowtype
1553 * should report an error if *found_whole_row is true; we don't do that here
1554 * because we don't know exactly what wording for the error message would
1555 * be most appropriate. The caller will be aware of the context.
1556 *
1557 * This could be built using replace_rte_variables and a callback function,
1558 * but since we don't ever need to insert sublinks, replace_rte_variables is
1559 * overly complicated.
1560 */
1561
1562 typedef struct
1563 {
1564 int target_varno; /* RTE index to search for */
1565 int sublevels_up; /* (current) nesting depth */
1566 const AttrMap *attno_map; /* map array for user attnos */
1567 Oid to_rowtype; /* change whole-row Vars to this type */
1568 bool *found_whole_row; /* output flag */
1569 } map_variable_attnos_context;
1570
1571 static Node *
1572 map_variable_attnos_mutator(Node *node,
1573 map_variable_attnos_context *context)
1574 {
1575 if (node == NULL)
1576 return NULL;
1577 if (IsA(node, Var))
1578 {
1579 Var *var = (Var *) node;
1580
1581 if (var->varno == context->target_varno &&
1582 var->varlevelsup == context->sublevels_up)
1583 {
1584 /* Found a matching variable, make the substitution */
1585 Var *newvar = (Var *) palloc(sizeof(Var));
1586 int attno = var->varattno;
1587
1588 *newvar = *var; /* initially copy all fields of the Var */
1589
1590 if (attno > 0)
1591 {
1592 /* user-defined column, replace attno */
1593 if (attno > context->attno_map->maplen ||
1594 context->attno_map->attnums[attno - 1] == 0)
1595 elog(ERROR, "unexpected varattno %d in expression to be mapped",
1596 attno);
1597 newvar->varattno = context->attno_map->attnums[attno - 1];
1598 /* If the syntactic referent is same RTE, fix it too */
1599 if (newvar->varnosyn == context->target_varno)
1600 newvar->varattnosyn = newvar->varattno;
1601 }
1602 else if (attno == 0)
1603 {
1604 /* whole-row variable, warn caller */
1605 *(context->found_whole_row) = true;
1606
1607 /* If the caller expects us to convert the Var, do so. */
1608 if (OidIsValid(context->to_rowtype) &&
1609 context->to_rowtype != var->vartype)
1610 {
1611 ConvertRowtypeExpr *r;
1612
1613 /* This certainly won't work for a RECORD variable. */
1614 Assert(var->vartype != RECORDOID);
1615
1616 /* Var itself is changed to the requested type. */
1617 newvar->vartype = context->to_rowtype;
1618
1619 /*
1620 * Add a conversion node on top to convert back to the
1621 * original type expected by the expression.
1622 */
1623 r = makeNode(ConvertRowtypeExpr);
1624 r->arg = (Expr *) newvar;
1625 r->resulttype = var->vartype;
1626 r->convertformat = COERCE_IMPLICIT_CAST;
1627 r->location = -1;
1628
1629 return (Node *) r;
1630 }
1631 }
1632 return (Node *) newvar;
1633 }
1634 /* otherwise fall through to copy the var normally */
1635 }
1636 else if (IsA(node, ConvertRowtypeExpr))
1637 {
1638 ConvertRowtypeExpr *r = (ConvertRowtypeExpr *) node;
1639 Var *var = (Var *) r->arg;
1640
1641 /*
1642 * If this is coercing a whole-row Var that we need to convert, then
1643 * just convert the Var without adding an extra ConvertRowtypeExpr.
1644 * Effectively we're simplifying var::parenttype::grandparenttype into
1645 * just var::grandparenttype. This avoids building stacks of CREs if
1646 * this function is applied repeatedly.
1647 */
1648 if (IsA(var, Var) &&
1649 var->varno == context->target_varno &&
1650 var->varlevelsup == context->sublevels_up &&
1651 var->varattno == 0 &&
1652 OidIsValid(context->to_rowtype) &&
1653 context->to_rowtype != var->vartype)
1654 {
1655 ConvertRowtypeExpr *newnode;
1656 Var *newvar = (Var *) palloc(sizeof(Var));
1657
1658 /* whole-row variable, warn caller */
1659 *(context->found_whole_row) = true;
1660
1661 *newvar = *var; /* initially copy all fields of the Var */
1662
1663 /* This certainly won't work for a RECORD variable. */
1664 Assert(var->vartype != RECORDOID);
1665
1666 /* Var itself is changed to the requested type. */
1667 newvar->vartype = context->to_rowtype;
1668
1669 newnode = (ConvertRowtypeExpr *) palloc(sizeof(ConvertRowtypeExpr));
1670 *newnode = *r; /* initially copy all fields of the CRE */
1671 newnode->arg = (Expr *) newvar;
1672
1673 return (Node *) newnode;
1674 }
1675 /* otherwise fall through to process the expression normally */
1676 }
1677 else if (IsA(node, Query))
1678 {
1679 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1680 Query *newnode;
1681
1682 context->sublevels_up++;
1683 newnode = query_tree_mutator((Query *) node,
1684 map_variable_attnos_mutator,
1685 context,
1686 0);
1687 context->sublevels_up--;
1688 return (Node *) newnode;
1689 }
1690 return expression_tree_mutator(node, map_variable_attnos_mutator, context);
1691 }
1692
1693 Node *
1694 map_variable_attnos(Node *node,
1695 int target_varno, int sublevels_up,
1696 const AttrMap *attno_map,
1697 Oid to_rowtype, bool *found_whole_row)
1698 {
1699 map_variable_attnos_context context;
1700
1701 context.target_varno = target_varno;
1702 context.sublevels_up = sublevels_up;
1703 context.attno_map = attno_map;
1704 context.to_rowtype = to_rowtype;
1705 context.found_whole_row = found_whole_row;
1706
1707 *found_whole_row = false;
1708
1709 /*
1710 * Must be prepared to start with a Query or a bare expression tree; if
1711 * it's a Query, we don't want to increment sublevels_up.
1712 */
1713 return query_or_expression_tree_mutator(node,
1714 map_variable_attnos_mutator,
1715 &context,
1716 0);
1717 }
1718
1719
1720 /*
1721 * ReplaceVarsFromTargetList - replace Vars with items from a targetlist
1722 *
1723 * Vars matching target_varno and sublevels_up are replaced by the
1724 * entry with matching resno from targetlist, if there is one.
1725 *
1726 * If there is no matching resno for such a Var, the action depends on the
1727 * nomatch_option:
1728 * REPLACEVARS_REPORT_ERROR: throw an error
1729 * REPLACEVARS_CHANGE_VARNO: change Var's varno to nomatch_varno
1730 * REPLACEVARS_SUBSTITUTE_NULL: replace Var with a NULL Const of same type
1731 *
1732 * The caller must also provide target_rte, the RTE describing the target
1733 * relation. This is needed to handle whole-row Vars referencing the target.
1734 * We expand such Vars into RowExpr constructs.
1735 *
1736 * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must
1737 * provide result_relation, the index of the result relation in the rewritten
1738 * query. This is needed to handle OLD/NEW RETURNING list Vars referencing
1739 * target_varno. When such Vars are expanded, their varreturningtype is
1740 * copied onto any replacement Vars referencing result_relation. In addition,
1741 * if the replacement expression from the targetlist is not simply a Var
1742 * referencing result_relation, it is wrapped in a ReturningExpr node (causing
1743 * the executor to return NULL if the OLD/NEW row doesn't exist).
1744 *
1745 * Note that ReplaceVarFromTargetList always generates the replacement
1746 * expression with varlevelsup = 0. The caller is responsible for adjusting
1747 * the varlevelsup if needed. This simplifies the caller's life if it wants to
1748 * cache the replacement expressions.
1749 *
1750 * outer_hasSubLinks works the same as for replace_rte_variables().
1751 */
1752
1753 typedef struct
1754 {
1755 RangeTblEntry *target_rte;
1756 List *targetlist;
1757 int result_relation;
1758 ReplaceVarsNoMatchOption nomatch_option;
1759 int nomatch_varno;
1760 } ReplaceVarsFromTargetList_context;
1761
1762 static Node *
1763 ReplaceVarsFromTargetList_callback(Var *var,
1764 replace_rte_variables_context *context)
1765 {
1766 ReplaceVarsFromTargetList_context *rcon = (ReplaceVarsFromTargetList_context *) context->callback_arg;
1767 Node *newnode;
1768
1769 newnode = ReplaceVarFromTargetList(var,
1770 rcon->target_rte,
1771 rcon->targetlist,
1772 rcon->result_relation,
1773 rcon->nomatch_option,
1774 rcon->nomatch_varno);
1775
1776 /* Must adjust varlevelsup if replaced Var is within a subquery */
1777 if (var->varlevelsup > 0)
1778 IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
1779
1780 return newnode;
1781 }
1782
1783 Node *
1784 ReplaceVarFromTargetList(Var *var,
1785 RangeTblEntry *target_rte,
1786 List *targetlist,
1787 int result_relation,
1788 ReplaceVarsNoMatchOption nomatch_option,
1789 int nomatch_varno)
1790 {
1791 TargetEntry *tle;
1792
1793 if (var->varattno == InvalidAttrNumber)
1794 {
1795 /* Must expand whole-tuple reference into RowExpr */
1796 RowExpr *rowexpr;
1797 List *colnames;
1798 List *fields;
1799 ListCell *lc;
1800
1801 /*
1802 * If generating an expansion for a var of a named rowtype (ie, this
1803 * is a plain relation RTE), then we must include dummy items for
1804 * dropped columns. If the var is RECORD (ie, this is a JOIN), then
1805 * omit dropped columns. In the latter case, attach column names to
1806 * the RowExpr for use of the executor and ruleutils.c.
1807 *
1808 * In order to be able to cache the results, we always generate the
1809 * expansion with varlevelsup = 0. The caller is responsible for
1810 * adjusting it if needed.
1811 *
1812 * The varreturningtype is copied onto each individual field Var, so
1813 * that it is handled correctly when we recurse.
1814 */
1815 expandRTE(target_rte,
1816 var->varno, 0 /* not varlevelsup */ ,
1817 var->varreturningtype, var->location,
1818 (var->vartype != RECORDOID),
1819 &colnames, &fields);
1820 rowexpr = makeNode(RowExpr);
1821 /* the fields will be set below */
1822 rowexpr->args = NIL;
1823 rowexpr->row_typeid = var->vartype;
1824 rowexpr->row_format = COERCE_IMPLICIT_CAST;
1825 rowexpr->colnames = (var->vartype == RECORDOID) ? colnames : NIL;
1826 rowexpr->location = var->location;
1827 /* Adjust the generated per-field Vars... */
1828 foreach(lc, fields)
1829 {
1830 Node *field = lfirst(lc);
1831
1832 if (field && IsA(field, Var))
1833 field = ReplaceVarFromTargetList((Var *) field,
1834 target_rte,
1835 targetlist,
1836 result_relation,
1837 nomatch_option,
1838 nomatch_varno);
1839 rowexpr->args = lappend(rowexpr->args, field);
1840 }
1841
1842 /* Wrap it in a ReturningExpr, if needed, per comments above */
1843 if (var->varreturningtype != VAR_RETURNING_DEFAULT)
1844 {
1845 ReturningExpr *rexpr = makeNode(ReturningExpr);
1846
1847 rexpr->retlevelsup = 0;
1848 rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
1849 rexpr->retexpr = (Expr *) rowexpr;
1850
1851 return (Node *) rexpr;
1852 }
1853
1854 return (Node *) rowexpr;
1855 }
1856
1857 /* Normal case referencing one targetlist element */
1858 tle = get_tle_by_resno(targetlist, var->varattno);
1859
1860 if (tle == NULL || tle->resjunk)
1861 {
1862 /* Failed to find column in targetlist */
1863 switch (nomatch_option)
1864 {
1865 case REPLACEVARS_REPORT_ERROR:
1866 /* fall through, throw error below */
1867 break;
1868
1869 case REPLACEVARS_CHANGE_VARNO:
1870 var = copyObject(var);
1871 var->varno = nomatch_varno;
1872 var->varlevelsup = 0;
1873 /* we leave the syntactic referent alone */
1874 return (Node *) var;
1875
1876 case REPLACEVARS_SUBSTITUTE_NULL:
1877 {
1878 /*
1879 * If Var is of domain type, we must add a CoerceToDomain
1880 * node, in case there is a NOT NULL domain constraint.
1881 */
1882 int16 vartyplen;
1883 bool vartypbyval;
1884
1885 get_typlenbyval(var->vartype, &vartyplen, &vartypbyval);
1886 return coerce_null_to_domain(var->vartype,
1887 var->vartypmod,
1888 var->varcollid,
1889 vartyplen,
1890 vartypbyval);
1891 }
1892 }
1893 elog(ERROR, "could not find replacement targetlist entry for attno %d",
1894 var->varattno);
1895 return NULL; /* keep compiler quiet */
1896 }
1897 else
1898 {
1899 /* Make a copy of the tlist item to return */
1900 Expr *newnode = copyObject(tle->expr);
1901
1902 /*
1903 * Check to see if the tlist item contains a PARAM_MULTIEXPR Param,
1904 * and throw error if so. This case could only happen when expanding
1905 * an ON UPDATE rule's NEW variable and the referenced tlist item in
1906 * the original UPDATE command is part of a multiple assignment. There
1907 * seems no practical way to handle such cases without multiple
1908 * evaluation of the multiple assignment's sub-select, which would
1909 * create semantic oddities that users of rules would probably prefer
1910 * not to cope with. So treat it as an unimplemented feature.
1911 */
1912 if (contains_multiexpr_param((Node *) newnode, NULL))
1913 ereport(ERROR,
1914 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1915 errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command")));
1916
1917 /* Handle any OLD/NEW RETURNING list Vars */
1918 if (var->varreturningtype != VAR_RETURNING_DEFAULT)
1919 {
1920 /*
1921 * Copy varreturningtype onto any Vars in the tlist item that
1922 * refer to result_relation (which had better be non-zero).
1923 */
1924 if (result_relation == 0)
1925 elog(ERROR, "variable returning old/new found outside RETURNING list");
1926
1927 SetVarReturningType((Node *) newnode, result_relation,
1928 0, var->varreturningtype);
1929
1930 /* Wrap it in a ReturningExpr, if needed, per comments above */
1931 if (!IsA(newnode, Var) ||
1932 ((Var *) newnode)->varno != result_relation ||
1933 ((Var *) newnode)->varlevelsup != 0)
1934 {
1935 ReturningExpr *rexpr = makeNode(ReturningExpr);
1936
1937 rexpr->retlevelsup = 0;
1938 rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD);
1939 rexpr->retexpr = newnode;
1940
1941 newnode = (Expr *) rexpr;
1942 }
1943 }
1944
1945 return (Node *) newnode;
1946 }
1947 }
1948
1949 Node *
1950 ReplaceVarsFromTargetList(Node *node,
1951 int target_varno, int sublevels_up,
1952 RangeTblEntry *target_rte,
1953 List *targetlist,
1954 int result_relation,
1955 ReplaceVarsNoMatchOption nomatch_option,
1956 int nomatch_varno,
1957 bool *outer_hasSubLinks)
1958 {
1959 ReplaceVarsFromTargetList_context context;
1960
1961 context.target_rte = target_rte;
1962 context.targetlist = targetlist;
1963 context.result_relation = result_relation;
1964 context.nomatch_option = nomatch_option;
1965 context.nomatch_varno = nomatch_varno;
1966
1967 return replace_rte_variables(node, target_varno, sublevels_up,
1968 ReplaceVarsFromTargetList_callback,
1969 &context,
1970 outer_hasSubLinks);
1971 }