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