PostgreSQL Source Code  git master
rewriteHandler.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * rewriteHandler.c
4  * Primary module of query rewriter.
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/rewrite/rewriteHandler.c
11  *
12  * NOTES
13  * Some of the terms used in this file are of historic nature: "retrieve"
14  * was the PostQUEL keyword for what today is SELECT. "RIR" stands for
15  * "Retrieve-Instead-Retrieve", that is an ON SELECT DO INSTEAD SELECT rule
16  * (which has to be unconditional and where only one rule can exist on each
17  * relation).
18  *
19  *-------------------------------------------------------------------------
20  */
21 #include "postgres.h"
22 
23 #include "access/relation.h"
24 #include "access/sysattr.h"
25 #include "access/table.h"
26 #include "catalog/dependency.h"
27 #include "catalog/pg_type.h"
28 #include "commands/trigger.h"
29 #include "foreign/fdwapi.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "nodes/nodeFuncs.h"
33 #include "optimizer/optimizer.h"
34 #include "parser/analyze.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_relation.h"
37 #include "parser/parsetree.h"
38 #include "rewrite/rewriteDefine.h"
39 #include "rewrite/rewriteHandler.h"
40 #include "rewrite/rewriteManip.h"
42 #include "rewrite/rowsecurity.h"
43 #include "utils/builtins.h"
44 #include "utils/lsyscache.h"
45 #include "utils/rel.h"
46 
47 
48 /* We use a list of these to detect recursion in RewriteQuery */
49 typedef struct rewrite_event
50 {
51  Oid relation; /* OID of relation having rules */
52  CmdType event; /* type of rule being fired */
54 
56 {
57  bool for_execute; /* AcquireRewriteLocks' forExecute param */
59 
60 static bool acquireLocksOnSubLinks(Node *node,
62 static Query *rewriteRuleAction(Query *parsetree,
63  Query *rule_action,
64  Node *rule_qual,
65  int rt_index,
66  CmdType event,
67  bool *returning_flag);
68 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
69 static List *rewriteTargetListIU(List *targetList,
70  CmdType commandType,
71  OverridingKind override,
72  Relation target_relation,
73  int result_rti,
74  RangeTblEntry *values_rte,
75  int values_rte_index,
76  Bitmapset **unused_values_attrnos);
78  TargetEntry *prior_tle,
79  const char *attrName);
80 static Node *get_assignment_input(Node *node);
82 static bool rewriteValuesRTE(Query *parsetree, RangeTblEntry *rte, int rti,
83  Relation target_relation, bool force_nulls,
84  Bitmapset *unused_cols);
85 static void markQueryForLocking(Query *qry, Node *jtnode,
86  LockClauseStrength strength, LockWaitPolicy waitPolicy,
87  bool pushedDown);
88 static List *matchLocks(CmdType event, RuleLock *rulelocks,
89  int varno, Query *parsetree, bool *hasUpdate);
90 static Query *fireRIRrules(Query *parsetree, List *activeRIRs);
92 static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist);
93 
94 
95 /*
96  * AcquireRewriteLocks -
97  * Acquire suitable locks on all the relations mentioned in the Query.
98  * These locks will ensure that the relation schemas don't change under us
99  * while we are rewriting, planning, and executing the query.
100  *
101  * Caution: this may modify the querytree, therefore caller should usually
102  * have done a copyObject() to make a writable copy of the querytree in the
103  * current memory context.
104  *
105  * forExecute indicates that the query is about to be executed. If so,
106  * we'll acquire the lock modes specified in the RTE rellockmode fields.
107  * If forExecute is false, AccessShareLock is acquired on all relations.
108  * This case is suitable for ruleutils.c, for example, where we only need
109  * schema stability and we don't intend to actually modify any relations.
110  *
111  * forUpdatePushedDown indicates that a pushed-down FOR [KEY] UPDATE/SHARE
112  * applies to the current subquery, requiring all rels to be opened with at
113  * least RowShareLock. This should always be false at the top of the
114  * recursion. When it is true, we adjust RTE rellockmode fields to reflect
115  * the higher lock level. This flag is ignored if forExecute is false.
116  *
117  * A secondary purpose of this routine is to fix up JOIN RTE references to
118  * dropped columns (see details below). Such RTEs are modified in-place.
119  *
120  * This processing can, and for efficiency's sake should, be skipped when the
121  * querytree has just been built by the parser: parse analysis already got
122  * all the same locks we'd get here, and the parser will have omitted dropped
123  * columns from JOINs to begin with. But we must do this whenever we are
124  * dealing with a querytree produced earlier than the current command.
125  *
126  * About JOINs and dropped columns: although the parser never includes an
127  * already-dropped column in a JOIN RTE's alias var list, it is possible for
128  * such a list in a stored rule to include references to dropped columns.
129  * (If the column is not explicitly referenced anywhere else in the query,
130  * the dependency mechanism won't consider it used by the rule and so won't
131  * prevent the column drop.) To support get_rte_attribute_is_dropped(), we
132  * replace join alias vars that reference dropped columns with null pointers.
133  *
134  * (In PostgreSQL 8.0, we did not do this processing but instead had
135  * get_rte_attribute_is_dropped() recurse to detect dropped columns in joins.
136  * That approach had horrible performance unfortunately; in particular
137  * construction of a nested join was O(N^2) in the nesting depth.)
138  */
139 void
141  bool forExecute,
142  bool forUpdatePushedDown)
143 {
144  ListCell *l;
145  int rt_index;
147 
148  context.for_execute = forExecute;
149 
150  /*
151  * First, process RTEs of the current query level.
152  */
153  rt_index = 0;
154  foreach(l, parsetree->rtable)
155  {
156  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
157  Relation rel;
158  LOCKMODE lockmode;
159  List *newaliasvars;
160  Index curinputvarno;
161  RangeTblEntry *curinputrte;
162  ListCell *ll;
163 
164  ++rt_index;
165  switch (rte->rtekind)
166  {
167  case RTE_RELATION:
168 
169  /*
170  * Grab the appropriate lock type for the relation, and do not
171  * release it until end of transaction. This protects the
172  * rewriter, planner, and executor against schema changes
173  * mid-query.
174  *
175  * If forExecute is false, ignore rellockmode and just use
176  * AccessShareLock.
177  */
178  if (!forExecute)
179  lockmode = AccessShareLock;
180  else if (forUpdatePushedDown)
181  {
182  /* Upgrade RTE's lock mode to reflect pushed-down lock */
183  if (rte->rellockmode == AccessShareLock)
184  rte->rellockmode = RowShareLock;
185  lockmode = rte->rellockmode;
186  }
187  else
188  lockmode = rte->rellockmode;
189 
190  rel = table_open(rte->relid, lockmode);
191 
192  /*
193  * While we have the relation open, update the RTE's relkind,
194  * just in case it changed since this rule was made.
195  */
196  rte->relkind = rel->rd_rel->relkind;
197 
198  table_close(rel, NoLock);
199  break;
200 
201  case RTE_JOIN:
202 
203  /*
204  * Scan the join's alias var list to see if any columns have
205  * been dropped, and if so replace those Vars with null
206  * pointers.
207  *
208  * Since a join has only two inputs, we can expect to see
209  * multiple references to the same input RTE; optimize away
210  * multiple fetches.
211  */
212  newaliasvars = NIL;
213  curinputvarno = 0;
214  curinputrte = NULL;
215  foreach(ll, rte->joinaliasvars)
216  {
217  Var *aliasitem = (Var *) lfirst(ll);
218  Var *aliasvar = aliasitem;
219 
220  /* Look through any implicit coercion */
221  aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
222 
223  /*
224  * If the list item isn't a simple Var, then it must
225  * represent a merged column, ie a USING column, and so it
226  * couldn't possibly be dropped, since it's referenced in
227  * the join clause. (Conceivably it could also be a null
228  * pointer already? But that's OK too.)
229  */
230  if (aliasvar && IsA(aliasvar, Var))
231  {
232  /*
233  * The elements of an alias list have to refer to
234  * earlier RTEs of the same rtable, because that's the
235  * order the planner builds things in. So we already
236  * processed the referenced RTE, and so it's safe to
237  * use get_rte_attribute_is_dropped on it. (This might
238  * not hold after rewriting or planning, but it's OK
239  * to assume here.)
240  */
241  Assert(aliasvar->varlevelsup == 0);
242  if (aliasvar->varno != curinputvarno)
243  {
244  curinputvarno = aliasvar->varno;
245  if (curinputvarno >= rt_index)
246  elog(ERROR, "unexpected varno %d in JOIN RTE %d",
247  curinputvarno, rt_index);
248  curinputrte = rt_fetch(curinputvarno,
249  parsetree->rtable);
250  }
251  if (get_rte_attribute_is_dropped(curinputrte,
252  aliasvar->varattno))
253  {
254  /* Replace the join alias item with a NULL */
255  aliasitem = NULL;
256  }
257  }
258  newaliasvars = lappend(newaliasvars, aliasitem);
259  }
260  rte->joinaliasvars = newaliasvars;
261  break;
262 
263  case RTE_SUBQUERY:
264 
265  /*
266  * The subquery RTE itself is all right, but we have to
267  * recurse to process the represented subquery.
268  */
270  forExecute,
271  (forUpdatePushedDown ||
272  get_parse_rowmark(parsetree, rt_index) != NULL));
273  break;
274 
275  default:
276  /* ignore other types of RTEs */
277  break;
278  }
279  }
280 
281  /* Recurse into subqueries in WITH */
282  foreach(l, parsetree->cteList)
283  {
284  CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
285 
286  AcquireRewriteLocks((Query *) cte->ctequery, forExecute, false);
287  }
288 
289  /*
290  * Recurse into sublink subqueries, too. But we already did the ones in
291  * the rtable and cteList.
292  */
293  if (parsetree->hasSubLinks)
294  query_tree_walker(parsetree, acquireLocksOnSubLinks, &context,
296 }
297 
298 /*
299  * Walker to find sublink subqueries for AcquireRewriteLocks
300  */
301 static bool
303 {
304  if (node == NULL)
305  return false;
306  if (IsA(node, SubLink))
307  {
308  SubLink *sub = (SubLink *) node;
309 
310  /* Do what we came for */
312  context->for_execute,
313  false);
314  /* Fall through to process lefthand args of SubLink */
315  }
316 
317  /*
318  * Do NOT recurse into Query nodes, because AcquireRewriteLocks already
319  * processed subselects of subselects for us.
320  */
321  return expression_tree_walker(node, acquireLocksOnSubLinks, context);
322 }
323 
324 
325 /*
326  * rewriteRuleAction -
327  * Rewrite the rule action with appropriate qualifiers (taken from
328  * the triggering query).
329  *
330  * Input arguments:
331  * parsetree - original query
332  * rule_action - one action (query) of a rule
333  * rule_qual - WHERE condition of rule, or NULL if unconditional
334  * rt_index - RT index of result relation in original query
335  * event - type of rule event
336  * Output arguments:
337  * *returning_flag - set true if we rewrite RETURNING clause in rule_action
338  * (must be initialized to false)
339  * Return value:
340  * rewritten form of rule_action
341  */
342 static Query *
344  Query *rule_action,
345  Node *rule_qual,
346  int rt_index,
347  CmdType event,
348  bool *returning_flag)
349 {
350  int current_varno,
351  new_varno;
352  int rt_length;
353  Query *sub_action;
354  Query **sub_action_ptr;
356 
357  context.for_execute = true;
358 
359  /*
360  * Make modifiable copies of rule action and qual (what we're passed are
361  * the stored versions in the relcache; don't touch 'em!).
362  */
363  rule_action = copyObject(rule_action);
364  rule_qual = copyObject(rule_qual);
365 
366  /*
367  * Acquire necessary locks and fix any deleted JOIN RTE entries.
368  */
369  AcquireRewriteLocks(rule_action, true, false);
370  (void) acquireLocksOnSubLinks(rule_qual, &context);
371 
372  current_varno = rt_index;
373  rt_length = list_length(parsetree->rtable);
374  new_varno = PRS2_NEW_VARNO + rt_length;
375 
376  /*
377  * Adjust rule action and qual to offset its varnos, so that we can merge
378  * its rtable with the main parsetree's rtable.
379  *
380  * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
381  * will be in the SELECT part, and we have to modify that rather than the
382  * top-level INSERT (kluge!).
383  */
384  sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
385 
386  OffsetVarNodes((Node *) sub_action, rt_length, 0);
387  OffsetVarNodes(rule_qual, rt_length, 0);
388  /* but references to OLD should point at original rt_index */
389  ChangeVarNodes((Node *) sub_action,
390  PRS2_OLD_VARNO + rt_length, rt_index, 0);
391  ChangeVarNodes(rule_qual,
392  PRS2_OLD_VARNO + rt_length, rt_index, 0);
393 
394  /*
395  * Generate expanded rtable consisting of main parsetree's rtable plus
396  * rule action's rtable; this becomes the complete rtable for the rule
397  * action. Some of the entries may be unused after we finish rewriting,
398  * but we leave them all in place for two reasons:
399  *
400  * We'd have a much harder job to adjust the query's varnos if we
401  * selectively removed RT entries.
402  *
403  * If the rule is INSTEAD, then the original query won't be executed at
404  * all, and so its rtable must be preserved so that the executor will do
405  * the correct permissions checks on it.
406  *
407  * RT entries that are not referenced in the completed jointree will be
408  * ignored by the planner, so they do not affect query semantics. But any
409  * permissions checks specified in them will be applied during executor
410  * startup (see ExecCheckRTEPerms()). This allows us to check that the
411  * caller has, say, insert-permission on a view, when the view is not
412  * semantically referenced at all in the resulting query.
413  *
414  * When a rule is not INSTEAD, the permissions checks done on its copied
415  * RT entries will be redundant with those done during execution of the
416  * original query, but we don't bother to treat that case differently.
417  *
418  * NOTE: because planner will destructively alter rtable, we must ensure
419  * that rule action's rtable is separate and shares no substructure with
420  * the main rtable. Hence do a deep copy here.
421  */
422  sub_action->rtable = list_concat(copyObject(parsetree->rtable),
423  sub_action->rtable);
424 
425  /*
426  * There could have been some SubLinks in parsetree's rtable, in which
427  * case we'd better mark the sub_action correctly.
428  */
429  if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
430  {
431  ListCell *lc;
432 
433  foreach(lc, parsetree->rtable)
434  {
435  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
436 
437  switch (rte->rtekind)
438  {
439  case RTE_RELATION:
440  sub_action->hasSubLinks =
442  break;
443  case RTE_FUNCTION:
444  sub_action->hasSubLinks =
446  break;
447  case RTE_TABLEFUNC:
448  sub_action->hasSubLinks =
450  break;
451  case RTE_VALUES:
452  sub_action->hasSubLinks =
454  break;
455  default:
456  /* other RTE types don't contain bare expressions */
457  break;
458  }
459  if (sub_action->hasSubLinks)
460  break; /* no need to keep scanning rtable */
461  }
462  }
463 
464  /*
465  * Also, we might have absorbed some RTEs with RLS conditions into the
466  * sub_action. If so, mark it as hasRowSecurity, whether or not those
467  * RTEs will be referenced after we finish rewriting. (Note: currently
468  * this is a no-op because RLS conditions aren't added till later, but it
469  * seems like good future-proofing to do this anyway.)
470  */
471  sub_action->hasRowSecurity |= parsetree->hasRowSecurity;
472 
473  /*
474  * Each rule action's jointree should be the main parsetree's jointree
475  * plus that rule's jointree, but usually *without* the original rtindex
476  * that we're replacing (if present, which it won't be for INSERT). Note
477  * that if the rule action refers to OLD, its jointree will add a
478  * reference to rt_index. If the rule action doesn't refer to OLD, but
479  * either the rule_qual or the user query quals do, then we need to keep
480  * the original rtindex in the jointree to provide data for the quals. We
481  * don't want the original rtindex to be joined twice, however, so avoid
482  * keeping it if the rule action mentions it.
483  *
484  * As above, the action's jointree must not share substructure with the
485  * main parsetree's.
486  */
487  if (sub_action->commandType != CMD_UTILITY)
488  {
489  bool keeporig;
490  List *newjointree;
491 
492  Assert(sub_action->jointree != NULL);
493  keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
494  rt_index, 0)) &&
495  (rangeTableEntry_used(rule_qual, rt_index, 0) ||
496  rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
497  newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
498  if (newjointree != NIL)
499  {
500  /*
501  * If sub_action is a setop, manipulating its jointree will do no
502  * good at all, because the jointree is dummy. (Perhaps someday
503  * we could push the joining and quals down to the member
504  * statements of the setop?)
505  */
506  if (sub_action->setOperations != NULL)
507  ereport(ERROR,
508  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
509  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
510 
511  sub_action->jointree->fromlist =
512  list_concat(newjointree, sub_action->jointree->fromlist);
513 
514  /*
515  * There could have been some SubLinks in newjointree, in which
516  * case we'd better mark the sub_action correctly.
517  */
518  if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
519  sub_action->hasSubLinks =
520  checkExprHasSubLink((Node *) newjointree);
521  }
522  }
523 
524  /*
525  * If the original query has any CTEs, copy them into the rule action. But
526  * we don't need them for a utility action.
527  */
528  if (parsetree->cteList != NIL && sub_action->commandType != CMD_UTILITY)
529  {
530  ListCell *lc;
531 
532  /*
533  * Annoying implementation restriction: because CTEs are identified by
534  * name within a cteList, we can't merge a CTE from the original query
535  * if it has the same name as any CTE in the rule action.
536  *
537  * This could possibly be fixed by using some sort of internally
538  * generated ID, instead of names, to link CTE RTEs to their CTEs.
539  */
540  foreach(lc, parsetree->cteList)
541  {
542  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
543  ListCell *lc2;
544 
545  foreach(lc2, sub_action->cteList)
546  {
547  CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(lc2);
548 
549  if (strcmp(cte->ctename, cte2->ctename) == 0)
550  ereport(ERROR,
551  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
552  errmsg("WITH query name \"%s\" appears in both a rule action and the query being rewritten",
553  cte->ctename)));
554  }
555  }
556 
557  /* OK, it's safe to combine the CTE lists */
558  sub_action->cteList = list_concat(sub_action->cteList,
559  copyObject(parsetree->cteList));
560  }
561 
562  /*
563  * Event Qualification forces copying of parsetree and splitting into two
564  * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
565  * onto rule action
566  */
567  AddQual(sub_action, rule_qual);
568 
569  AddQual(sub_action, parsetree->jointree->quals);
570 
571  /*
572  * Rewrite new.attribute with right hand side of target-list entry for
573  * appropriate field name in insert/update.
574  *
575  * KLUGE ALERT: since ReplaceVarsFromTargetList returns a mutated copy, we
576  * can't just apply it to sub_action; we have to remember to update the
577  * sublink inside rule_action, too.
578  */
579  if ((event == CMD_INSERT || event == CMD_UPDATE) &&
580  sub_action->commandType != CMD_UTILITY)
581  {
582  sub_action = (Query *)
583  ReplaceVarsFromTargetList((Node *) sub_action,
584  new_varno,
585  0,
586  rt_fetch(new_varno, sub_action->rtable),
587  parsetree->targetList,
588  (event == CMD_UPDATE) ?
591  current_varno,
592  NULL);
593  if (sub_action_ptr)
594  *sub_action_ptr = sub_action;
595  else
596  rule_action = sub_action;
597  }
598 
599  /*
600  * If rule_action has a RETURNING clause, then either throw it away if the
601  * triggering query has no RETURNING clause, or rewrite it to emit what
602  * the triggering query's RETURNING clause asks for. Throw an error if
603  * more than one rule has a RETURNING clause.
604  */
605  if (!parsetree->returningList)
606  rule_action->returningList = NIL;
607  else if (rule_action->returningList)
608  {
609  if (*returning_flag)
610  ereport(ERROR,
611  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
612  errmsg("cannot have RETURNING lists in multiple rules")));
613  *returning_flag = true;
614  rule_action->returningList = (List *)
616  parsetree->resultRelation,
617  0,
618  rt_fetch(parsetree->resultRelation,
619  parsetree->rtable),
620  rule_action->returningList,
622  0,
623  &rule_action->hasSubLinks);
624 
625  /*
626  * There could have been some SubLinks in parsetree's returningList,
627  * in which case we'd better mark the rule_action correctly.
628  */
629  if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
630  rule_action->hasSubLinks =
631  checkExprHasSubLink((Node *) rule_action->returningList);
632  }
633 
634  return rule_action;
635 }
636 
637 /*
638  * Copy the query's jointree list, and optionally attempt to remove any
639  * occurrence of the given rt_index as a top-level join item (we do not look
640  * for it within join items; this is OK because we are only expecting to find
641  * it as an UPDATE or DELETE target relation, which will be at the top level
642  * of the join). Returns modified jointree list --- this is a separate copy
643  * sharing no nodes with the original.
644  */
645 static List *
646 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
647 {
648  List *newjointree = copyObject(parsetree->jointree->fromlist);
649  ListCell *l;
650 
651  if (removert)
652  {
653  foreach(l, newjointree)
654  {
655  RangeTblRef *rtr = lfirst(l);
656 
657  if (IsA(rtr, RangeTblRef) &&
658  rtr->rtindex == rt_index)
659  {
660  newjointree = foreach_delete_current(newjointree, l);
661  break;
662  }
663  }
664  }
665  return newjointree;
666 }
667 
668 
669 /*
670  * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
671  *
672  * This has the following responsibilities:
673  *
674  * 1. For an INSERT, add tlist entries to compute default values for any
675  * attributes that have defaults and are not assigned to in the given tlist.
676  * (We do not insert anything for default-less attributes, however. The
677  * planner will later insert NULLs for them, but there's no reason to slow
678  * down rewriter processing with extra tlist nodes.) Also, for both INSERT
679  * and UPDATE, replace explicit DEFAULT specifications with column default
680  * expressions.
681  *
682  * 2. For an UPDATE on a trigger-updatable view, add tlist entries for any
683  * unassigned-to attributes, assigning them their old values. These will
684  * later get expanded to the output values of the view. (This is equivalent
685  * to what the planner's expand_targetlist() will do for UPDATE on a regular
686  * table, but it's more convenient to do it here while we still have easy
687  * access to the view's original RT index.) This is only necessary for
688  * trigger-updatable views, for which the view remains the result relation of
689  * the query. For auto-updatable views we must not do this, since it might
690  * add assignments to non-updatable view columns. For rule-updatable views it
691  * is unnecessary extra work, since the query will be rewritten with a
692  * different result relation which will be processed when we recurse via
693  * RewriteQuery.
694  *
695  * 3. Merge multiple entries for the same target attribute, or declare error
696  * if we can't. Multiple entries are only allowed for INSERT/UPDATE of
697  * portions of an array or record field, for example
698  * UPDATE table SET foo[2] = 42, foo[4] = 43;
699  * We can merge such operations into a single assignment op. Essentially,
700  * the expression we want to produce in this case is like
701  * foo = array_set_element(array_set_element(foo, 2, 42), 4, 43)
702  *
703  * 4. Sort the tlist into standard order: non-junk fields in order by resno,
704  * then junk fields (these in no particular order).
705  *
706  * We must do items 1,2,3 before firing rewrite rules, else rewritten
707  * references to NEW.foo will produce wrong or incomplete results. Item 4
708  * is not needed for rewriting, but will be needed by the planner, and we
709  * can do it essentially for free while handling the other items.
710  *
711  * Note that for an inheritable UPDATE, this processing is only done once,
712  * using the parent relation as reference. It must not do anything that
713  * will not be correct when transposed to the child relation(s). (Step 4
714  * is incorrect by this light, since child relations might have different
715  * column ordering, but the planner will fix things by re-sorting the tlist
716  * for each child.)
717  *
718  * If values_rte is non-NULL (i.e., we are doing a multi-row INSERT using
719  * values from a VALUES RTE), we populate *unused_values_attrnos with the
720  * attribute numbers of any unused columns from the VALUES RTE. This can
721  * happen for identity and generated columns whose targetlist entries are
722  * replaced with generated expressions (if INSERT ... OVERRIDING USER VALUE is
723  * used, or all the values to be inserted are DEFAULT). This information is
724  * required by rewriteValuesRTE() to handle any DEFAULT items in the unused
725  * columns. The caller must have initialized *unused_values_attrnos to NULL.
726  */
727 static List *
729  CmdType commandType,
730  OverridingKind override,
731  Relation target_relation,
732  int result_rti,
733  RangeTblEntry *values_rte,
734  int values_rte_index,
735  Bitmapset **unused_values_attrnos)
736 {
737  TargetEntry **new_tles;
738  List *new_tlist = NIL;
739  List *junk_tlist = NIL;
740  Form_pg_attribute att_tup;
741  int attrno,
742  next_junk_attrno,
743  numattrs;
744  ListCell *temp;
745  Bitmapset *default_only_cols = NULL;
746 
747  /*
748  * We process the normal (non-junk) attributes by scanning the input tlist
749  * once and transferring TLEs into an array, then scanning the array to
750  * build an output tlist. This avoids O(N^2) behavior for large numbers
751  * of attributes.
752  *
753  * Junk attributes are tossed into a separate list during the same tlist
754  * scan, then appended to the reconstructed tlist.
755  */
756  numattrs = RelationGetNumberOfAttributes(target_relation);
757  new_tles = (TargetEntry **) palloc0(numattrs * sizeof(TargetEntry *));
758  next_junk_attrno = numattrs + 1;
759 
760  foreach(temp, targetList)
761  {
762  TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
763 
764  if (!old_tle->resjunk)
765  {
766  /* Normal attr: stash it into new_tles[] */
767  attrno = old_tle->resno;
768  if (attrno < 1 || attrno > numattrs)
769  elog(ERROR, "bogus resno %d in targetlist", attrno);
770  att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
771 
772  /* We can (and must) ignore deleted attributes */
773  if (att_tup->attisdropped)
774  continue;
775 
776  /* Merge with any prior assignment to same attribute */
777  new_tles[attrno - 1] =
778  process_matched_tle(old_tle,
779  new_tles[attrno - 1],
780  NameStr(att_tup->attname));
781  }
782  else
783  {
784  /*
785  * Copy all resjunk tlist entries to junk_tlist, and assign them
786  * resnos above the last real resno.
787  *
788  * Typical junk entries include ORDER BY or GROUP BY expressions
789  * (are these actually possible in an INSERT or UPDATE?), system
790  * attribute references, etc.
791  */
792 
793  /* Get the resno right, but don't copy unnecessarily */
794  if (old_tle->resno != next_junk_attrno)
795  {
796  old_tle = flatCopyTargetEntry(old_tle);
797  old_tle->resno = next_junk_attrno;
798  }
799  junk_tlist = lappend(junk_tlist, old_tle);
800  next_junk_attrno++;
801  }
802  }
803 
804  for (attrno = 1; attrno <= numattrs; attrno++)
805  {
806  TargetEntry *new_tle = new_tles[attrno - 1];
807  bool apply_default;
808 
809  att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
810 
811  /* We can (and must) ignore deleted attributes */
812  if (att_tup->attisdropped)
813  continue;
814 
815  /*
816  * Handle the two cases where we need to insert a default expression:
817  * it's an INSERT and there's no tlist entry for the column, or the
818  * tlist entry is a DEFAULT placeholder node.
819  */
820  apply_default = ((new_tle == NULL && commandType == CMD_INSERT) ||
821  (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)));
822 
823  if (commandType == CMD_INSERT)
824  {
825  int values_attrno = 0;
826 
827  /* Source attribute number for values that come from a VALUES RTE */
828  if (values_rte && new_tle && IsA(new_tle->expr, Var))
829  {
830  Var *var = (Var *) new_tle->expr;
831 
832  if (var->varno == values_rte_index)
833  values_attrno = var->varattno;
834  }
835 
836  /*
837  * Can only insert DEFAULT into GENERATED ALWAYS identity columns,
838  * unless either OVERRIDING USER VALUE or OVERRIDING SYSTEM VALUE
839  * is specified.
840  */
841  if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS && !apply_default)
842  {
843  if (override == OVERRIDING_USER_VALUE)
844  apply_default = true;
845  else if (override != OVERRIDING_SYSTEM_VALUE)
846  {
847  /*
848  * If this column's values come from a VALUES RTE, test
849  * whether it contains only SetToDefault items. Since the
850  * VALUES list might be quite large, we arrange to only
851  * scan it once.
852  */
853  if (values_attrno != 0)
854  {
855  if (default_only_cols == NULL)
856  default_only_cols = findDefaultOnlyColumns(values_rte);
857 
858  if (bms_is_member(values_attrno, default_only_cols))
859  apply_default = true;
860  }
861 
862  if (!apply_default)
863  ereport(ERROR,
864  (errcode(ERRCODE_GENERATED_ALWAYS),
865  errmsg("cannot insert a non-DEFAULT value into column \"%s\"",
866  NameStr(att_tup->attname)),
867  errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
868  NameStr(att_tup->attname)),
869  errhint("Use OVERRIDING SYSTEM VALUE to override.")));
870  }
871  }
872 
873  /*
874  * Although inserting into a GENERATED BY DEFAULT identity column
875  * is allowed, apply the default if OVERRIDING USER VALUE is
876  * specified.
877  */
878  if (att_tup->attidentity == ATTRIBUTE_IDENTITY_BY_DEFAULT &&
879  override == OVERRIDING_USER_VALUE)
880  apply_default = true;
881 
882  /*
883  * Can only insert DEFAULT into generated columns, regardless of
884  * any OVERRIDING clauses.
885  */
886  if (att_tup->attgenerated && !apply_default)
887  {
888  /*
889  * If this column's values come from a VALUES RTE, test
890  * whether it contains only SetToDefault items, as above.
891  */
892  if (values_attrno != 0)
893  {
894  if (default_only_cols == NULL)
895  default_only_cols = findDefaultOnlyColumns(values_rte);
896 
897  if (bms_is_member(values_attrno, default_only_cols))
898  apply_default = true;
899  }
900 
901  if (!apply_default)
902  ereport(ERROR,
903  (errcode(ERRCODE_GENERATED_ALWAYS),
904  errmsg("cannot insert a non-DEFAULT value into column \"%s\"",
905  NameStr(att_tup->attname)),
906  errdetail("Column \"%s\" is a generated column.",
907  NameStr(att_tup->attname))));
908  }
909 
910  /*
911  * For an INSERT from a VALUES RTE, return the attribute numbers
912  * of any VALUES columns that will no longer be used (due to the
913  * targetlist entry being replaced by a default expression).
914  */
915  if (values_attrno != 0 && apply_default && unused_values_attrnos)
916  *unused_values_attrnos = bms_add_member(*unused_values_attrnos,
917  values_attrno);
918  }
919 
920  /*
921  * Updates to identity and generated columns follow the same rules as
922  * above, except that UPDATE doesn't admit OVERRIDING clauses. Also,
923  * the source can't be a VALUES RTE, so we needn't consider that.
924  */
925  if (commandType == CMD_UPDATE)
926  {
927  if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS &&
928  new_tle && !apply_default)
929  ereport(ERROR,
930  (errcode(ERRCODE_GENERATED_ALWAYS),
931  errmsg("column \"%s\" can only be updated to DEFAULT",
932  NameStr(att_tup->attname)),
933  errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
934  NameStr(att_tup->attname))));
935 
936  if (att_tup->attgenerated && new_tle && !apply_default)
937  ereport(ERROR,
938  (errcode(ERRCODE_GENERATED_ALWAYS),
939  errmsg("column \"%s\" can only be updated to DEFAULT",
940  NameStr(att_tup->attname)),
941  errdetail("Column \"%s\" is a generated column.",
942  NameStr(att_tup->attname))));
943  }
944 
945  if (att_tup->attgenerated)
946  {
947  /*
948  * stored generated column will be fixed in executor
949  */
950  new_tle = NULL;
951  }
952  else if (apply_default)
953  {
954  Node *new_expr;
955 
956  new_expr = build_column_default(target_relation, attrno);
957 
958  /*
959  * If there is no default (ie, default is effectively NULL), we
960  * can omit the tlist entry in the INSERT case, since the planner
961  * can insert a NULL for itself, and there's no point in spending
962  * any more rewriter cycles on the entry. But in the UPDATE case
963  * we've got to explicitly set the column to NULL.
964  */
965  if (!new_expr)
966  {
967  if (commandType == CMD_INSERT)
968  new_tle = NULL;
969  else
970  {
971  new_expr = (Node *) makeConst(att_tup->atttypid,
972  -1,
973  att_tup->attcollation,
974  att_tup->attlen,
975  (Datum) 0,
976  true, /* isnull */
977  att_tup->attbyval);
978  /* this is to catch a NOT NULL domain constraint */
979  new_expr = coerce_to_domain(new_expr,
980  InvalidOid, -1,
981  att_tup->atttypid,
984  -1,
985  false);
986  }
987  }
988 
989  if (new_expr)
990  new_tle = makeTargetEntry((Expr *) new_expr,
991  attrno,
992  pstrdup(NameStr(att_tup->attname)),
993  false);
994  }
995 
996  /*
997  * For an UPDATE on a trigger-updatable view, provide a dummy entry
998  * whenever there is no explicit assignment.
999  */
1000  if (new_tle == NULL && commandType == CMD_UPDATE &&
1001  target_relation->rd_rel->relkind == RELKIND_VIEW &&
1002  view_has_instead_trigger(target_relation, CMD_UPDATE))
1003  {
1004  Node *new_expr;
1005 
1006  new_expr = (Node *) makeVar(result_rti,
1007  attrno,
1008  att_tup->atttypid,
1009  att_tup->atttypmod,
1010  att_tup->attcollation,
1011  0);
1012 
1013  new_tle = makeTargetEntry((Expr *) new_expr,
1014  attrno,
1015  pstrdup(NameStr(att_tup->attname)),
1016  false);
1017  }
1018 
1019  if (new_tle)
1020  new_tlist = lappend(new_tlist, new_tle);
1021  }
1022 
1023  pfree(new_tles);
1024 
1025  return list_concat(new_tlist, junk_tlist);
1026 }
1027 
1028 
1029 /*
1030  * Convert a matched TLE from the original tlist into a correct new TLE.
1031  *
1032  * This routine detects and handles multiple assignments to the same target
1033  * attribute. (The attribute name is needed only for error messages.)
1034  */
1035 static TargetEntry *
1037  TargetEntry *prior_tle,
1038  const char *attrName)
1039 {
1040  TargetEntry *result;
1041  CoerceToDomain *coerce_expr = NULL;
1042  Node *src_expr;
1043  Node *prior_expr;
1044  Node *src_input;
1045  Node *prior_input;
1046  Node *priorbottom;
1047  Node *newexpr;
1048 
1049  if (prior_tle == NULL)
1050  {
1051  /*
1052  * Normal case where this is the first assignment to the attribute.
1053  */
1054  return src_tle;
1055  }
1056 
1057  /*----------
1058  * Multiple assignments to same attribute. Allow only if all are
1059  * FieldStore or SubscriptingRef assignment operations. This is a bit
1060  * tricky because what we may actually be looking at is a nest of
1061  * such nodes; consider
1062  * UPDATE tab SET col.fld1.subfld1 = x, col.fld2.subfld2 = y
1063  * The two expressions produced by the parser will look like
1064  * FieldStore(col, fld1, FieldStore(placeholder, subfld1, x))
1065  * FieldStore(col, fld2, FieldStore(placeholder, subfld2, y))
1066  * However, we can ignore the substructure and just consider the top
1067  * FieldStore or SubscriptingRef from each assignment, because it works to
1068  * combine these as
1069  * FieldStore(FieldStore(col, fld1,
1070  * FieldStore(placeholder, subfld1, x)),
1071  * fld2, FieldStore(placeholder, subfld2, y))
1072  * Note the leftmost expression goes on the inside so that the
1073  * assignments appear to occur left-to-right.
1074  *
1075  * For FieldStore, instead of nesting we can generate a single
1076  * FieldStore with multiple target fields. We must nest when
1077  * SubscriptingRefs are involved though.
1078  *
1079  * As a further complication, the destination column might be a domain,
1080  * resulting in each assignment containing a CoerceToDomain node over a
1081  * FieldStore or SubscriptingRef. These should have matching target
1082  * domains, so we strip them and reconstitute a single CoerceToDomain over
1083  * the combined FieldStore/SubscriptingRef nodes. (Notice that this has the
1084  * result that the domain's checks are applied only after we do all the
1085  * field or element updates, not after each one. This is arguably desirable.)
1086  *----------
1087  */
1088  src_expr = (Node *) src_tle->expr;
1089  prior_expr = (Node *) prior_tle->expr;
1090 
1091  if (src_expr && IsA(src_expr, CoerceToDomain) &&
1092  prior_expr && IsA(prior_expr, CoerceToDomain) &&
1093  ((CoerceToDomain *) src_expr)->resulttype ==
1094  ((CoerceToDomain *) prior_expr)->resulttype)
1095  {
1096  /* we assume without checking that resulttypmod/resultcollid match */
1097  coerce_expr = (CoerceToDomain *) src_expr;
1098  src_expr = (Node *) ((CoerceToDomain *) src_expr)->arg;
1099  prior_expr = (Node *) ((CoerceToDomain *) prior_expr)->arg;
1100  }
1101 
1102  src_input = get_assignment_input(src_expr);
1103  prior_input = get_assignment_input(prior_expr);
1104  if (src_input == NULL ||
1105  prior_input == NULL ||
1106  exprType(src_expr) != exprType(prior_expr))
1107  ereport(ERROR,
1108  (errcode(ERRCODE_SYNTAX_ERROR),
1109  errmsg("multiple assignments to same column \"%s\"",
1110  attrName)));
1111 
1112  /*
1113  * Prior TLE could be a nest of assignments if we do this more than once.
1114  */
1115  priorbottom = prior_input;
1116  for (;;)
1117  {
1118  Node *newbottom = get_assignment_input(priorbottom);
1119 
1120  if (newbottom == NULL)
1121  break; /* found the original Var reference */
1122  priorbottom = newbottom;
1123  }
1124  if (!equal(priorbottom, src_input))
1125  ereport(ERROR,
1126  (errcode(ERRCODE_SYNTAX_ERROR),
1127  errmsg("multiple assignments to same column \"%s\"",
1128  attrName)));
1129 
1130  /*
1131  * Looks OK to nest 'em.
1132  */
1133  if (IsA(src_expr, FieldStore))
1134  {
1135  FieldStore *fstore = makeNode(FieldStore);
1136 
1137  if (IsA(prior_expr, FieldStore))
1138  {
1139  /* combine the two */
1140  memcpy(fstore, prior_expr, sizeof(FieldStore));
1141  fstore->newvals =
1142  list_concat_copy(((FieldStore *) prior_expr)->newvals,
1143  ((FieldStore *) src_expr)->newvals);
1144  fstore->fieldnums =
1145  list_concat_copy(((FieldStore *) prior_expr)->fieldnums,
1146  ((FieldStore *) src_expr)->fieldnums);
1147  }
1148  else
1149  {
1150  /* general case, just nest 'em */
1151  memcpy(fstore, src_expr, sizeof(FieldStore));
1152  fstore->arg = (Expr *) prior_expr;
1153  }
1154  newexpr = (Node *) fstore;
1155  }
1156  else if (IsA(src_expr, SubscriptingRef))
1157  {
1159 
1160  memcpy(sbsref, src_expr, sizeof(SubscriptingRef));
1161  sbsref->refexpr = (Expr *) prior_expr;
1162  newexpr = (Node *) sbsref;
1163  }
1164  else
1165  {
1166  elog(ERROR, "cannot happen");
1167  newexpr = NULL;
1168  }
1169 
1170  if (coerce_expr)
1171  {
1172  /* put back the CoerceToDomain */
1173  CoerceToDomain *newcoerce = makeNode(CoerceToDomain);
1174 
1175  memcpy(newcoerce, coerce_expr, sizeof(CoerceToDomain));
1176  newcoerce->arg = (Expr *) newexpr;
1177  newexpr = (Node *) newcoerce;
1178  }
1179 
1180  result = flatCopyTargetEntry(src_tle);
1181  result->expr = (Expr *) newexpr;
1182  return result;
1183 }
1184 
1185 /*
1186  * If node is an assignment node, return its input; else return NULL
1187  */
1188 static Node *
1190 {
1191  if (node == NULL)
1192  return NULL;
1193  if (IsA(node, FieldStore))
1194  {
1195  FieldStore *fstore = (FieldStore *) node;
1196 
1197  return (Node *) fstore->arg;
1198  }
1199  else if (IsA(node, SubscriptingRef))
1200  {
1201  SubscriptingRef *sbsref = (SubscriptingRef *) node;
1202 
1203  if (sbsref->refassgnexpr == NULL)
1204  return NULL;
1205 
1206  return (Node *) sbsref->refexpr;
1207  }
1208 
1209  return NULL;
1210 }
1211 
1212 /*
1213  * Make an expression tree for the default value for a column.
1214  *
1215  * If there is no default, return a NULL instead.
1216  */
1217 Node *
1219 {
1220  TupleDesc rd_att = rel->rd_att;
1221  Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1222  Oid atttype = att_tup->atttypid;
1223  int32 atttypmod = att_tup->atttypmod;
1224  Node *expr = NULL;
1225  Oid exprtype;
1226 
1227  if (att_tup->attidentity)
1228  {
1230 
1231  nve->seqid = getIdentitySequence(RelationGetRelid(rel), attrno, false);
1232  nve->typeId = att_tup->atttypid;
1233 
1234  return (Node *) nve;
1235  }
1236 
1237  /*
1238  * Scan to see if relation has a default for this column.
1239  */
1240  if (att_tup->atthasdef && rd_att->constr &&
1241  rd_att->constr->num_defval > 0)
1242  {
1243  AttrDefault *defval = rd_att->constr->defval;
1244  int ndef = rd_att->constr->num_defval;
1245 
1246  while (--ndef >= 0)
1247  {
1248  if (attrno == defval[ndef].adnum)
1249  {
1250  /*
1251  * Found it, convert string representation to node tree.
1252  */
1253  expr = stringToNode(defval[ndef].adbin);
1254  break;
1255  }
1256  }
1257  }
1258 
1259  /*
1260  * No per-column default, so look for a default for the type itself. But
1261  * not for generated columns.
1262  */
1263  if (expr == NULL && !att_tup->attgenerated)
1264  expr = get_typdefault(atttype);
1265 
1266  if (expr == NULL)
1267  return NULL; /* No default anywhere */
1268 
1269  /*
1270  * Make sure the value is coerced to the target column type; this will
1271  * generally be true already, but there seem to be some corner cases
1272  * involving domain defaults where it might not be true. This should match
1273  * the parser's processing of non-defaulted expressions --- see
1274  * transformAssignedExpr().
1275  */
1276  exprtype = exprType(expr);
1277 
1278  expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1279  expr, exprtype,
1280  atttype, atttypmod,
1283  -1);
1284  if (expr == NULL)
1285  ereport(ERROR,
1286  (errcode(ERRCODE_DATATYPE_MISMATCH),
1287  errmsg("column \"%s\" is of type %s"
1288  " but default expression is of type %s",
1289  NameStr(att_tup->attname),
1290  format_type_be(atttype),
1291  format_type_be(exprtype)),
1292  errhint("You will need to rewrite or cast the expression.")));
1293 
1294  return expr;
1295 }
1296 
1297 
1298 /* Does VALUES RTE contain any SetToDefault items? */
1299 static bool
1301 {
1302  ListCell *lc;
1303 
1304  foreach(lc, rte->values_lists)
1305  {
1306  List *sublist = (List *) lfirst(lc);
1307  ListCell *lc2;
1308 
1309  foreach(lc2, sublist)
1310  {
1311  Node *col = (Node *) lfirst(lc2);
1312 
1313  if (IsA(col, SetToDefault))
1314  return true;
1315  }
1316  }
1317  return false;
1318 }
1319 
1320 
1321 /*
1322  * Search a VALUES RTE for columns that contain only SetToDefault items,
1323  * returning a Bitmapset containing the attribute numbers of any such columns.
1324  */
1325 static Bitmapset *
1327 {
1328  Bitmapset *default_only_cols = NULL;
1329  ListCell *lc;
1330 
1331  foreach(lc, rte->values_lists)
1332  {
1333  List *sublist = (List *) lfirst(lc);
1334  ListCell *lc2;
1335  int i;
1336 
1337  if (default_only_cols == NULL)
1338  {
1339  /* Populate the initial result bitmap from the first row */
1340  i = 0;
1341  foreach(lc2, sublist)
1342  {
1343  Node *col = (Node *) lfirst(lc2);
1344 
1345  i++;
1346  if (IsA(col, SetToDefault))
1347  default_only_cols = bms_add_member(default_only_cols, i);
1348  }
1349  }
1350  else
1351  {
1352  /* Update the result bitmap from this next row */
1353  i = 0;
1354  foreach(lc2, sublist)
1355  {
1356  Node *col = (Node *) lfirst(lc2);
1357 
1358  i++;
1359  if (!IsA(col, SetToDefault))
1360  default_only_cols = bms_del_member(default_only_cols, i);
1361  }
1362  }
1363 
1364  /*
1365  * If no column in the rows read so far contains only DEFAULT items,
1366  * we are done.
1367  */
1368  if (bms_is_empty(default_only_cols))
1369  break;
1370  }
1371 
1372  return default_only_cols;
1373 }
1374 
1375 
1376 /*
1377  * When processing INSERT ... VALUES with a VALUES RTE (ie, multiple VALUES
1378  * lists), we have to replace any DEFAULT items in the VALUES lists with
1379  * the appropriate default expressions. The other aspects of targetlist
1380  * rewriting need be applied only to the query's targetlist proper.
1381  *
1382  * For an auto-updatable view, each DEFAULT item in the VALUES list is
1383  * replaced with the default from the view, if it has one. Otherwise it is
1384  * left untouched so that the underlying base relation's default can be
1385  * applied instead (when we later recurse to here after rewriting the query
1386  * to refer to the base relation instead of the view).
1387  *
1388  * For other types of relation, including rule- and trigger-updatable views,
1389  * all DEFAULT items are replaced, and if the target relation doesn't have a
1390  * default, the value is explicitly set to NULL.
1391  *
1392  * Additionally, if force_nulls is true, the target relation's defaults are
1393  * ignored and all DEFAULT items in the VALUES list are explicitly set to
1394  * NULL, regardless of the target relation's type. This is used for the
1395  * product queries generated by DO ALSO rules attached to an auto-updatable
1396  * view, for which we will have already called this function with force_nulls
1397  * false. For these product queries, we must then force any remaining DEFAULT
1398  * items to NULL to provide concrete values for the rule actions.
1399  * Essentially, this is a mix of the 2 cases above --- the original query is
1400  * an insert into an auto-updatable view, and the product queries are inserts
1401  * into a rule-updatable view.
1402  *
1403  * Finally, if a DEFAULT item is found in a column mentioned in unused_cols,
1404  * it is explicitly set to NULL. This happens for columns in the VALUES RTE
1405  * whose corresponding targetlist entries have already been replaced with the
1406  * relation's default expressions, so that any values in those columns of the
1407  * VALUES RTE are no longer used. This can happen for identity and generated
1408  * columns (if INSERT ... OVERRIDING USER VALUE is used, or all the values to
1409  * be inserted are DEFAULT). In principle we could replace all entries in
1410  * such a column with NULL, whether DEFAULT or not; but it doesn't seem worth
1411  * the trouble.
1412  *
1413  * Note that we may have subscripted or field assignment targetlist entries,
1414  * as well as more complex expressions from already-replaced DEFAULT items if
1415  * we have recursed to here for an auto-updatable view. However, it ought to
1416  * be impossible for such entries to have DEFAULTs assigned to them, except
1417  * for unused columns, as described above --- we should only have to replace
1418  * DEFAULT items for targetlist entries that contain simple Vars referencing
1419  * the VALUES RTE, or which are no longer referred to by the targetlist.
1420  *
1421  * Returns true if all DEFAULT items were replaced, and false if some were
1422  * left untouched.
1423  */
1424 static bool
1425 rewriteValuesRTE(Query *parsetree, RangeTblEntry *rte, int rti,
1426  Relation target_relation, bool force_nulls,
1427  Bitmapset *unused_cols)
1428 {
1429  List *newValues;
1430  ListCell *lc;
1431  bool isAutoUpdatableView;
1432  bool allReplaced;
1433  int numattrs;
1434  int *attrnos;
1435 
1436  /*
1437  * Rebuilding all the lists is a pretty expensive proposition in a big
1438  * VALUES list, and it's a waste of time if there aren't any DEFAULT
1439  * placeholders. So first scan to see if there are any.
1440  *
1441  * We skip this check if force_nulls is true, because we know that there
1442  * are DEFAULT items present in that case.
1443  */
1444  if (!force_nulls && !searchForDefault(rte))
1445  return true; /* nothing to do */
1446 
1447  /*
1448  * Scan the targetlist for entries referring to the VALUES RTE, and note
1449  * the target attributes. As noted above, we should only need to do this
1450  * for targetlist entries containing simple Vars --- nothing else in the
1451  * VALUES RTE should contain DEFAULT items (except possibly for unused
1452  * columns), and we complain if such a thing does occur.
1453  */
1454  numattrs = list_length(linitial(rte->values_lists));
1455  attrnos = (int *) palloc0(numattrs * sizeof(int));
1456 
1457  foreach(lc, parsetree->targetList)
1458  {
1459  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1460 
1461  if (IsA(tle->expr, Var))
1462  {
1463  Var *var = (Var *) tle->expr;
1464 
1465  if (var->varno == rti)
1466  {
1467  int attrno = var->varattno;
1468 
1469  Assert(attrno >= 1 && attrno <= numattrs);
1470  attrnos[attrno - 1] = tle->resno;
1471  }
1472  }
1473  }
1474 
1475  /*
1476  * Check if the target relation is an auto-updatable view, in which case
1477  * unresolved defaults will be left untouched rather than being set to
1478  * NULL. If force_nulls is true, we always set DEFAULT items to NULL, so
1479  * skip this check in that case --- it isn't an auto-updatable view.
1480  */
1481  isAutoUpdatableView = false;
1482  if (!force_nulls &&
1483  target_relation->rd_rel->relkind == RELKIND_VIEW &&
1484  !view_has_instead_trigger(target_relation, CMD_INSERT))
1485  {
1486  List *locks;
1487  bool hasUpdate;
1488  bool found;
1489  ListCell *l;
1490 
1491  /* Look for an unconditional DO INSTEAD rule */
1492  locks = matchLocks(CMD_INSERT, target_relation->rd_rules,
1493  parsetree->resultRelation, parsetree, &hasUpdate);
1494 
1495  found = false;
1496  foreach(l, locks)
1497  {
1498  RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
1499 
1500  if (rule_lock->isInstead &&
1501  rule_lock->qual == NULL)
1502  {
1503  found = true;
1504  break;
1505  }
1506  }
1507 
1508  /*
1509  * If we didn't find an unconditional DO INSTEAD rule, assume that the
1510  * view is auto-updatable. If it isn't, rewriteTargetView() will
1511  * throw an error.
1512  */
1513  if (!found)
1514  isAutoUpdatableView = true;
1515  }
1516 
1517  newValues = NIL;
1518  allReplaced = true;
1519  foreach(lc, rte->values_lists)
1520  {
1521  List *sublist = (List *) lfirst(lc);
1522  List *newList = NIL;
1523  ListCell *lc2;
1524  int i;
1525 
1526  Assert(list_length(sublist) == numattrs);
1527 
1528  i = 0;
1529  foreach(lc2, sublist)
1530  {
1531  Node *col = (Node *) lfirst(lc2);
1532  int attrno = attrnos[i++];
1533 
1534  if (IsA(col, SetToDefault))
1535  {
1536  Form_pg_attribute att_tup;
1537  Node *new_expr;
1538 
1539  /*
1540  * If this column isn't used, just replace the DEFAULT with
1541  * NULL (attrno will be 0 in this case because the targetlist
1542  * entry will have been replaced by the default expression).
1543  */
1544  if (bms_is_member(i, unused_cols))
1545  {
1546  SetToDefault *def = (SetToDefault *) col;
1547 
1548  newList = lappend(newList,
1549  makeNullConst(def->typeId,
1550  def->typeMod,
1551  def->collation));
1552  continue;
1553  }
1554 
1555  if (attrno == 0)
1556  elog(ERROR, "cannot set value in column %d to DEFAULT", i);
1557  att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
1558 
1559  if (!force_nulls && !att_tup->attisdropped)
1560  new_expr = build_column_default(target_relation, attrno);
1561  else
1562  new_expr = NULL; /* force a NULL if dropped */
1563 
1564  /*
1565  * If there is no default (ie, default is effectively NULL),
1566  * we've got to explicitly set the column to NULL, unless the
1567  * target relation is an auto-updatable view.
1568  */
1569  if (!new_expr)
1570  {
1571  if (isAutoUpdatableView)
1572  {
1573  /* Leave the value untouched */
1574  newList = lappend(newList, col);
1575  allReplaced = false;
1576  continue;
1577  }
1578 
1579  new_expr = (Node *) makeConst(att_tup->atttypid,
1580  -1,
1581  att_tup->attcollation,
1582  att_tup->attlen,
1583  (Datum) 0,
1584  true, /* isnull */
1585  att_tup->attbyval);
1586  /* this is to catch a NOT NULL domain constraint */
1587  new_expr = coerce_to_domain(new_expr,
1588  InvalidOid, -1,
1589  att_tup->atttypid,
1592  -1,
1593  false);
1594  }
1595  newList = lappend(newList, new_expr);
1596  }
1597  else
1598  newList = lappend(newList, col);
1599  }
1600  newValues = lappend(newValues, newList);
1601  }
1602  rte->values_lists = newValues;
1603 
1604  pfree(attrnos);
1605 
1606  return allReplaced;
1607 }
1608 
1609 
1610 /*
1611  * rewriteTargetListUD - rewrite UPDATE/DELETE targetlist as needed
1612  *
1613  * This function adds a "junk" TLE that is needed to allow the executor to
1614  * find the original row for the update or delete. When the target relation
1615  * is a regular table, the junk TLE emits the ctid attribute of the original
1616  * row. When the target relation is a foreign table, we let the FDW decide
1617  * what to add.
1618  *
1619  * We used to do this during RewriteQuery(), but now that inheritance trees
1620  * can contain a mix of regular and foreign tables, we must postpone it till
1621  * planning, after the inheritance tree has been expanded. In that way we
1622  * can do the right thing for each child table.
1623  */
1624 void
1625 rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
1626  Relation target_relation)
1627 {
1628  Var *var = NULL;
1629  const char *attrname;
1630  TargetEntry *tle;
1631 
1632  if (target_relation->rd_rel->relkind == RELKIND_RELATION ||
1633  target_relation->rd_rel->relkind == RELKIND_MATVIEW ||
1634  target_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1635  {
1636  /*
1637  * Emit CTID so that executor can find the row to update or delete.
1638  */
1639  var = makeVar(parsetree->resultRelation,
1641  TIDOID,
1642  -1,
1643  InvalidOid,
1644  0);
1645 
1646  attrname = "ctid";
1647  }
1648  else if (target_relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1649  {
1650  /*
1651  * Let the foreign table's FDW add whatever junk TLEs it wants.
1652  */
1653  FdwRoutine *fdwroutine;
1654 
1655  fdwroutine = GetFdwRoutineForRelation(target_relation, false);
1656 
1657  if (fdwroutine->AddForeignUpdateTargets != NULL)
1658  fdwroutine->AddForeignUpdateTargets(parsetree, target_rte,
1659  target_relation);
1660 
1661  /*
1662  * If we have a row-level trigger corresponding to the operation, emit
1663  * a whole-row Var so that executor will have the "old" row to pass to
1664  * the trigger. Alas, this misses system columns.
1665  */
1666  if (target_relation->trigdesc &&
1667  ((parsetree->commandType == CMD_UPDATE &&
1668  (target_relation->trigdesc->trig_update_after_row ||
1669  target_relation->trigdesc->trig_update_before_row)) ||
1670  (parsetree->commandType == CMD_DELETE &&
1671  (target_relation->trigdesc->trig_delete_after_row ||
1672  target_relation->trigdesc->trig_delete_before_row))))
1673  {
1674  var = makeWholeRowVar(target_rte,
1675  parsetree->resultRelation,
1676  0,
1677  false);
1678 
1679  attrname = "wholerow";
1680  }
1681  }
1682 
1683  if (var != NULL)
1684  {
1685  tle = makeTargetEntry((Expr *) var,
1686  list_length(parsetree->targetList) + 1,
1687  pstrdup(attrname),
1688  true);
1689 
1690  parsetree->targetList = lappend(parsetree->targetList, tle);
1691  }
1692 }
1693 
1694 /*
1695  * Record in target_rte->extraUpdatedCols the indexes of any generated columns
1696  * that depend on any columns mentioned in target_rte->updatedCols.
1697  */
1698 void
1699 fill_extraUpdatedCols(RangeTblEntry *target_rte, Relation target_relation)
1700 {
1701  TupleDesc tupdesc = RelationGetDescr(target_relation);
1702  TupleConstr *constr = tupdesc->constr;
1703 
1704  target_rte->extraUpdatedCols = NULL;
1705 
1706  if (constr && constr->has_generated_stored)
1707  {
1708  for (int i = 0; i < constr->num_defval; i++)
1709  {
1710  AttrDefault *defval = &constr->defval[i];
1711  Node *expr;
1712  Bitmapset *attrs_used = NULL;
1713 
1714  /* skip if not generated column */
1715  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
1716  continue;
1717 
1718  /* identify columns this generated column depends on */
1719  expr = stringToNode(defval->adbin);
1720  pull_varattnos(expr, 1, &attrs_used);
1721 
1722  if (bms_overlap(target_rte->updatedCols, attrs_used))
1723  target_rte->extraUpdatedCols =
1724  bms_add_member(target_rte->extraUpdatedCols,
1726  }
1727  }
1728 }
1729 
1730 
1731 /*
1732  * matchLocks -
1733  * match the list of locks and returns the matching rules
1734  */
1735 static List *
1737  RuleLock *rulelocks,
1738  int varno,
1739  Query *parsetree,
1740  bool *hasUpdate)
1741 {
1742  List *matching_locks = NIL;
1743  int nlocks;
1744  int i;
1745 
1746  if (rulelocks == NULL)
1747  return NIL;
1748 
1749  if (parsetree->commandType != CMD_SELECT)
1750  {
1751  if (parsetree->resultRelation != varno)
1752  return NIL;
1753  }
1754 
1755  nlocks = rulelocks->numLocks;
1756 
1757  for (i = 0; i < nlocks; i++)
1758  {
1759  RewriteRule *oneLock = rulelocks->rules[i];
1760 
1761  if (oneLock->event == CMD_UPDATE)
1762  *hasUpdate = true;
1763 
1764  /*
1765  * Suppress ON INSERT/UPDATE/DELETE rules that are disabled or
1766  * configured to not fire during the current sessions replication
1767  * role. ON SELECT rules will always be applied in order to keep views
1768  * working even in LOCAL or REPLICA role.
1769  */
1770  if (oneLock->event != CMD_SELECT)
1771  {
1773  {
1774  if (oneLock->enabled == RULE_FIRES_ON_ORIGIN ||
1775  oneLock->enabled == RULE_DISABLED)
1776  continue;
1777  }
1778  else /* ORIGIN or LOCAL ROLE */
1779  {
1780  if (oneLock->enabled == RULE_FIRES_ON_REPLICA ||
1781  oneLock->enabled == RULE_DISABLED)
1782  continue;
1783  }
1784  }
1785 
1786  if (oneLock->event == event)
1787  {
1788  if (parsetree->commandType != CMD_SELECT ||
1789  rangeTableEntry_used((Node *) parsetree, varno, 0))
1790  matching_locks = lappend(matching_locks, oneLock);
1791  }
1792  }
1793 
1794  return matching_locks;
1795 }
1796 
1797 
1798 /*
1799  * ApplyRetrieveRule - expand an ON SELECT rule
1800  */
1801 static Query *
1803  RewriteRule *rule,
1804  int rt_index,
1806  List *activeRIRs)
1807 {
1808  Query *rule_action;
1809  RangeTblEntry *rte,
1810  *subrte;
1811  RowMarkClause *rc;
1812 
1813  if (list_length(rule->actions) != 1)
1814  elog(ERROR, "expected just one rule action");
1815  if (rule->qual != NULL)
1816  elog(ERROR, "cannot handle qualified ON SELECT rule");
1817 
1818  if (rt_index == parsetree->resultRelation)
1819  {
1820  /*
1821  * We have a view as the result relation of the query, and it wasn't
1822  * rewritten by any rule. This case is supported if there is an
1823  * INSTEAD OF trigger that will trap attempts to insert/update/delete
1824  * view rows. The executor will check that; for the moment just plow
1825  * ahead. We have two cases:
1826  *
1827  * For INSERT, we needn't do anything. The unmodified RTE will serve
1828  * fine as the result relation.
1829  *
1830  * For UPDATE/DELETE, we need to expand the view so as to have source
1831  * data for the operation. But we also need an unmodified RTE to
1832  * serve as the target. So, copy the RTE and add the copy to the
1833  * rangetable. Note that the copy does not get added to the jointree.
1834  * Also note that there's a hack in fireRIRrules to avoid calling this
1835  * function again when it arrives at the copied RTE.
1836  */
1837  if (parsetree->commandType == CMD_INSERT)
1838  return parsetree;
1839  else if (parsetree->commandType == CMD_UPDATE ||
1840  parsetree->commandType == CMD_DELETE)
1841  {
1842  RangeTblEntry *newrte;
1843  Var *var;
1844  TargetEntry *tle;
1845 
1846  rte = rt_fetch(rt_index, parsetree->rtable);
1847  newrte = copyObject(rte);
1848  parsetree->rtable = lappend(parsetree->rtable, newrte);
1849  parsetree->resultRelation = list_length(parsetree->rtable);
1850 
1851  /*
1852  * There's no need to do permissions checks twice, so wipe out the
1853  * permissions info for the original RTE (we prefer to keep the
1854  * bits set on the result RTE).
1855  */
1856  rte->requiredPerms = 0;
1857  rte->checkAsUser = InvalidOid;
1858  rte->selectedCols = NULL;
1859  rte->insertedCols = NULL;
1860  rte->updatedCols = NULL;
1861  rte->extraUpdatedCols = NULL;
1862 
1863  /*
1864  * For the most part, Vars referencing the view should remain as
1865  * they are, meaning that they implicitly represent OLD values.
1866  * But in the RETURNING list if any, we want such Vars to
1867  * represent NEW values, so change them to reference the new RTE.
1868  *
1869  * Since ChangeVarNodes scribbles on the tree in-place, copy the
1870  * RETURNING list first for safety.
1871  */
1872  parsetree->returningList = copyObject(parsetree->returningList);
1873  ChangeVarNodes((Node *) parsetree->returningList, rt_index,
1874  parsetree->resultRelation, 0);
1875 
1876  /*
1877  * To allow the executor to compute the original view row to pass
1878  * to the INSTEAD OF trigger, we add a resjunk whole-row Var
1879  * referencing the original RTE. This will later get expanded
1880  * into a RowExpr computing all the OLD values of the view row.
1881  */
1882  var = makeWholeRowVar(rte, rt_index, 0, false);
1883  tle = makeTargetEntry((Expr *) var,
1884  list_length(parsetree->targetList) + 1,
1885  pstrdup("wholerow"),
1886  true);
1887 
1888  parsetree->targetList = lappend(parsetree->targetList, tle);
1889 
1890  /* Now, continue with expanding the original view RTE */
1891  }
1892  else
1893  elog(ERROR, "unrecognized commandType: %d",
1894  (int) parsetree->commandType);
1895  }
1896 
1897  /*
1898  * Check if there's a FOR [KEY] UPDATE/SHARE clause applying to this view.
1899  *
1900  * Note: we needn't explicitly consider any such clauses appearing in
1901  * ancestor query levels; their effects have already been pushed down to
1902  * here by markQueryForLocking, and will be reflected in "rc".
1903  */
1904  rc = get_parse_rowmark(parsetree, rt_index);
1905 
1906  /*
1907  * Make a modifiable copy of the view query, and acquire needed locks on
1908  * the relations it mentions. Force at least RowShareLock for all such
1909  * rels if there's a FOR [KEY] UPDATE/SHARE clause affecting this view.
1910  */
1911  rule_action = copyObject(linitial(rule->actions));
1912 
1913  AcquireRewriteLocks(rule_action, true, (rc != NULL));
1914 
1915  /*
1916  * If FOR [KEY] UPDATE/SHARE of view, mark all the contained tables as
1917  * implicit FOR [KEY] UPDATE/SHARE, the same as the parser would have done
1918  * if the view's subquery had been written out explicitly.
1919  */
1920  if (rc != NULL)
1921  markQueryForLocking(rule_action, (Node *) rule_action->jointree,
1922  rc->strength, rc->waitPolicy, true);
1923 
1924  /*
1925  * Recursively expand any view references inside the view.
1926  *
1927  * Note: this must happen after markQueryForLocking. That way, any UPDATE
1928  * permission bits needed for sub-views are initially applied to their
1929  * RTE_RELATION RTEs by markQueryForLocking, and then transferred to their
1930  * OLD rangetable entries by the action below (in a recursive call of this
1931  * routine).
1932  */
1933  rule_action = fireRIRrules(rule_action, activeRIRs);
1934 
1935  /*
1936  * Now, plug the view query in as a subselect, converting the relation's
1937  * original RTE to a subquery RTE.
1938  */
1939  rte = rt_fetch(rt_index, parsetree->rtable);
1940 
1941  rte->rtekind = RTE_SUBQUERY;
1942  rte->subquery = rule_action;
1943  rte->security_barrier = RelationIsSecurityView(relation);
1944  /* Clear fields that should not be set in a subquery RTE */
1945  rte->relid = InvalidOid;
1946  rte->relkind = 0;
1947  rte->rellockmode = 0;
1948  rte->tablesample = NULL;
1949  rte->inh = false; /* must not be set for a subquery */
1950 
1951  /*
1952  * We move the view's permission check data down to its rangetable. The
1953  * checks will actually be done against the OLD entry therein.
1954  */
1955  subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
1956  Assert(subrte->relid == relation->rd_id);
1957  subrte->requiredPerms = rte->requiredPerms;
1958  subrte->checkAsUser = rte->checkAsUser;
1959  subrte->selectedCols = rte->selectedCols;
1960  subrte->insertedCols = rte->insertedCols;
1961  subrte->updatedCols = rte->updatedCols;
1962  subrte->extraUpdatedCols = rte->extraUpdatedCols;
1963 
1964  rte->requiredPerms = 0; /* no permission check on subquery itself */
1965  rte->checkAsUser = InvalidOid;
1966  rte->selectedCols = NULL;
1967  rte->insertedCols = NULL;
1968  rte->updatedCols = NULL;
1969  rte->extraUpdatedCols = NULL;
1970 
1971  return parsetree;
1972 }
1973 
1974 /*
1975  * Recursively mark all relations used by a view as FOR [KEY] UPDATE/SHARE.
1976  *
1977  * This may generate an invalid query, eg if some sub-query uses an
1978  * aggregate. We leave it to the planner to detect that.
1979  *
1980  * NB: this must agree with the parser's transformLockingClause() routine.
1981  * However, unlike the parser we have to be careful not to mark a view's
1982  * OLD and NEW rels for updating. The best way to handle that seems to be
1983  * to scan the jointree to determine which rels are used.
1984  */
1985 static void
1987  LockClauseStrength strength, LockWaitPolicy waitPolicy,
1988  bool pushedDown)
1989 {
1990  if (jtnode == NULL)
1991  return;
1992  if (IsA(jtnode, RangeTblRef))
1993  {
1994  int rti = ((RangeTblRef *) jtnode)->rtindex;
1995  RangeTblEntry *rte = rt_fetch(rti, qry->rtable);
1996 
1997  if (rte->rtekind == RTE_RELATION)
1998  {
1999  applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
2001  }
2002  else if (rte->rtekind == RTE_SUBQUERY)
2003  {
2004  applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
2005  /* FOR UPDATE/SHARE of subquery is propagated to subquery's rels */
2007  strength, waitPolicy, true);
2008  }
2009  /* other RTE types are unaffected by FOR UPDATE */
2010  }
2011  else if (IsA(jtnode, FromExpr))
2012  {
2013  FromExpr *f = (FromExpr *) jtnode;
2014  ListCell *l;
2015 
2016  foreach(l, f->fromlist)
2017  markQueryForLocking(qry, lfirst(l), strength, waitPolicy, pushedDown);
2018  }
2019  else if (IsA(jtnode, JoinExpr))
2020  {
2021  JoinExpr *j = (JoinExpr *) jtnode;
2022 
2023  markQueryForLocking(qry, j->larg, strength, waitPolicy, pushedDown);
2024  markQueryForLocking(qry, j->rarg, strength, waitPolicy, pushedDown);
2025  }
2026  else
2027  elog(ERROR, "unrecognized node type: %d",
2028  (int) nodeTag(jtnode));
2029 }
2030 
2031 
2032 /*
2033  * fireRIRonSubLink -
2034  * Apply fireRIRrules() to each SubLink (subselect in expression) found
2035  * in the given tree.
2036  *
2037  * NOTE: although this has the form of a walker, we cheat and modify the
2038  * SubLink nodes in-place. It is caller's responsibility to ensure that
2039  * no unwanted side-effects occur!
2040  *
2041  * This is unlike most of the other routines that recurse into subselects,
2042  * because we must take control at the SubLink node in order to replace
2043  * the SubLink's subselect link with the possibly-rewritten subquery.
2044  */
2045 static bool
2046 fireRIRonSubLink(Node *node, List *activeRIRs)
2047 {
2048  if (node == NULL)
2049  return false;
2050  if (IsA(node, SubLink))
2051  {
2052  SubLink *sub = (SubLink *) node;
2053 
2054  /* Do what we came for */
2055  sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
2056  activeRIRs);
2057  /* Fall through to process lefthand args of SubLink */
2058  }
2059 
2060  /*
2061  * Do NOT recurse into Query nodes, because fireRIRrules already processed
2062  * subselects of subselects for us.
2063  */
2065  (void *) activeRIRs);
2066 }
2067 
2068 
2069 /*
2070  * fireRIRrules -
2071  * Apply all RIR rules on each rangetable entry in the given query
2072  *
2073  * activeRIRs is a list of the OIDs of views we're already processing RIR
2074  * rules for, used to detect/reject recursion.
2075  */
2076 static Query *
2077 fireRIRrules(Query *parsetree, List *activeRIRs)
2078 {
2079  int origResultRelation = parsetree->resultRelation;
2080  int rt_index;
2081  ListCell *lc;
2082 
2083  /*
2084  * Expand SEARCH and CYCLE clauses in CTEs.
2085  *
2086  * This is just a convenient place to do this, since we are already
2087  * looking at each Query.
2088  */
2089  foreach(lc, parsetree->cteList)
2090  {
2092 
2093  if (cte->search_clause || cte->cycle_clause)
2094  {
2095  cte = rewriteSearchAndCycle(cte);
2096  lfirst(lc) = cte;
2097  }
2098  }
2099 
2100  /*
2101  * don't try to convert this into a foreach loop, because rtable list can
2102  * get changed each time through...
2103  */
2104  rt_index = 0;
2105  while (rt_index < list_length(parsetree->rtable))
2106  {
2107  RangeTblEntry *rte;
2108  Relation rel;
2109  List *locks;
2110  RuleLock *rules;
2111  RewriteRule *rule;
2112  int i;
2113 
2114  ++rt_index;
2115 
2116  rte = rt_fetch(rt_index, parsetree->rtable);
2117 
2118  /*
2119  * A subquery RTE can't have associated rules, so there's nothing to
2120  * do to this level of the query, but we must recurse into the
2121  * subquery to expand any rule references in it.
2122  */
2123  if (rte->rtekind == RTE_SUBQUERY)
2124  {
2125  rte->subquery = fireRIRrules(rte->subquery, activeRIRs);
2126  continue;
2127  }
2128 
2129  /*
2130  * Joins and other non-relation RTEs can be ignored completely.
2131  */
2132  if (rte->rtekind != RTE_RELATION)
2133  continue;
2134 
2135  /*
2136  * Always ignore RIR rules for materialized views referenced in
2137  * queries. (This does not prevent refreshing MVs, since they aren't
2138  * referenced in their own query definitions.)
2139  *
2140  * Note: in the future we might want to allow MVs to be conditionally
2141  * expanded as if they were regular views, if they are not scannable.
2142  * In that case this test would need to be postponed till after we've
2143  * opened the rel, so that we could check its state.
2144  */
2145  if (rte->relkind == RELKIND_MATVIEW)
2146  continue;
2147 
2148  /*
2149  * In INSERT ... ON CONFLICT, ignore the EXCLUDED pseudo-relation;
2150  * even if it points to a view, we needn't expand it, and should not
2151  * because we want the RTE to remain of RTE_RELATION type. Otherwise,
2152  * it would get changed to RTE_SUBQUERY type, which is an
2153  * untested/unsupported situation.
2154  */
2155  if (parsetree->onConflict &&
2156  rt_index == parsetree->onConflict->exclRelIndex)
2157  continue;
2158 
2159  /*
2160  * If the table is not referenced in the query, then we ignore it.
2161  * This prevents infinite expansion loop due to new rtable entries
2162  * inserted by expansion of a rule. A table is referenced if it is
2163  * part of the join set (a source table), or is referenced by any Var
2164  * nodes, or is the result table.
2165  */
2166  if (rt_index != parsetree->resultRelation &&
2167  !rangeTableEntry_used((Node *) parsetree, rt_index, 0))
2168  continue;
2169 
2170  /*
2171  * Also, if this is a new result relation introduced by
2172  * ApplyRetrieveRule, we don't want to do anything more with it.
2173  */
2174  if (rt_index == parsetree->resultRelation &&
2175  rt_index != origResultRelation)
2176  continue;
2177 
2178  /*
2179  * We can use NoLock here since either the parser or
2180  * AcquireRewriteLocks should have locked the rel already.
2181  */
2182  rel = table_open(rte->relid, NoLock);
2183 
2184  /*
2185  * Collect the RIR rules that we must apply
2186  */
2187  rules = rel->rd_rules;
2188  if (rules != NULL)
2189  {
2190  locks = NIL;
2191  for (i = 0; i < rules->numLocks; i++)
2192  {
2193  rule = rules->rules[i];
2194  if (rule->event != CMD_SELECT)
2195  continue;
2196 
2197  locks = lappend(locks, rule);
2198  }
2199 
2200  /*
2201  * If we found any, apply them --- but first check for recursion!
2202  */
2203  if (locks != NIL)
2204  {
2205  ListCell *l;
2206 
2207  if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
2208  ereport(ERROR,
2209  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2210  errmsg("infinite recursion detected in rules for relation \"%s\"",
2211  RelationGetRelationName(rel))));
2212  activeRIRs = lappend_oid(activeRIRs, RelationGetRelid(rel));
2213 
2214  foreach(l, locks)
2215  {
2216  rule = lfirst(l);
2217 
2218  parsetree = ApplyRetrieveRule(parsetree,
2219  rule,
2220  rt_index,
2221  rel,
2222  activeRIRs);
2223  }
2224 
2225  activeRIRs = list_delete_last(activeRIRs);
2226  }
2227  }
2228 
2229  table_close(rel, NoLock);
2230  }
2231 
2232  /* Recurse into subqueries in WITH */
2233  foreach(lc, parsetree->cteList)
2234  {
2235  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2236 
2237  cte->ctequery = (Node *)
2238  fireRIRrules((Query *) cte->ctequery, activeRIRs);
2239  }
2240 
2241  /*
2242  * Recurse into sublink subqueries, too. But we already did the ones in
2243  * the rtable and cteList.
2244  */
2245  if (parsetree->hasSubLinks)
2246  query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
2248 
2249  /*
2250  * Apply any row level security policies. We do this last because it
2251  * requires special recursion detection if the new quals have sublink
2252  * subqueries, and if we did it in the loop above query_tree_walker would
2253  * then recurse into those quals a second time.
2254  */
2255  rt_index = 0;
2256  foreach(lc, parsetree->rtable)
2257  {
2258  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2259  Relation rel;
2260  List *securityQuals;
2261  List *withCheckOptions;
2262  bool hasRowSecurity;
2263  bool hasSubLinks;
2264 
2265  ++rt_index;
2266 
2267  /* Only normal relations can have RLS policies */
2268  if (rte->rtekind != RTE_RELATION ||
2269  (rte->relkind != RELKIND_RELATION &&
2270  rte->relkind != RELKIND_PARTITIONED_TABLE))
2271  continue;
2272 
2273  rel = table_open(rte->relid, NoLock);
2274 
2275  /*
2276  * Fetch any new security quals that must be applied to this RTE.
2277  */
2278  get_row_security_policies(parsetree, rte, rt_index,
2279  &securityQuals, &withCheckOptions,
2280  &hasRowSecurity, &hasSubLinks);
2281 
2282  if (securityQuals != NIL || withCheckOptions != NIL)
2283  {
2284  if (hasSubLinks)
2285  {
2287 
2288  /*
2289  * Recursively process the new quals, checking for infinite
2290  * recursion.
2291  */
2292  if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
2293  ereport(ERROR,
2294  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2295  errmsg("infinite recursion detected in policy for relation \"%s\"",
2296  RelationGetRelationName(rel))));
2297 
2298  activeRIRs = lappend_oid(activeRIRs, RelationGetRelid(rel));
2299 
2300  /*
2301  * get_row_security_policies just passed back securityQuals
2302  * and/or withCheckOptions, and there were SubLinks, make sure
2303  * we lock any relations which are referenced.
2304  *
2305  * These locks would normally be acquired by the parser, but
2306  * securityQuals and withCheckOptions are added post-parsing.
2307  */
2308  context.for_execute = true;
2309  (void) acquireLocksOnSubLinks((Node *) securityQuals, &context);
2310  (void) acquireLocksOnSubLinks((Node *) withCheckOptions,
2311  &context);
2312 
2313  /*
2314  * Now that we have the locks on anything added by
2315  * get_row_security_policies, fire any RIR rules for them.
2316  */
2317  expression_tree_walker((Node *) securityQuals,
2318  fireRIRonSubLink, (void *) activeRIRs);
2319 
2320  expression_tree_walker((Node *) withCheckOptions,
2321  fireRIRonSubLink, (void *) activeRIRs);
2322 
2323  activeRIRs = list_delete_last(activeRIRs);
2324  }
2325 
2326  /*
2327  * Add the new security barrier quals to the start of the RTE's
2328  * list so that they get applied before any existing barrier quals
2329  * (which would have come from a security-barrier view, and should
2330  * get lower priority than RLS conditions on the table itself).
2331  */
2332  rte->securityQuals = list_concat(securityQuals,
2333  rte->securityQuals);
2334 
2335  parsetree->withCheckOptions = list_concat(withCheckOptions,
2336  parsetree->withCheckOptions);
2337  }
2338 
2339  /*
2340  * Make sure the query is marked correctly if row level security
2341  * applies, or if the new quals had sublinks.
2342  */
2343  if (hasRowSecurity)
2344  parsetree->hasRowSecurity = true;
2345  if (hasSubLinks)
2346  parsetree->hasSubLinks = true;
2347 
2348  table_close(rel, NoLock);
2349  }
2350 
2351  return parsetree;
2352 }
2353 
2354 
2355 /*
2356  * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
2357  * qualification. This is used to generate suitable "else clauses" for
2358  * conditional INSTEAD rules. (Unfortunately we must use "x IS NOT TRUE",
2359  * not just "NOT x" which the planner is much smarter about, else we will
2360  * do the wrong thing when the qual evaluates to NULL.)
2361  *
2362  * The rule_qual may contain references to OLD or NEW. OLD references are
2363  * replaced by references to the specified rt_index (the relation that the
2364  * rule applies to). NEW references are only possible for INSERT and UPDATE
2365  * queries on the relation itself, and so they should be replaced by copies
2366  * of the related entries in the query's own targetlist.
2367  */
2368 static Query *
2370  Node *rule_qual,
2371  int rt_index,
2372  CmdType event)
2373 {
2374  /* Don't scribble on the passed qual (it's in the relcache!) */
2375  Node *new_qual = copyObject(rule_qual);
2377 
2378  context.for_execute = true;
2379 
2380  /*
2381  * In case there are subqueries in the qual, acquire necessary locks and
2382  * fix any deleted JOIN RTE entries. (This is somewhat redundant with
2383  * rewriteRuleAction, but not entirely ... consider restructuring so that
2384  * we only need to process the qual this way once.)
2385  */
2386  (void) acquireLocksOnSubLinks(new_qual, &context);
2387 
2388  /* Fix references to OLD */
2389  ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
2390  /* Fix references to NEW */
2391  if (event == CMD_INSERT || event == CMD_UPDATE)
2392  new_qual = ReplaceVarsFromTargetList(new_qual,
2394  0,
2395  rt_fetch(rt_index,
2396  parsetree->rtable),
2397  parsetree->targetList,
2398  (event == CMD_UPDATE) ?
2401  rt_index,
2402  &parsetree->hasSubLinks);
2403  /* And attach the fixed qual */
2404  AddInvertedQual(parsetree, new_qual);
2405 
2406  return parsetree;
2407 }
2408 
2409 
2410 /*
2411  * fireRules -
2412  * Iterate through rule locks applying rules.
2413  *
2414  * Input arguments:
2415  * parsetree - original query
2416  * rt_index - RT index of result relation in original query
2417  * event - type of rule event
2418  * locks - list of rules to fire
2419  * Output arguments:
2420  * *instead_flag - set true if any unqualified INSTEAD rule is found
2421  * (must be initialized to false)
2422  * *returning_flag - set true if we rewrite RETURNING clause in any rule
2423  * (must be initialized to false)
2424  * *qual_product - filled with modified original query if any qualified
2425  * INSTEAD rule is found (must be initialized to NULL)
2426  * Return value:
2427  * list of rule actions adjusted for use with this query
2428  *
2429  * Qualified INSTEAD rules generate their action with the qualification
2430  * condition added. They also generate a modified version of the original
2431  * query with the negated qualification added, so that it will run only for
2432  * rows that the qualified action doesn't act on. (If there are multiple
2433  * qualified INSTEAD rules, we AND all the negated quals onto a single
2434  * modified original query.) We won't execute the original, unmodified
2435  * query if we find either qualified or unqualified INSTEAD rules. If
2436  * we find both, the modified original query is discarded too.
2437  */
2438 static List *
2439 fireRules(Query *parsetree,
2440  int rt_index,
2441  CmdType event,
2442  List *locks,
2443  bool *instead_flag,
2444  bool *returning_flag,
2445  Query **qual_product)
2446 {
2447  List *results = NIL;
2448  ListCell *l;
2449 
2450  foreach(l, locks)
2451  {
2452  RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
2453  Node *event_qual = rule_lock->qual;
2454  List *actions = rule_lock->actions;
2455  QuerySource qsrc;
2456  ListCell *r;
2457 
2458  /* Determine correct QuerySource value for actions */
2459  if (rule_lock->isInstead)
2460  {
2461  if (event_qual != NULL)
2462  qsrc = QSRC_QUAL_INSTEAD_RULE;
2463  else
2464  {
2465  qsrc = QSRC_INSTEAD_RULE;
2466  *instead_flag = true; /* report unqualified INSTEAD */
2467  }
2468  }
2469  else
2470  qsrc = QSRC_NON_INSTEAD_RULE;
2471 
2472  if (qsrc == QSRC_QUAL_INSTEAD_RULE)
2473  {
2474  /*
2475  * If there are INSTEAD rules with qualifications, the original
2476  * query is still performed. But all the negated rule
2477  * qualifications of the INSTEAD rules are added so it does its
2478  * actions only in cases where the rule quals of all INSTEAD rules
2479  * are false. Think of it as the default action in a case. We save
2480  * this in *qual_product so RewriteQuery() can add it to the query
2481  * list after we mangled it up enough.
2482  *
2483  * If we have already found an unqualified INSTEAD rule, then
2484  * *qual_product won't be used, so don't bother building it.
2485  */
2486  if (!*instead_flag)
2487  {
2488  if (*qual_product == NULL)
2489  *qual_product = copyObject(parsetree);
2490  *qual_product = CopyAndAddInvertedQual(*qual_product,
2491  event_qual,
2492  rt_index,
2493  event);
2494  }
2495  }
2496 
2497  /* Now process the rule's actions and add them to the result list */
2498  foreach(r, actions)
2499  {
2500  Query *rule_action = lfirst(r);
2501 
2502  if (rule_action->commandType == CMD_NOTHING)
2503  continue;
2504 
2505  rule_action = rewriteRuleAction(parsetree, rule_action,
2506  event_qual, rt_index, event,
2507  returning_flag);
2508 
2509  rule_action->querySource = qsrc;
2510  rule_action->canSetTag = false; /* might change later */
2511 
2512  results = lappend(results, rule_action);
2513  }
2514  }
2515 
2516  return results;
2517 }
2518 
2519 
2520 /*
2521  * get_view_query - get the Query from a view's _RETURN rule.
2522  *
2523  * Caller should have verified that the relation is a view, and therefore
2524  * we should find an ON SELECT action.
2525  *
2526  * Note that the pointer returned is into the relcache and therefore must
2527  * be treated as read-only to the caller and not modified or scribbled on.
2528  */
2529 Query *
2531 {
2532  int i;
2533 
2534  Assert(view->rd_rel->relkind == RELKIND_VIEW);
2535 
2536  for (i = 0; i < view->rd_rules->numLocks; i++)
2537  {
2538  RewriteRule *rule = view->rd_rules->rules[i];
2539 
2540  if (rule->event == CMD_SELECT)
2541  {
2542  /* A _RETURN rule should have only one action */
2543  if (list_length(rule->actions) != 1)
2544  elog(ERROR, "invalid _RETURN rule action specification");
2545 
2546  return (Query *) linitial(rule->actions);
2547  }
2548  }
2549 
2550  elog(ERROR, "failed to find _RETURN rule for view");
2551  return NULL; /* keep compiler quiet */
2552 }
2553 
2554 
2555 /*
2556  * view_has_instead_trigger - does view have an INSTEAD OF trigger for event?
2557  *
2558  * If it does, we don't want to treat it as auto-updatable. This test can't
2559  * be folded into view_query_is_auto_updatable because it's not an error
2560  * condition.
2561  */
2562 static bool
2564 {
2565  TriggerDesc *trigDesc = view->trigdesc;
2566 
2567  switch (event)
2568  {
2569  case CMD_INSERT:
2570  if (trigDesc && trigDesc->trig_insert_instead_row)
2571  return true;
2572  break;
2573  case CMD_UPDATE:
2574  if (trigDesc && trigDesc->trig_update_instead_row)
2575  return true;
2576  break;
2577  case CMD_DELETE:
2578  if (trigDesc && trigDesc->trig_delete_instead_row)
2579  return true;
2580  break;
2581  default:
2582  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2583  break;
2584  }
2585  return false;
2586 }
2587 
2588 
2589 /*
2590  * view_col_is_auto_updatable - test whether the specified column of a view
2591  * is auto-updatable. Returns NULL (if the column can be updated) or a message
2592  * string giving the reason that it cannot be.
2593  *
2594  * The returned string has not been translated; if it is shown as an error
2595  * message, the caller should apply _() to translate it.
2596  *
2597  * Note that the checks performed here are local to this view. We do not check
2598  * whether the referenced column of the underlying base relation is updatable.
2599  */
2600 static const char *
2602 {
2603  Var *var = (Var *) tle->expr;
2604 
2605  /*
2606  * For now, the only updatable columns we support are those that are Vars
2607  * referring to user columns of the underlying base relation.
2608  *
2609  * The view targetlist may contain resjunk columns (e.g., a view defined
2610  * like "SELECT * FROM t ORDER BY a+b" is auto-updatable) but such columns
2611  * are not auto-updatable, and in fact should never appear in the outer
2612  * query's targetlist.
2613  */
2614  if (tle->resjunk)
2615  return gettext_noop("Junk view columns are not updatable.");
2616 
2617  if (!IsA(var, Var) ||
2618  var->varno != rtr->rtindex ||
2619  var->varlevelsup != 0)
2620  return gettext_noop("View columns that are not columns of their base relation are not updatable.");
2621 
2622  if (var->varattno < 0)
2623  return gettext_noop("View columns that refer to system columns are not updatable.");
2624 
2625  if (var->varattno == 0)
2626  return gettext_noop("View columns that return whole-row references are not updatable.");
2627 
2628  return NULL; /* the view column is updatable */
2629 }
2630 
2631 
2632 /*
2633  * view_query_is_auto_updatable - test whether the specified view definition
2634  * represents an auto-updatable view. Returns NULL (if the view can be updated)
2635  * or a message string giving the reason that it cannot be.
2636 
2637  * The returned string has not been translated; if it is shown as an error
2638  * message, the caller should apply _() to translate it.
2639  *
2640  * If check_cols is true, the view is required to have at least one updatable
2641  * column (necessary for INSERT/UPDATE). Otherwise the view's columns are not
2642  * checked for updatability. See also view_cols_are_auto_updatable.
2643  *
2644  * Note that the checks performed here are only based on the view definition.
2645  * We do not check whether any base relations referred to by the view are
2646  * updatable.
2647  */
2648 const char *
2649 view_query_is_auto_updatable(Query *viewquery, bool check_cols)
2650 {
2651  RangeTblRef *rtr;
2652  RangeTblEntry *base_rte;
2653 
2654  /*----------
2655  * Check if the view is simply updatable. According to SQL-92 this means:
2656  * - No DISTINCT clause.
2657  * - Each TLE is a column reference, and each column appears at most once.
2658  * - FROM contains exactly one base relation.
2659  * - No GROUP BY or HAVING clauses.
2660  * - No set operations (UNION, INTERSECT or EXCEPT).
2661  * - No sub-queries in the WHERE clause that reference the target table.
2662  *
2663  * We ignore that last restriction since it would be complex to enforce
2664  * and there isn't any actual benefit to disallowing sub-queries. (The
2665  * semantic issues that the standard is presumably concerned about don't
2666  * arise in Postgres, since any such sub-query will not see any updates
2667  * executed by the outer query anyway, thanks to MVCC snapshotting.)
2668  *
2669  * We also relax the second restriction by supporting part of SQL:1999
2670  * feature T111, which allows for a mix of updatable and non-updatable
2671  * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2672  * a non-updatable column.
2673  *
2674  * In addition we impose these constraints, involving features that are
2675  * not part of SQL-92:
2676  * - No CTEs (WITH clauses).
2677  * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2678  * - No system columns (including whole-row references) in the tlist.
2679  * - No window functions in the tlist.
2680  * - No set-returning functions in the tlist.
2681  *
2682  * Note that we do these checks without recursively expanding the view.
2683  * If the base relation is a view, we'll recursively deal with it later.
2684  *----------
2685  */
2686  if (viewquery->distinctClause != NIL)
2687  return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2688 
2689  if (viewquery->groupClause != NIL || viewquery->groupingSets)
2690  return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2691 
2692  if (viewquery->havingQual != NULL)
2693  return gettext_noop("Views containing HAVING are not automatically updatable.");
2694 
2695  if (viewquery->setOperations != NULL)
2696  return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2697 
2698  if (viewquery->cteList != NIL)
2699  return gettext_noop("Views containing WITH are not automatically updatable.");
2700 
2701  if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2702  return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2703 
2704  /*
2705  * We must not allow window functions or set returning functions in the
2706  * targetlist. Otherwise we might end up inserting them into the quals of
2707  * the main query. We must also check for aggregates in the targetlist in
2708  * case they appear without a GROUP BY.
2709  *
2710  * These restrictions ensure that each row of the view corresponds to a
2711  * unique row in the underlying base relation.
2712  */
2713  if (viewquery->hasAggs)
2714  return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2715 
2716  if (viewquery->hasWindowFuncs)
2717  return gettext_noop("Views that return window functions are not automatically updatable.");
2718 
2719  if (viewquery->hasTargetSRFs)
2720  return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2721 
2722  /*
2723  * The view query should select from a single base relation, which must be
2724  * a table or another view.
2725  */
2726  if (list_length(viewquery->jointree->fromlist) != 1)
2727  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2728 
2729  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2730  if (!IsA(rtr, RangeTblRef))
2731  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2732 
2733  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2734  if (base_rte->rtekind != RTE_RELATION ||
2735  (base_rte->relkind != RELKIND_RELATION &&
2736  base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2737  base_rte->relkind != RELKIND_VIEW &&
2738  base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2739  return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2740 
2741  if (base_rte->tablesample)
2742  return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2743 
2744  /*
2745  * Check that the view has at least one updatable column. This is required
2746  * for INSERT/UPDATE but not for DELETE.
2747  */
2748  if (check_cols)
2749  {
2750  ListCell *cell;
2751  bool found;
2752 
2753  found = false;
2754  foreach(cell, viewquery->targetList)
2755  {
2756  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2757 
2758  if (view_col_is_auto_updatable(rtr, tle) == NULL)
2759  {
2760  found = true;
2761  break;
2762  }
2763  }
2764 
2765  if (!found)
2766  return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2767  }
2768 
2769  return NULL; /* the view is updatable */
2770 }
2771 
2772 
2773 /*
2774  * view_cols_are_auto_updatable - test whether all of the required columns of
2775  * an auto-updatable view are actually updatable. Returns NULL (if all the
2776  * required columns can be updated) or a message string giving the reason that
2777  * they cannot be.
2778  *
2779  * The returned string has not been translated; if it is shown as an error
2780  * message, the caller should apply _() to translate it.
2781  *
2782  * This should be used for INSERT/UPDATE to ensure that we don't attempt to
2783  * assign to any non-updatable columns.
2784  *
2785  * Additionally it may be used to retrieve the set of updatable columns in the
2786  * view, or if one or more of the required columns is not updatable, the name
2787  * of the first offending non-updatable column.
2788  *
2789  * The caller must have already verified that this is an auto-updatable view
2790  * using view_query_is_auto_updatable.
2791  *
2792  * Note that the checks performed here are only based on the view definition.
2793  * We do not check whether the referenced columns of the base relation are
2794  * updatable.
2795  */
2796 static const char *
2798  Bitmapset *required_cols,
2799  Bitmapset **updatable_cols,
2800  char **non_updatable_col)
2801 {
2802  RangeTblRef *rtr;
2803  AttrNumber col;
2804  ListCell *cell;
2805 
2806  /*
2807  * The caller should have verified that this view is auto-updatable and so
2808  * there should be a single base relation.
2809  */
2810  Assert(list_length(viewquery->jointree->fromlist) == 1);
2811  rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
2812 
2813  /* Initialize the optional return values */
2814  if (updatable_cols != NULL)
2815  *updatable_cols = NULL;
2816  if (non_updatable_col != NULL)
2817  *non_updatable_col = NULL;
2818 
2819  /* Test each view column for updatability */
2821  foreach(cell, viewquery->targetList)
2822  {
2823  TargetEntry *tle = (TargetEntry *) lfirst(cell);
2824  const char *col_update_detail;
2825 
2826  col++;
2827  col_update_detail = view_col_is_auto_updatable(rtr, tle);
2828 
2829  if (col_update_detail == NULL)
2830  {
2831  /* The column is updatable */
2832  if (updatable_cols != NULL)
2833  *updatable_cols = bms_add_member(*updatable_cols, col);
2834  }
2835  else if (bms_is_member(col, required_cols))
2836  {
2837  /* The required column is not updatable */
2838  if (non_updatable_col != NULL)
2839  *non_updatable_col = tle->resname;
2840  return col_update_detail;
2841  }
2842  }
2843 
2844  return NULL; /* all the required view columns are updatable */
2845 }
2846 
2847 
2848 /*
2849  * relation_is_updatable - determine which update events the specified
2850  * relation supports.
2851  *
2852  * Note that views may contain a mix of updatable and non-updatable columns.
2853  * For a view to support INSERT/UPDATE it must have at least one updatable
2854  * column, but there is no such restriction for DELETE. If include_cols is
2855  * non-NULL, then only the specified columns are considered when testing for
2856  * updatability.
2857  *
2858  * Unlike the preceding functions, this does recurse to look at a view's
2859  * base relations, so it needs to detect recursion. To do that, we pass
2860  * a list of currently-considered outer relations. External callers need
2861  * only pass NIL.
2862  *
2863  * This is used for the information_schema views, which have separate concepts
2864  * of "updatable" and "trigger updatable". A relation is "updatable" if it
2865  * can be updated without the need for triggers (either because it has a
2866  * suitable RULE, or because it is simple enough to be automatically updated).
2867  * A relation is "trigger updatable" if it has a suitable INSTEAD OF trigger.
2868  * The SQL standard regards this as not necessarily updatable, presumably
2869  * because there is no way of knowing what the trigger will actually do.
2870  * The information_schema views therefore call this function with
2871  * include_triggers = false. However, other callers might only care whether
2872  * data-modifying SQL will work, so they can pass include_triggers = true
2873  * to have trigger updatability included in the result.
2874  *
2875  * The return value is a bitmask of rule event numbers indicating which of
2876  * the INSERT, UPDATE and DELETE operations are supported. (We do it this way
2877  * so that we can test for UPDATE plus DELETE support in a single call.)
2878  */
2879 int
2881  List *outer_reloids,
2882  bool include_triggers,
2883  Bitmapset *include_cols)
2884 {
2885  int events = 0;
2886  Relation rel;
2887  RuleLock *rulelocks;
2888 
2889 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2890 
2891  /* Since this function recurses, it could be driven to stack overflow */
2893 
2894  rel = try_relation_open(reloid, AccessShareLock);
2895 
2896  /*
2897  * If the relation doesn't exist, return zero rather than throwing an
2898  * error. This is helpful since scanning an information_schema view under
2899  * MVCC rules can result in referencing rels that have actually been
2900  * deleted already.
2901  */
2902  if (rel == NULL)
2903  return 0;
2904 
2905  /* If we detect a recursive view, report that it is not updatable */
2906  if (list_member_oid(outer_reloids, RelationGetRelid(rel)))
2907  {
2909  return 0;
2910  }
2911 
2912  /* If the relation is a table, it is always updatable */
2913  if (rel->rd_rel->relkind == RELKIND_RELATION ||
2914  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2915  {
2917  return ALL_EVENTS;
2918  }
2919 
2920  /* Look for unconditional DO INSTEAD rules, and note supported events */
2921  rulelocks = rel->rd_rules;
2922  if (rulelocks != NULL)
2923  {
2924  int i;
2925 
2926  for (i = 0; i < rulelocks->numLocks; i++)
2927  {
2928  if (rulelocks->rules[i]->isInstead &&
2929  rulelocks->rules[i]->qual == NULL)
2930  {
2931  events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2932  }
2933  }
2934 
2935  /* If we have rules for all events, we're done */
2936  if (events == ALL_EVENTS)
2937  {
2939  return events;
2940  }
2941  }
2942 
2943  /* Similarly look for INSTEAD OF triggers, if they are to be included */
2944  if (include_triggers)
2945  {
2946  TriggerDesc *trigDesc = rel->trigdesc;
2947 
2948  if (trigDesc)
2949  {
2950  if (trigDesc->trig_insert_instead_row)
2951  events |= (1 << CMD_INSERT);
2952  if (trigDesc->trig_update_instead_row)
2953  events |= (1 << CMD_UPDATE);
2954  if (trigDesc->trig_delete_instead_row)
2955  events |= (1 << CMD_DELETE);
2956 
2957  /* If we have triggers for all events, we're done */
2958  if (events == ALL_EVENTS)
2959  {
2961  return events;
2962  }
2963  }
2964  }
2965 
2966  /* If this is a foreign table, check which update events it supports */
2967  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2968  {
2969  FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2970 
2971  if (fdwroutine->IsForeignRelUpdatable != NULL)
2972  events |= fdwroutine->IsForeignRelUpdatable(rel);
2973  else
2974  {
2975  /* Assume presence of executor functions is sufficient */
2976  if (fdwroutine->ExecForeignInsert != NULL)
2977  events |= (1 << CMD_INSERT);
2978  if (fdwroutine->ExecForeignUpdate != NULL)
2979  events |= (1 << CMD_UPDATE);
2980  if (fdwroutine->ExecForeignDelete != NULL)
2981  events |= (1 << CMD_DELETE);
2982  }
2983 
2985  return events;
2986  }
2987 
2988  /* Check if this is an automatically updatable view */
2989  if (rel->rd_rel->relkind == RELKIND_VIEW)
2990  {
2991  Query *viewquery = get_view_query(rel);
2992 
2993  if (view_query_is_auto_updatable(viewquery, false) == NULL)
2994  {
2995  Bitmapset *updatable_cols;
2996  int auto_events;
2997  RangeTblRef *rtr;
2998  RangeTblEntry *base_rte;
2999  Oid baseoid;
3000 
3001  /*
3002  * Determine which of the view's columns are updatable. If there
3003  * are none within the set of columns we are looking at, then the
3004  * view doesn't support INSERT/UPDATE, but it may still support
3005  * DELETE.
3006  */
3007  view_cols_are_auto_updatable(viewquery, NULL,
3008  &updatable_cols, NULL);
3009 
3010  if (include_cols != NULL)
3011  updatable_cols = bms_int_members(updatable_cols, include_cols);
3012 
3013  if (bms_is_empty(updatable_cols))
3014  auto_events = (1 << CMD_DELETE); /* May support DELETE */
3015  else
3016  auto_events = ALL_EVENTS; /* May support all events */
3017 
3018  /*
3019  * The base relation must also support these update commands.
3020  * Tables are always updatable, but for any other kind of base
3021  * relation we must do a recursive check limited to the columns
3022  * referenced by the locally updatable columns in this view.
3023  */
3024  rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
3025  base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
3026  Assert(base_rte->rtekind == RTE_RELATION);
3027 
3028  if (base_rte->relkind != RELKIND_RELATION &&
3029  base_rte->relkind != RELKIND_PARTITIONED_TABLE)
3030  {
3031  baseoid = base_rte->relid;
3032  outer_reloids = lappend_oid(outer_reloids,
3033  RelationGetRelid(rel));
3034  include_cols = adjust_view_column_set(updatable_cols,
3035  viewquery->targetList);
3036  auto_events &= relation_is_updatable(baseoid,
3037  outer_reloids,
3038  include_triggers,
3039  include_cols);
3040  outer_reloids = list_delete_last(outer_reloids);
3041  }
3042  events |= auto_events;
3043  }
3044  }
3045 
3046  /* If we reach here, the relation may support some update commands */
3048  return events;
3049 }
3050 
3051 
3052 /*
3053  * adjust_view_column_set - map a set of column numbers according to targetlist
3054  *
3055  * This is used with simply-updatable views to map column-permissions sets for
3056  * the view columns onto the matching columns in the underlying base relation.
3057  * The targetlist is expected to be a list of plain Vars of the underlying
3058  * relation (as per the checks above in view_query_is_auto_updatable).
3059  */
3060 static Bitmapset *
3062 {
3063  Bitmapset *result = NULL;
3064  int col;
3065 
3066  col = -1;
3067  while ((col = bms_next_member(cols, col)) >= 0)
3068  {
3069  /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
3071 
3072  if (attno == InvalidAttrNumber)
3073  {
3074  /*
3075  * There's a whole-row reference to the view. For permissions
3076  * purposes, treat it as a reference to each column available from
3077  * the view. (We should *not* convert this to a whole-row
3078  * reference to the base relation, since the view may not touch
3079  * all columns of the base relation.)
3080  */
3081  ListCell *lc;
3082 
3083  foreach(lc, targetlist)
3084  {
3085  TargetEntry *tle = lfirst_node(TargetEntry, lc);
3086  Var *var;
3087 
3088  if (tle->resjunk)
3089  continue;
3090  var = castNode(Var, tle->expr);
3091  result = bms_add_member(result,
3092  var->varattno - FirstLowInvalidHeapAttributeNumber);
3093  }
3094  }
3095  else
3096  {
3097  /*
3098  * Views do not have system columns, so we do not expect to see
3099  * any other system attnos here. If we do find one, the error
3100  * case will apply.
3101  */
3102  TargetEntry *tle = get_tle_by_resno(targetlist, attno);
3103 
3104  if (tle != NULL && !tle->resjunk && IsA(tle->expr, Var))
3105  {
3106  Var *var = (Var *) tle->expr;
3107 
3108  result = bms_add_member(result,
3109  var->varattno - FirstLowInvalidHeapAttributeNumber);
3110  }
3111  else
3112  elog(ERROR, "attribute number %d not found in view targetlist",
3113  attno);
3114  }
3115  }
3116 
3117  return result;
3118 }
3119 
3120 
3121 /*
3122  * rewriteTargetView -
3123  * Attempt to rewrite a query where the target relation is a view, so that
3124  * the view's base relation becomes the target relation.
3125  *
3126  * Note that the base relation here may itself be a view, which may or may not
3127  * have INSTEAD OF triggers or rules to handle the update. That is handled by
3128  * the recursion in RewriteQuery.
3129  */
3130 static Query *
3132 {
3133  Query *viewquery;
3134  const char *auto_update_detail;
3135  RangeTblRef *rtr;
3136  int base_rt_index;
3137  int new_rt_index;
3138  RangeTblEntry *base_rte;
3139  RangeTblEntry *view_rte;
3140  RangeTblEntry *new_rte;
3141  Relation base_rel;
3142  List *view_targetlist;
3143  ListCell *lc;
3144 
3145  /*
3146  * Get the Query from the view's ON SELECT rule. We're going to munge the
3147  * Query to change the view's base relation into the target relation,
3148  * along with various other changes along the way, so we need to make a
3149  * copy of it (get_view_query() returns a pointer into the relcache, so we
3150  * have to treat it as read-only).
3151  */
3152  viewquery = copyObject(get_view_query(view));
3153 
3154  /* The view must be updatable, else fail */
3155  auto_update_detail =
3156  view_query_is_auto_updatable(viewquery,
3157  parsetree->commandType != CMD_DELETE);
3158 
3159  if (auto_update_detail)
3160  {
3161  /* messages here should match execMain.c's CheckValidResultRel */
3162  switch (parsetree->commandType)
3163  {
3164  case CMD_INSERT:
3165  ereport(ERROR,
3166  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3167  errmsg("cannot insert into view \"%s\"",
3168  RelationGetRelationName(view)),
3169  errdetail_internal("%s", _(auto_update_detail)),
3170  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
3171  break;
3172  case CMD_UPDATE:
3173  ereport(ERROR,
3174  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3175  errmsg("cannot update view \"%s\"",
3176  RelationGetRelationName(view)),
3177  errdetail_internal("%s", _(auto_update_detail)),
3178  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
3179  break;
3180  case CMD_DELETE:
3181  ereport(ERROR,
3182  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3183  errmsg("cannot delete from view \"%s\"",
3184  RelationGetRelationName(view)),
3185  errdetail_internal("%s", _(auto_update_detail)),
3186  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
3187  break;
3188  default:
3189  elog(ERROR, "unrecognized CmdType: %d",
3190  (int) parsetree->commandType);
3191  break;
3192  }
3193  }
3194 
3195  /*
3196  * For INSERT/UPDATE the modified columns must all be updatable. Note that
3197  * we get the modified columns from the query's targetlist, not from the
3198  * result RTE's insertedCols and/or updatedCols set, since
3199  * rewriteTargetListIU may have added additional targetlist entries for
3200  * view defaults, and these must also be updatable.
3201  */
3202  if (parsetree->commandType != CMD_DELETE)
3203  {
3204  Bitmapset *modified_cols = NULL;
3205  char *non_updatable_col;
3206 
3207  foreach(lc, parsetree->targetList)
3208  {
3209  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3210 
3211  if (!tle->resjunk)
3212  modified_cols = bms_add_member(modified_cols,
3214  }
3215 
3216  if (parsetree->onConflict)
3217  {
3218  foreach(lc, parsetree->onConflict->onConflictSet)
3219  {
3220  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3221 
3222  if (!tle->resjunk)
3223  modified_cols = bms_add_member(modified_cols,
3225  }
3226  }
3227 
3228  auto_update_detail = view_cols_are_auto_updatable(viewquery,
3229  modified_cols,
3230  NULL,
3231  &non_updatable_col);
3232  if (auto_update_detail)
3233  {
3234  /*
3235  * This is a different error, caused by an attempt to update a
3236  * non-updatable column in an otherwise updatable view.
3237  */
3238  switch (parsetree->commandType)
3239  {
3240  case CMD_INSERT:
3241  ereport(ERROR,
3242  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3243  errmsg("cannot insert into column \"%s\" of view \"%s\"",
3244  non_updatable_col,
3245  RelationGetRelationName(view)),
3246  errdetail_internal("%s", _(auto_update_detail))));
3247  break;
3248  case CMD_UPDATE:
3249  ereport(ERROR,
3250  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3251  errmsg("cannot update column \"%s\" of view \"%s\"",
3252  non_updatable_col,
3253  RelationGetRelationName(view)),
3254  errdetail_internal("%s", _(auto_update_detail))));
3255  break;
3256  default:
3257  elog(ERROR, "unrecognized CmdType: %d",
3258  (int) parsetree->commandType);
3259  break;
3260  }
3261  }
3262  }
3263 
3264  /* Locate RTE describing the view in the outer query */
3265  view_rte = rt_fetch(parsetree->resultRelation, parsetree->rtable);
3266 
3267  /*
3268  * If we get here, view_query_is_auto_updatable() has verified that the
3269  * view contains a single base relation.
3270  */
3271  Assert(list_length(viewquery->jointree->fromlist) == 1);
3272  rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
3273 
3274  base_rt_index = rtr->rtindex;
3275  base_rte = rt_fetch(base_rt_index, viewquery->rtable);
3276  Assert(base_rte->rtekind == RTE_RELATION);
3277 
3278  /*
3279  * Up to now, the base relation hasn't been touched at all in our query.
3280  * We need to acquire lock on it before we try to do anything with it.
3281  * (The subsequent recursive call of RewriteQuery will suppose that we
3282  * already have the right lock!) Since it will become the query target
3283  * relation, RowExclusiveLock is always the right thing.
3284  */
3285  base_rel = table_open(base_rte->relid, RowExclusiveLock);
3286 
3287  /*
3288  * While we have the relation open, update the RTE's relkind, just in case
3289  * it changed since this view was made (cf. AcquireRewriteLocks).
3290  */
3291  base_rte->relkind = base_rel->rd_rel->relkind;
3292 
3293  /*
3294  * If the view query contains any sublink subqueries then we need to also
3295  * acquire locks on any relations they refer to. We know that there won't
3296  * be any subqueries in the range table or CTEs, so we can skip those, as
3297  * in AcquireRewriteLocks.
3298  */
3299  if (viewquery->hasSubLinks)
3300  {
3302 
3303  context.for_execute = true;
3304  query_tree_walker(viewquery, acquireLocksOnSubLinks, &context,
3306  }
3307 
3308  /*
3309  * Create a new target RTE describing the base relation, and add it to the
3310  * outer query's rangetable. (What's happening in the next few steps is
3311  * very much like what the planner would do to "pull up" the view into the
3312  * outer query. Perhaps someday we should refactor things enough so that
3313  * we can share code with the planner.)
3314  *
3315  * Be sure to set rellockmode to the correct thing for the target table.
3316  * Since we copied the whole viewquery above, we can just scribble on
3317  * base_rte instead of copying it.
3318  */
3319  new_rte = base_rte;
3320  new_rte->rellockmode = RowExclusiveLock;
3321 
3322  parsetree->rtable = lappend(parsetree->rtable, new_rte);
3323  new_rt_index = list_length(parsetree->rtable);
3324 
3325  /*
3326  * INSERTs never inherit. For UPDATE/DELETE, we use the view query's
3327  * inheritance flag for the base relation.
3328  */
3329  if (parsetree->commandType == CMD_INSERT)
3330  new_rte->inh = false;
3331 
3332  /*
3333  * Adjust the view's targetlist Vars to reference the new target RTE, ie
3334  * make their varnos be new_rt_index instead of base_rt_index. There can
3335  * be no Vars for other rels in the tlist, so this is sufficient to pull
3336  * up the tlist expressions for use in the outer query. The tlist will
3337  * provide the replacement expressions used by ReplaceVarsFromTargetList
3338  * below.
3339  */
3340  view_targetlist = viewquery->targetList;
3341 
3342  ChangeVarNodes((Node *) view_targetlist,
3343  base_rt_index,
3344  new_rt_index,
3345  0);
3346 
3347  /*
3348  * Mark the new target RTE for the permissions checks that we want to
3349  * enforce against the view owner, as distinct from the query caller. At
3350  * the relation level, require the same INSERT/UPDATE/DELETE permissions
3351  * that the query caller needs against the view. We drop the ACL_SELECT
3352  * bit that is presumably in new_rte->requiredPerms initially.
3353  *
3354  * Note: the original view RTE remains in the query's rangetable list.
3355  * Although it will be unused in the query plan, we need it there so that
3356  * the executor still performs appropriate permissions checks for the
3357  * query caller's use of the view.
3358  */
3359  new_rte->checkAsUser = view->rd_rel->relowner;
3360  new_rte->requiredPerms = view_rte->requiredPerms;
3361 
3362  /*
3363  * Now for the per-column permissions bits.
3364  *
3365  * Initially, new_rte contains selectedCols permission check bits for all
3366  * base-rel columns referenced by the view, but since the view is a SELECT
3367  * query its insertedCols/updatedCols is empty. We set insertedCols and
3368  * updatedCols to include all the columns the outer query is trying to
3369  * modify, adjusting the column numbers as needed. But we leave
3370  * selectedCols as-is, so the view owner must have read permission for all
3371  * columns used in the view definition, even if some of them are not read
3372  * by the outer query. We could try to limit selectedCols to only columns
3373  * used in the transformed query, but that does not correspond to what
3374  * happens in ordinary SELECT usage of a view: all referenced columns must
3375  * have read permission, even if optimization finds that some of them can
3376  * be discarded during query transformation. The flattening we're doing
3377  * here is an optional optimization, too. (If you are unpersuaded and
3378  * want to change this, note that applying adjust_view_column_set to
3379  * view_rte->selectedCols is clearly *not* the right answer, since that
3380  * neglects base-rel columns used in the view's WHERE quals.)
3381  *
3382  * This step needs the modified view targetlist, so we have to do things
3383  * in this order.
3384  */
3385  Assert(bms_is_empty(new_rte->insertedCols) &&
3386  bms_is_empty(new_rte->updatedCols));
3387 
3388  new_rte->insertedCols = adjust_view_column_set(view_rte->insertedCols,
3389  view_targetlist);
3390 
3391  new_rte->updatedCols = adjust_view_column_set(view_rte->updatedCols,
3392  view_targetlist);
3393 
3394  /*
3395  * Move any security barrier quals from the view RTE onto the new target
3396  * RTE. Any such quals should now apply to the new target RTE and will
3397  * not reference the original view RTE in the rewritten query.
3398  */
3399  new_rte->securityQuals = view_rte->securityQuals;
3400  view_rte->securityQuals = NIL;
3401 
3402  /*
3403  * Now update all Vars in the outer query that reference the view to
3404  * reference the appropriate column of the base relation instead.
3405  */
3406  parsetree = (Query *)
3407  ReplaceVarsFromTargetList((Node *) parsetree,
3408  parsetree->resultRelation,
3409  0,
3410  view_rte,
3411  view_targetlist,
3413  0,
3414  &parsetree->hasSubLinks);
3415 
3416  /*
3417  * Update all other RTI references in the query that point to the view
3418  * (for example, parsetree->resultRelation itself) to point to the new
3419  * base relation instead. Vars will not be affected since none of them
3420  * reference parsetree->resultRelation any longer.
3421  */
3422  ChangeVarNodes((Node *) parsetree,
3423  parsetree->resultRelation,
3424  new_rt_index,
3425  0);
3426  Assert(parsetree->resultRelation == new_rt_index);
3427 
3428  /*
3429  * For INSERT/UPDATE we must also update resnos in the targetlist to refer
3430  * to columns of the base relation, since those indicate the target
3431  * columns to be affected.
3432  *
3433  * Note that this destroys the resno ordering of the targetlist, but that
3434  * will be fixed when we recurse through rewriteQuery, which will invoke
3435  * rewriteTargetListIU again on the updated targetlist.
3436  */
3437  if (parsetree->commandType != CMD_DELETE)
3438  {
3439  foreach(lc, parsetree->targetList)
3440  {
3441  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3442  TargetEntry *view_tle;
3443 
3444  if (tle->resjunk)
3445  continue;
3446 
3447  view_tle = get_tle_by_resno(view_targetlist, tle->resno);
3448  if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
3449  tle->resno = ((Var *) view_tle->expr)->varattno;
3450  else
3451  elog(ERROR, "attribute number %d not found in view targetlist",
3452  tle->resno);
3453  }
3454  }
3455 
3456  /*
3457  * For INSERT .. ON CONFLICT .. DO UPDATE, we must also update assorted
3458  * stuff in the onConflict data structure.
3459  */
3460  if (parsetree->onConflict &&
3461  parsetree->onConflict->action == ONCONFLICT_UPDATE)
3462  {
3463  Index old_exclRelIndex,
3464  new_exclRelIndex;
3465  ParseNamespaceItem *new_exclNSItem;
3466  RangeTblEntry *new_exclRte;
3467  List *tmp_tlist;
3468 
3469  /*
3470  * Like the INSERT/UPDATE code above, update the resnos in the
3471  * auxiliary UPDATE targetlist to refer to columns of the base
3472  * relation.
3473  */
3474  foreach(lc, parsetree->onConflict->onConflictSet)
3475  {
3476  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3477  TargetEntry *view_tle;
3478 
3479  if (tle->resjunk)
3480  continue;
3481 
3482  view_tle = get_tle_by_resno(view_targetlist, tle->resno);
3483  if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
3484  tle->resno = ((Var *) view_tle->expr)->varattno;
3485  else
3486  elog(ERROR, "attribute number %d not found in view targetlist",
3487  tle->resno);
3488  }
3489 
3490  /*
3491  * Also, create a new RTE for the EXCLUDED pseudo-relation, using the
3492  * query's new base rel (which may well have a different column list
3493  * from the view, hence we need a new column alias list). This should
3494  * match transformOnConflictClause. In particular, note that the
3495  * relkind is set to composite to signal that we're not dealing with
3496  * an actual relation, and no permissions checks are wanted.
3497  */
3498  old_exclRelIndex = parsetree->onConflict->exclRelIndex;
3499 
3500  new_exclNSItem = addRangeTableEntryForRelation(make_parsestate(NULL),
3501  base_rel,
3503  makeAlias("excluded", NIL),
3504  false, false);
3505  new_exclRte = new_exclNSItem->p_rte;
3506  new_exclRte->relkind = RELKIND_COMPOSITE_TYPE;
3507  new_exclRte->requiredPerms = 0;
3508  /* other permissions fields in new_exclRte are already empty */
3509 
3510  parsetree->rtable = lappend(parsetree->rtable, new_exclRte);
3511  new_exclRelIndex = parsetree->onConflict->exclRelIndex =
3512  list_length(parsetree->rtable);
3513 
3514  /*
3515  * Replace the targetlist for the EXCLUDED pseudo-relation with a new
3516  * one, representing the columns from the new base relation.
3517  */
3518  parsetree->onConflict->exclRelTlist =
3519  BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex);
3520 
3521  /*
3522  * Update all Vars in the ON CONFLICT clause that refer to the old
3523  * EXCLUDED pseudo-relation. We want to use the column mappings
3524  * defined in the view targetlist, but we need the outputs to refer to
3525  * the new EXCLUDED pseudo-relation rather than the new target RTE.
3526  * Also notice that "EXCLUDED.*" will be expanded using the view's
3527  * rowtype, which seems correct.
3528  */
3529  tmp_tlist = copyObject(view_targetlist);
3530 
3531  ChangeVarNodes((Node *) tmp_tlist, new_rt_index,
3532  new_exclRelIndex, 0);
3533 
3534  parsetree->onConflict = (OnConflictExpr *)
3535  ReplaceVarsFromTargetList((Node *) parsetree->onConflict,
3536  old_exclRelIndex,
3537  0,
3538  view_rte,
3539  tmp_tlist,
3541  0,
3542  &parsetree->hasSubLinks);
3543  }
3544 
3545  /*
3546  * For UPDATE/DELETE, pull up any WHERE quals from the view. We know that
3547  * any Vars in the quals must reference the one base relation, so we need
3548  * only adjust their varnos to reference the new target (just the same as
3549  * we did with the view targetlist).
3550  *
3551  * If it's a security-barrier view, its WHERE quals must be applied before
3552  * quals from the outer query, so we attach them to the RTE as security
3553  * barrier quals rather than adding them to the main WHERE clause.
3554  *
3555  * For INSERT, the view's quals can be ignored in the main query.
3556  */
3557  if (parsetree->commandType != CMD_INSERT &&
3558  viewquery->jointree->quals != NULL)
3559  {
3560  Node *viewqual = (Node *) viewquery->jointree->quals;
3561 
3562  /*
3563  * Even though we copied viewquery already at the top of this
3564  * function, we must duplicate the viewqual again here, because we may
3565  * need to use the quals again below for a WithCheckOption clause.
3566  */
3567  viewqual = copyObject(viewqual);
3568 
3569  ChangeVarNodes(viewqual, base_rt_index, new_rt_index, 0);
3570 
3571  if (RelationIsSecurityView(view))
3572  {
3573  /*
3574  * The view's quals go in front of existing barrier quals: those
3575  * would have come from an outer level of security-barrier view,
3576  * and so must get evaluated later.
3577  *
3578  * Note: the parsetree has been mutated, so the new_rte pointer is
3579  * stale and needs to be re-computed.
3580  */
3581  new_rte = rt_fetch(new_rt_index, parsetree->rtable);
3582  new_rte->securityQuals = lcons(viewqual, new_rte->securityQuals);
3583 
3584  /*
3585  * Do not set parsetree->hasRowSecurity, because these aren't RLS
3586  * conditions (they aren't affected by enabling/disabling RLS).
3587  */
3588 
3589  /*
3590  * Make sure that the query is marked correctly if the added qual
3591  * has sublinks.
3592  */
3593  if (!parsetree->hasSubLinks)
3594  parsetree->hasSubLinks = checkExprHasSubLink(viewqual);
3595  }
3596  else
3597  AddQual(parsetree, (Node *) viewqual);
3598  }
3599 
3600  /*
3601  * For INSERT/UPDATE, if the view has the WITH CHECK OPTION, or any parent
3602  * view specified WITH CASCADED CHECK OPTION, add the quals from the view
3603  * to the query's withCheckOptions list.
3604  */
3605  if (parsetree->commandType != CMD_DELETE)
3606  {
3607  bool has_wco = RelationHasCheckOption(view);
3608  bool cascaded = RelationHasCascadedCheckOption(view);
3609 
3610  /*
3611  * If the parent view has a cascaded check option, treat this view as
3612  * if it also had a cascaded check option.
3613  *
3614  * New WithCheckOptions are added to the start of the list, so if
3615  * there is a cascaded check option, it will be the first item in the
3616  * list.
3617  */
3618  if (parsetree->withCheckOptions != NIL)
3619  {
3620  WithCheckOption *parent_wco =
3621  (WithCheckOption *) linitial(parsetree->withCheckOptions);
3622 
3623  if (parent_wco->cascaded)
3624  {
3625  has_wco = true;
3626  cascaded = true;
3627  }
3628  }
3629 
3630  /*
3631  * Add the new WithCheckOption to the start of the list, so that
3632  * checks on inner views are run before checks on outer views, as
3633  * required by the SQL standard.
3634  *
3635  * If the new check is CASCADED, we need to add it even if this view
3636  * has no quals, since there may be quals on child views. A LOCAL
3637  * check can be omitted if this view has no quals.
3638  */
3639  if (has_wco && (cascaded || viewquery->jointree->quals != NULL))
3640  {
3641  WithCheckOption *wco;
3642 
3643  wco = makeNode(WithCheckOption);
3644  wco->kind = WCO_VIEW_CHECK;
3645  wco->relname = pstrdup(RelationGetRelationName(view));
3646  wco->polname = NULL;
3647  wco->qual = NULL;
3648  wco->cascaded = cascaded;
3649 
3650  parsetree->withCheckOptions = lcons(wco,
3651  parsetree->withCheckOptions);
3652 
3653  if (viewquery->jointree->quals != NULL)
3654  {
3655  wco->qual = (Node *) viewquery->jointree->quals;
3656  ChangeVarNodes(wco->qual, base_rt_index, new_rt_index, 0);
3657 
3658  /*
3659  * Make sure that the query is marked correctly if the added
3660  * qual has sublinks. We can skip this check if the query is
3661  * already marked, or if the command is an UPDATE, in which
3662  * case the same qual will have already been added, and this
3663  * check will already have been done.
3664  */
3665  if (!parsetree->hasSubLinks &&
3666  parsetree->commandType != CMD_UPDATE)
3667  parsetree->hasSubLinks = checkExprHasSubLink(wco->qual);
3668  }
3669  }
3670  }
3671 
3672  table_close(base_rel, NoLock);
3673 
3674  return parsetree;
3675 }
3676 
3677 
3678 /*
3679  * RewriteQuery -
3680  * rewrites the query and apply the rules again on the queries rewritten
3681  *
3682  * rewrite_events is a list of open query-rewrite actions, so we can detect
3683  * infinite recursion.
3684  */
3685 static List *
3686 RewriteQuery(Query *parsetree, List *rewrite_events)
3687 {
3688  CmdType event = parsetree->commandType;
3689  bool instead = false;
3690  bool returning = false;
3691  bool updatableview = false;
3692  Query *qual_product = NULL;
3693  List *rewritten = NIL;
3694  ListCell *lc1;
3695 
3696  /*
3697  * First, recursively process any insert/update/delete statements in WITH
3698  * clauses. (We have to do this first because the WITH clauses may get
3699  * copied into rule actions below.)
3700  */
3701  foreach(lc1, parsetree->cteList)
3702  {
3704  Query *ctequery = castNode(Query, cte->ctequery);
3705  List *newstuff;
3706 
3707  if (ctequery->commandType == CMD_SELECT)
3708  continue;
3709 
3710  newstuff = RewriteQuery(ctequery, rewrite_events);
3711 
3712  /*
3713  * Currently we can only handle unconditional, single-statement DO
3714  * INSTEAD rules correctly; we have to get exactly one Query out of
3715  * the rewrite operation to stuff back into the CTE node.
3716  */
3717  if (list_length(newstuff) == 1)
3718  {
3719  /* Push the single Query back into the CTE node */
3720  ctequery = linitial_node(Query, newstuff);
3721  /* WITH queries should never be canSetTag */
3722  Assert(!ctequery->canSetTag);
3723  cte->ctequery = (Node *) ctequery;
3724  }
3725  else if (newstuff == NIL)
3726  {
3727  ereport(ERROR,
3728  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3729  errmsg("DO INSTEAD NOTHING rules are not supported for data-modifying statements in WITH")));
3730  }
3731  else
3732  {
3733  ListCell *lc2;
3734 
3735  /* examine queries to determine which error message to issue */
3736  foreach(lc2, newstuff)
3737  {
3738  Query *q = (Query *) lfirst(lc2);
3739 
3741  ereport(ERROR,
3742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3743  errmsg("conditional DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3745  ereport(ERROR,
3746  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3747  errmsg("DO ALSO rules are not supported for data-modifying statements in WITH")));
3748  }
3749 
3750  ereport(ERROR,
3751  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3752  errmsg("multi-statement DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3753  }
3754  }
3755 
3756  /*
3757  * If the statement is an insert, update, or delete, adjust its targetlist
3758  * as needed, and then fire INSERT/UPDATE/DELETE rules on it.
3759  *
3760  * SELECT rules are handled later when we have all the queries that should
3761  * get executed. Also, utilities aren't rewritten at all (do we still
3762  * need that check?)
3763  */
3764  if (event != CMD_SELECT && event != CMD_UTILITY)
3765  {
3766  int result_relation;
3767  RangeTblEntry *rt_entry;
3768  Relation rt_entry_relation;
3769  List *locks;
3770  List *product_queries;
3771  bool hasUpdate = false;
3772  int values_rte_index = 0;
3773  bool defaults_remaining = false;
3774 
3775  result_relation = parsetree->resultRelation;
3776  Assert(result_relation != 0);
3777  rt_entry = rt_fetch(result_relation, parsetree->rtable);
3778  Assert(rt_entry->rtekind == RTE_RELATION);
3779 
3780  /*
3781  * We can use NoLock here since either the parser or
3782  * AcquireRewriteLocks should have locked the rel already.
3783  */
3784  rt_entry_relation = table_open(rt_entry->relid, NoLock);
3785 
3786  /*
3787  * Rewrite the targetlist as needed for the command type.
3788  */
3789  if (event == CMD_INSERT)
3790  {
3791  RangeTblEntry *values_rte = NULL;
3792 
3793  /*
3794  * If it's an INSERT ... VALUES (...), (...), ... there will be a
3795  * single RTE for the VALUES targetlists.
3796  */
3797  if (list_length(parsetree->jointree->fromlist) == 1)
3798  {
3799  RangeTblRef *rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
3800 
3801  if (IsA(rtr, RangeTblRef))
3802  {
3803  RangeTblEntry *rte = rt_fetch(rtr->rtindex,
3804  parsetree->rtable);
3805 
3806  if (rte->rtekind == RTE_VALUES)
3807  {
3808  values_rte = rte;
3809  values_rte_index = rtr->rtindex;
3810  }
3811  }
3812  }
3813 
3814  if (values_rte)
3815  {
3816  Bitmapset *unused_values_attrnos = NULL;
3817 
3818  /* Process the main targetlist ... */
3819  parsetree->targetList = rewriteTargetListIU(parsetree->targetList,
3820  parsetree->commandType,
3821  parsetree->override,
3822  rt_entry_relation,
3823  parsetree->resultRelation,
3824  values_rte,
3825  values_rte_index,
3826  &unused_values_attrnos);
3827  /* ... and the VALUES expression lists */
3828  if (!rewriteValuesRTE(parsetree, values_rte, values_rte_index,
3829  rt_entry_relation, false,
3830  unused_values_attrnos))
3831  defaults_remaining = true;
3832  }
3833  else
3834  {
3835  /* Process just the main targetlist */
3836  parsetree->targetList =
3837  rewriteTargetListIU(parsetree->targetList,
3838  parsetree->commandType,
3839  parsetree->override,
3840  rt_entry_relation,
3841  parsetree->resultRelation,
3842  NULL, 0, NULL);
3843  }
3844 
3845  if (parsetree->onConflict &&
3846  parsetree->onConflict->action == ONCONFLICT_UPDATE)
3847  {
3848  parsetree->onConflict->onConflictSet =
3850  CMD_UPDATE,
3851  parsetree->override,
3852  rt_entry_relation,
3853  parsetree->resultRelation,
3854  NULL, 0, NULL);
3855  }
3856  }
3857  else if (event == CMD_UPDATE)
3858  {
3859  parsetree->targetList =
3860  rewriteTargetListIU(parsetree->targetList,
3861  parsetree->commandType,
3862  parsetree->override,
3863  rt_entry_relation,
3864  parsetree->resultRelation,
3865  NULL, 0, NULL);
3866 
3867  /* Also populate extraUpdatedCols (for generated columns) */
3868  fill_extraUpdatedCols(rt_entry, rt_entry_relation);
3869  }
3870  else if (event == CMD_DELETE)
3871  {
3872  /* Nothing to do here */
3873  }
3874  else
3875  elog(ERROR, "unrecognized commandType: %d", (int) event);
3876 
3877  /*
3878  * Collect and apply the appropriate rules.
3879  */
3880  locks = matchLocks(event, rt_entry_relation->rd_rules,
3881  result_relation, parsetree, &hasUpdate);
3882 
3883  product_queries = fireRules(parsetree,
3884  result_relation,
3885  event,
3886  locks,
3887  &instead,
3888  &returning,
3889  &qual_product);
3890 
3891  /*
3892  * If we have a VALUES RTE with any remaining untouched DEFAULT items,
3893  * and we got any product queries, finalize the VALUES RTE for each
3894  * product query (replacing the remaining DEFAULT items with NULLs).
3895  * We don't do this for the original query, because we know that it
3896  * must be an auto-insert on a view, and so should use the base
3897  * relation's defaults for any remaining DEFAULT items.
3898  */
3899  if (defaults_remaining && product_queries != NIL)
3900  {
3901  ListCell *n;
3902 
3903  /*
3904  * Each product query has its own copy of the VALUES RTE at the
3905  * same index in the rangetable, so we must finalize each one.
3906  */
3907  foreach(n, product_queries)
3908  {
3909  Query *pt = (Query *) lfirst(n);
3910  RangeTblEntry *values_rte = rt_fetch(values_rte_index,
3911  pt->rtable);
3912 
3913  rewriteValuesRTE(pt, values_rte, values_rte_index,
3914  rt_entry_relation,
3915  true, /* Force remaining defaults to NULL */
3916  NULL);
3917  }
3918  }
3919 
3920  /*
3921  * If there was no unqualified INSTEAD rule, and the target relation
3922  * is a view without any INSTEAD OF triggers, see if the view can be
3923  * automatically updated. If so, we perform the necessary query
3924  * transformation here and add the resulting query to the
3925  * product_queries list, so that it gets recursively rewritten if
3926  * necessary.
3927  *
3928  * If the view cannot be automatically updated, we throw an error here
3929  * which is OK since the query would fail at runtime anyway. Throwing
3930  * the error here is preferable to the executor check since we have
3931  * more detailed information available about why the view isn't
3932  * updatable.
3933  */
3934  if (!instead &&
3935  rt_entry_relation->rd_rel->relkind == RELKIND_VIEW &&
3936  !view_has_instead_trigger(rt_entry_relation, event))
3937  {
3938  /*
3939  * If there were any qualified INSTEAD rules, don't allow the view
3940  * to be automatically updated (an unqualified INSTEAD rule or
3941  * INSTEAD OF trigger is required).
3942  *
3943  * The messages here should match execMain.c's CheckValidResultRel
3944  * and in principle make those checks in executor unnecessary, but
3945  * we keep them just in case.
3946  */
3947  if (qual_product != NULL)
3948  {
3949  switch (parsetree->commandType)
3950  {
3951  case CMD_INSERT:
3952  ereport(ERROR,
3953  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3954  errmsg("cannot insert into view \"%s\"",
3955  RelationGetRelationName(rt_entry_relation)),
3956  errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3957  errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
3958  break;
3959  case CMD_UPDATE:
3960  ereport(ERROR,
3961  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3962  errmsg("cannot update view \"%s\"",
3963  RelationGetRelationName(rt_entry_relation)),
3964  errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3965  errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
3966  break;
3967  case CMD_DELETE:
3968  ereport(ERROR,
3969  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3970  errmsg("cannot delete from view \"%s\"",
3971  RelationGetRelationName(rt_entry_relation)),
3972  errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3973  errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
3974  break;
3975  default:
3976  elog(ERROR, "unrecognized CmdType: %d",
3977  (int) parsetree->commandType);
3978  break;
3979  }
3980  }
3981 
3982  /*
3983  * Attempt to rewrite the query to automatically update the view.
3984  * This throws an error if the view can't be automatically
3985  * updated.
3986  */
3987  parsetree = rewriteTargetView(parsetree, rt_entry_relation);
3988 
3989  /*
3990  * At this point product_queries contains any DO ALSO rule
3991  * actions. Add the rewritten query before or after those. This
3992  * must match the handling the original query would have gotten
3993  * below, if we allowed it to be included again.
3994  */
3995  if (parsetree->commandType == CMD_INSERT)
3996  product_queries = lcons(parsetree, product_queries);
3997  else
3998  product_queries = lappend(product_queries, parsetree);
3999 
4000  /*
4001  * Set the "instead" flag, as if there had been an unqualified
4002  * INSTEAD, to prevent the original query from being included a
4003  * second time below. The transformation will have rewritten any
4004  * RETURNING list, so we can also set "returning" to forestall
4005  * throwing an error below.
4006  */
4007  instead = true;
4008  returning = true;
4009  updatableview = true;
4010  }
4011 
4012  /*
4013  * If we got any product queries, recursively rewrite them --- but
4014  * first check for recursion!
4015  */
4016  if (product_queries != NIL)
4017  {
4018  ListCell *n;
4019  rewrite_event *rev;
4020 
4021  foreach(n, rewrite_events)
4022  {
4023  rev = (rewrite_event *) lfirst(n);
4024  if (rev->relation == RelationGetRelid(rt_entry_relation) &&
4025  rev->event == event)
4026  ereport(ERROR,
4027  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
4028  errmsg("infinite recursion detected in rules for relation \"%s\"",
4029  RelationGetRelationName(rt_entry_relation))));
4030  }
4031 
4032  rev = (rewrite_event *) palloc(sizeof(rewrite_event));
4033  rev->relation = RelationGetRelid(rt_entry_relation);
4034  rev->event = event;
4035  rewrite_events = lappend(rewrite_events, rev);
4036 
4037  foreach(n, product_queries)
4038  {
4039  Query *pt = (Query *) lfirst(n);
4040  List *newstuff;
4041 
4042  newstuff = RewriteQuery(pt, rewrite_events);
4043  rewritten = list_concat(rewritten, newstuff);
4044  }
4045 
4046  rewrite_events = list_delete_last(rewrite_events);
4047  }
4048 
4049  /*
4050  * If there is an INSTEAD, and the original query has a RETURNING, we
4051  * have to have found a RETURNING in the rule(s), else fail. (Because
4052  * DefineQueryRewrite only allows RETURNING in unconditional INSTEAD
4053  * rules, there's no need to worry whether the substituted RETURNING
4054  * will actually be executed --- it must be.)
4055  */
4056  if ((instead || qual_product != NULL) &&
4057  parsetree->returningList &&
4058  !returning)
4059  {
4060  switch (event)
4061  {
4062  case CMD_INSERT:
4063  ereport(ERROR,
4064  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4065  errmsg("cannot perform INSERT RETURNING on relation \"%s\"",
4066  RelationGetRelationName(rt_entry_relation)),
4067  errhint("You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.")));
4068  break;
4069  case CMD_UPDATE:
4070  ereport(ERROR,
4071  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4072  errmsg("cannot perform UPDATE RETURNING on relation \"%s\"",
4073  RelationGetRelationName(rt_entry_relation)),
4074  errhint("You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.")));
4075  break;
4076  case CMD_DELETE:
4077  ereport(ERROR,
4078  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4079  errmsg("cannot perform DELETE RETURNING on relation \"%s\"",
4080  RelationGetRelationName(rt_entry_relation)),
4081  errhint("You need an unconditional ON DELETE DO INSTEAD rule with a RETURNING clause.")));
4082  break;
4083  default:
4084  elog(ERROR, "unrecognized commandType: %d",
4085  (int) event);
4086  break;
4087  }
4088  }
4089 
4090  /*
4091  * Updatable views are supported by ON CONFLICT, so don't prevent that
4092  * case from proceeding
4093  */
4094  if (parsetree->onConflict &&
4095  (product_queries != NIL || hasUpdate) &&
4096  !updatableview)
4097  ereport(ERROR,
4098  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4099  errmsg("INSERT with ON CONFLICT clause cannot be used with table that has INSERT or UPDATE rules")));
4100 
4101  table_close(rt_entry_relation, NoLock);
4102  }
4103 
4104  /*
4105  * For INSERTs, the original query is done first; for UPDATE/DELETE, it is
4106  * done last. This is needed because update and delete rule actions might
4107  * not do anything if they are invoked after the update or delete is
4108  * performed. The command counter increment between the query executions
4109  * makes the deleted (and maybe the updated) tuples disappear so the scans
4110  * for them in the rule actions cannot find them.
4111  *
4112  * If we found any unqualified INSTEAD, the original query is not done at
4113  * all, in any form. Otherwise, we add the modified form if qualified
4114  * INSTEADs were found, else the unmodified form.
4115  */
4116  if (!instead)
4117  {
4118  if (parsetree->commandType == CMD_INSERT)
4119  {
4120  if (qual_product != NULL)
4121  rewritten = lcons(qual_product, rewritten);
4122  else
4123  rewritten = lcons(parsetree, rewritten);
4124  }
4125  else
4126  {
4127  if (qual_product != NULL)
4128  rewritten = lappend(rewritten, qual_product);
4129  else
4130  rewritten = lappend(rewritten, parsetree);
4131  }
4132  }
4133 
4134  /*
4135  * If the original query has a CTE list, and we generated more than one
4136  * non-utility result query, we have to fail because we'll have copied the
4137  * CTE list into each result query. That would break the expectation of
4138  * single evaluation of CTEs. This could possibly be fixed by
4139  * restructuring so that a CTE list can be shared across multiple Query
4140  * and PlannableStatement nodes.
4141  */
4142  if (parsetree->cteList != NIL)
4143  {
4144  int qcount = 0;
4145 
4146  foreach(lc1, rewritten)
4147  {
4148  Query *q = (Query *) lfirst(lc1);
4149 
4150  if (q->commandType != CMD_UTILITY)
4151  qcount++;
4152  }
4153  if (qcount > 1)
4154  ereport(ERROR,
4155  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4156  errmsg("WITH cannot be used in a query that is rewritten by rules into multiple queries")));
4157  }
4158 
4159  return rewritten;
4160 }
4161 
4162 
4163 /*
4164  * QueryRewrite -
4165  * Primary entry point to the query rewriter.
4166  * Rewrite one query via query rewrite system, possibly returning 0
4167  * or many queries.
4168  *
4169  * NOTE: the parsetree must either have come straight from the parser,
4170  * or have been scanned by AcquireRewriteLocks to acquire suitable locks.
4171  */
4172 List *
4173 QueryRewrite(Query *parsetree)
4174 {
4175  uint64 input_query_id = parsetree->queryId;
4176  List *querylist;
4177  List *results;
4178  ListCell *l;
4179  CmdType origCmdType;
4180  bool foundOriginalQuery;
4181  Query *lastInstead;
4182 
4183  /*
4184  * This function is only applied to top-level original queries
4185  */
4186  Assert(parsetree->querySource == QSRC_ORIGINAL);
4187  Assert(parsetree->canSetTag);
4188 
4189  /*
4190  * Step 1
4191  *
4192  * Apply all non-SELECT rules possibly getting 0 or many queries
4193  */
4194  querylist = RewriteQuery(parsetree, NIL);
4195 
4196  /*
4197  * Step 2
4198  *
4199  * Apply all the RIR rules on each query
4200  *
4201  * This is also a handy place to mark each query with the original queryId
4202  */
4203  results = NIL;
4204  foreach(l, querylist)
4205  {
4206  Query *query = (Query *) lfirst(l);
4207 
4208  query = fireRIRrules(query, NIL);
4209 
4210  query->queryId = input_query_id;
4211 
4212  results = lappend(results, query);
4213  }
4214 
4215  /*
4216  * Step 3
4217  *
4218  * Determine which, if any, of the resulting queries is supposed to set
4219  * the command-result tag; and update the canSetTag fields accordingly.
4220  *
4221  * If the original query is still in the list, it sets the command tag.
4222  * Otherwise, the last INSTEAD query of the same kind as the original is
4223  * allowed to set the tag. (Note these rules can leave us with no query
4224  * setting the tag. The tcop code has to cope with this by setting up a
4225  * default tag based on the original un-rewritten query.)
4226  *
4227  * The Asserts verify that at most one query in the result list is marked
4228  * canSetTag. If we aren't checking asserts, we can fall out of the loop
4229  * as soon as we find the original query.
4230  */
4231  origCmdType = parsetree->commandType;
4232  foundOriginalQuery = false;
4233  lastInstead = NULL;
4234 
4235  foreach(l, results)
4236  {
4237  Query *query = (Query *) lfirst(l);
4238 
4239  if (query->querySource == QSRC_ORIGINAL)
4240  {
4241  Assert(query->canSetTag);
4242  Assert(!foundOriginalQuery);
4243  foundOriginalQuery = true;
4244 #ifndef USE_ASSERT_CHECKING
4245  break;
4246 #endif
4247  }
4248  else
4249  {
4250  Assert(!query->canSetTag);
4251  if (query->commandType == origCmdType &&
4252  (query->querySource == QSRC_INSTEAD_RULE ||
4254  lastInstead = query;
4255  }
4256  }
4257 
4258  if (!foundOriginalQuery && lastInstead != NULL)
4259  lastInstead->canSetTag = true;
4260 
4261  return results;
4262 }
static void markQueryForLocking(Query *qry, Node *jtnode, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Node * limitOffset
Definition: parsenodes.h:160
ExecForeignDelete_function ExecForeignDelete
Definition: fdwapi.h:223
#define NIL
Definition: pg_list.h:65
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
Query * getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr)
Definition: rewriteManip.c:924
Node * qual
Definition: prs2lock.h:28
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:425
List * QueryRewrite(Query *parsetree)
Expr * arg
Definition: primnodes.h:815
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
List * joinaliasvars
Definition: parsenodes.h:1056
Index varlevelsup
Definition: primnodes.h:191
int errhint(const char *fmt,...)
Definition: elog.c:1152
int numLocks
Definition: prs2lock.h:42
static bool view_has_instead_trigger(Relation view, CmdType event)
CommonTableExpr * rewriteSearchAndCycle(CommonTableExpr *cte)
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
static bool acquireLocksOnSubLinks(Node *node, acquireLocksOnSubLinks_context *context)
FromExpr * jointree
Definition: parsenodes.h:138
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3073
bool checkExprHasSubLink(Node *node)
Definition: rewriteManip.c:277
static List * rewriteTargetListIU(List *targetList, CmdType commandType, OverridingKind override, Relation target_relation, int result_rti, RangeTblEntry *values_rte, int values_rte_index, Bitmapset **unused_values_attrnos)
#define RelationGetDescr(relation)
Definition: rel.h:483
int LOCKMODE
Definition: lockdefs.h:26
static Query * ApplyRetrieveRule(Query *parsetree, RewriteRule *rule, int rt_index, Relation relation, List *activeRIRs)
OnConflictExpr * onConflict
Definition: parsenodes.h:144
#define castNode(_type_, nodeptr)
Definition: nodes.h:602
void AddInvertedQual(Query *parsetree, Node *qual)
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:463
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:219
void get_row_security_policies(Query *root, RangeTblEntry *rte, int rt_index, List **securityQuals, List **withCheckOptions, bool *hasRowSecurity, bool *hasSubLinks)
Definition: rowsecurity.c:108
List * withCheckOptions
Definition: parsenodes.h:172
List * securityQuals
Definition: parsenodes.h:1130
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static const char * view_cols_are_auto_updatable(Query *viewquery, Bitmapset *required_cols, Bitmapset **updatable_cols, char **non_updatable_col)
bool hasAggs
Definition: parsenodes.h:125
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
int resultRelation
Definition: parsenodes.h:122
List * BuildOnConflictExcludedTargetlist(Relation targetrel, Index exclRelIndex)
Definition: analyze.c:1088
QuerySource
Definition: parsenodes.h:40
#define AccessShareLock
Definition: lockdefs.h:36
List * groupingSets
Definition: parsenodes.h:150
#define gettext_noop(x)
Definition: c.h:1197
Definition: nodes.h:533
Var * makeWholeRowVar(RangeTblEntry *rte, Index varno, Index varlevelsup, bool allowScalar)
Definition: makefuncs.c:133
static List * RewriteQuery(Query *parsetree, List *rewrite_events)
struct acquireLocksOnSubLinks_context acquireLocksOnSubLinks_context
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:694
void * stringToNode(const char *str)
Definition: read.c:89
static List * adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
AttrNumber varattno
Definition: primnodes.h:186
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
AclMode requiredPerms
Definition: parsenodes.h:1124
List * fromlist
Definition: primnodes.h:1534
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1433
Definition: primnodes.h:181
#define linitial_node(type, l)
Definition: pg_list.h:177
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
Oid getIdentitySequence(Oid relid, AttrNumber attnum, bool missing_ok)
Definition: pg_depend.c:955
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
bool isInstead
Definition: prs2lock.h:31
List * values_lists
Definition: parsenodes.h:1079
Node * quals
Definition: primnodes.h:1535
int SessionReplicationRole
Definition: trigger.c:68
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:246
LockClauseStrength strength
Definition: parsenodes.h:1388
AddForeignUpdateTargets_function AddForeignUpdateTargets
Definition: fdwapi.h:216
Definition: localtime.c:72
signed int int32
Definition: c.h:429
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1065
List * targetList
Definition: parsenodes.h:140
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
AttrDefault * defval
Definition: tupdesc.h:39
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
Node * larg
Definition: primnodes.h:1514
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
bool trig_insert_instead_row
Definition: reltrigger.h:58
RangeTblEntry * p_rte
Definition: parse_node.h:258
bool has_generated_stored
Definition: tupdesc.h:45
Bitmapset * extraUpdatedCols
Definition: parsenodes.h:1129
Bitmapset * selectedCols
Definition: parsenodes.h:1126
void pfree(void *pointer)
Definition: mcxt.c:1057
bool resjunk
Definition: primnodes.h:1438
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
#define ERROR
Definition: elog.h:45
static bool searchForDefault(RangeTblEntry *rte)
static Query * CopyAndAddInvertedQual(Query *parsetree, Node *rule_qual, int rt_index, CmdType event)
CTESearchClause * search_clause
Definition: parsenodes.h:1484
TableFunc * tablefunc
Definition: parsenodes.h:1074
static bool fireRIRonSubLink(Node *node, List *activeRIRs)
void fill_extraUpdatedCols(RangeTblEntry *target_rte, Relation target_relation)
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
static bool rewriteValuesRTE(Query *parsetree, RangeTblEntry *rte, int rti, Relation target_relation, bool force_nulls, Bitmapset *unused_cols)
#define ALL_EVENTS
TriggerDesc * trigdesc
Definition: rel.h:116
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
Definition: parse_coerce.c:669
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool trig_delete_after_row
Definition: reltrigger.h:67
Node * limitCount
Definition: parsenodes.h:161
#define NoLock
Definition: lockdefs.h:34
int32 typeMod
Definition: primnodes.h:1320
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
void check_stack_depth(void)
Definition: postgres.c:3310
TupleConstr * constr
Definition: tupdesc.h:85
#define RowExclusiveLock
Definition: lockdefs.h:38
CmdType event
Definition: prs2lock.h:27
int errdetail(const char *fmt,...)
Definition: elog.c:1038
AttrNumber resno
Definition: primnodes.h:1432
static Query * rewriteTargetView(Query *parsetree, Relation view)
List * list_delete_last(List *list)
Definition: list.c:892
bool trig_update_before_row
Definition: reltrigger.h:61
static struct rule * rules
Definition: zic.c:281
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
RewriteRule ** rules
Definition: prs2lock.h:43
#define RULE_DISABLED
Definition: rewriteDefine.h:24
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
List * actions
Definition: prs2lock.h:29
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition: makefuncs.c:271
List * returningList
Definition: parsenodes.h:146
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Oid rd_id
Definition: rel.h:112
List * newvals
Definition: primnodes.h:816
bool trig_update_after_row
Definition: reltrigger.h:62
int relation_is_updatable(Oid reloid, List *outer_reloids, bool include_triggers, Bitmapset *include_cols)
List * lappend(List *list, void *datum)
Definition: list.c:336
OnConflictAction action
Definition: primnodes.h:1550
#define PRS2_OLD_VARNO
Definition: primnodes.h:178
bool trig_update_instead_row
Definition: reltrigger.h:63
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
uint64 queryId
Definition: parsenodes.h:116
Index varno
Definition: primnodes.h:184
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
#define RULE_FIRES_ON_ORIGIN
Definition: rewriteDefine.h:21
static Bitmapset * findDefaultOnlyColumns(RangeTblEntry *rte)
static List * fireRules(Query *parsetree, int rt_index, CmdType event, List *locks, bool *instead_flag, bool *returning_flag, Query **qual_product)
Node * build_column_default(Relation rel, int attrno)
bool trig_delete_instead_row
Definition: reltrigger.h:68
#define RowShareLock
Definition: lockdefs.h:37
LockClauseStrength
Definition: lockoptions.h:21
void * palloc0(Size size)
Definition: mcxt.c:981
OverridingKind override
Definition: parsenodes.h:142
uintptr_t Datum
Definition: postgres.h:367
#define SESSION_REPLICATION_ROLE_REPLICA
Definition: trigger.h:140
bool get_rte_attribute_is_dropped(RangeTblEntry *rte, AttrNumber attnum)
#define RULE_FIRES_ON_REPLICA
Definition: rewriteDefine.h:23
unsigned int Index
Definition: c.h:549
TupleDesc rd_att
Definition: rel.h:111
bool security_barrier
Definition: parsenodes.h:1017
#define InvalidOid
Definition: postgres_ext.h:36
static Node * get_assignment_input(Node *node)
#define ereport(elevel,...)
Definition: elog.h:155
Bitmapset * updatedCols
Definition: parsenodes.h:1128
static Bitmapset * adjust_view_column_set(Bitmapset *cols, List *targetlist)
ExecForeignUpdate_function ExecForeignUpdate
Definition: fdwapi.h:222
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
List * lcons(void *datum, List *list)
Definition: list.c:468
struct rewrite_event rewrite_event
#define makeNode(_type_)
Definition: nodes.h:581
Node * rarg
Definition: primnodes.h:1515
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
QuerySource querySource
Definition: parsenodes.h:114
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
bool hasWindowFuncs
Definition: parsenodes.h:126
List * functions
Definition: parsenodes.h:1068
Node * get_typdefault(Oid typid)
Definition: lsyscache.c:2395
void AddQual(Query *parsetree, Node *qual)
Definition: rewriteManip.c:979
Expr * expr
Definition: primnodes.h:1431
#define ACL_SELECT_FOR_UPDATE
Definition: parsenodes.h:90
RuleLock * rd_rules
Definition: rel.h:114
bool canSetTag
Definition: parsenodes.h:118
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
static int list_length(const List *l)
Definition: pg_list.h:149
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1389
#define RelationHasCascadedCheckOption(relation)
Definition: rel.h:420
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
#define InvalidAttrNumber
Definition: attnum.h:23
#define nodeTag(nodeptr)
Definition: nodes.h:538
static Query * rewriteRuleAction(Query *parsetree, Query *rule_action, Node *rule_qual, int rt_index, CmdType event, bool *returning_flag)
RTEKind rtekind
Definition: parsenodes.h:981
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
uint16 num_defval
Definition: tupdesc.h:42
Expr * refassgnexpr
Definition: primnodes.h:446
List * cteList
Definition: parsenodes.h:135
CTECycleClause * cycle_clause
Definition: parsenodes.h:1485
Node * setOperations
Definition: parsenodes.h:166
Query * subquery
Definition: parsenodes.h:1016
List * groupClause
Definition: parsenodes.h:148
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:905
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
bool hasSubLinks
Definition: parsenodes.h:128
List * fieldnums
Definition: primnodes.h:817
Query * get_view_query(Relation view)
static TargetEntry * process_matched_tle(TargetEntry *src_tle, TargetEntry *prior_tle, const char *attrName)
#define elog(elevel,...)
Definition: elog.h:227
Bitmapset * insertedCols
Definition: parsenodes.h:1127
int i
AttrNumber adnum
Definition: tupdesc.h:24
#define RelationIsSecurityView(relation)
Definition: rel.h:388
char * adbin
Definition: tupdesc.h:25
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
IsForeignRelUpdatable_function IsForeignRelUpdatable
Definition: fdwapi.h:227
List * onConflictSet
Definition: primnodes.h:1559
#define NameStr(name)
Definition: c.h:681
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
void * arg
bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
Definition: rewriteManip.c:892
static const char * view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
Expr * refexpr
Definition: primnodes.h:444
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
#define copyObject(obj)
Definition: nodes.h:649
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:902
Node * havingQual
Definition: parsenodes.h:152
const char * view_query_is_auto_updatable(Query *viewquery, bool check_cols)
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:773
static Query * fireRIRrules(Query *parsetree, List *activeRIRs)
Definition: pg_list.h:50
void rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte, Relation target_relation)
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
struct TableSampleClause * tablesample
Definition: parsenodes.h:1011
int16 AttrNumber
Definition: attnum.h:21
static List * matchLocks(CmdType event, RuleLock *rulelocks, int varno, Query *parsetree, bool *hasUpdate)
#define _(x)
Definition: elog.c:89
#define RelationHasCheckOption(relation)
Definition: rel.h:398
#define RelationGetRelid(relation)
Definition: rel.h:457
LockWaitPolicy
Definition: lockoptions.h:36
CmdType
Definition: nodes.h:676
#define PRS2_NEW_VARNO
Definition: primnodes.h:179
void applyLockingClause(Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Definition: analyze.c:3166
bool hasRowSecurity
Definition: parsenodes.h:133
bool trig_delete_before_row
Definition: reltrigger.h:66
Node * strip_implicit_coercions(Node *node)
Definition: nodeFuncs.c:651
char enabled
Definition: prs2lock.h:30
OverridingKind
Definition: parsenodes.h:32