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