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