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