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