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