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