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