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