]> granicus.if.org Git - postgresql/blob - src/backend/rewrite/rewriteHandler.c
pgindent run.
[postgresql] / src / backend / rewrite / rewriteHandler.c
1 /*-------------------------------------------------------------------------
2  *
3  * rewriteHandler.c
4  *              Primary module of query rewriter.
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.126 2003/08/04 00:43:22 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "access/heapam.h"
17 #include "catalog/pg_operator.h"
18 #include "catalog/pg_type.h"
19 #include "miscadmin.h"
20 #include "nodes/makefuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/prep.h"
23 #include "optimizer/var.h"
24 #include "parser/analyze.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_oper.h"
28 #include "parser/parse_type.h"
29 #include "parser/parsetree.h"
30 #include "rewrite/rewriteHandler.h"
31 #include "rewrite/rewriteManip.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34
35
36 /* We use a list of these to detect recursion in RewriteQuery */
37 typedef struct rewrite_event
38 {
39         Oid                     relation;               /* OID of relation having rules */
40         CmdType         event;                  /* type of rule being fired */
41 }       rewrite_event;
42
43 static Query *rewriteRuleAction(Query *parsetree,
44                                   Query *rule_action,
45                                   Node *rule_qual,
46                                   int rt_index,
47                                   CmdType event);
48 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
49 static void rewriteTargetList(Query *parsetree, Relation target_relation);
50 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
51                                         TargetEntry *prior_tle);
52 static void markQueryForUpdate(Query *qry, bool skipOldNew);
53 static List *matchLocks(CmdType event, RuleLock *rulelocks,
54                    int varno, Query *parsetree);
55 static Query *fireRIRrules(Query *parsetree, List *activeRIRs);
56
57
58 /*
59  * rewriteRuleAction -
60  *        Rewrite the rule action with appropriate qualifiers (taken from
61  *        the triggering query).
62  */
63 static Query *
64 rewriteRuleAction(Query *parsetree,
65                                   Query *rule_action,
66                                   Node *rule_qual,
67                                   int rt_index,
68                                   CmdType event)
69 {
70         int                     current_varno,
71                                 new_varno;
72         List       *main_rtable;
73         int                     rt_length;
74         Query      *sub_action;
75         Query     **sub_action_ptr;
76         List       *rt;
77
78         /*
79          * Make modifiable copies of rule action and qual (what we're passed
80          * are the stored versions in the relcache; don't touch 'em!).
81          */
82         rule_action = (Query *) copyObject(rule_action);
83         rule_qual = (Node *) copyObject(rule_qual);
84
85         current_varno = rt_index;
86         rt_length = length(parsetree->rtable);
87         new_varno = PRS2_NEW_VARNO + rt_length;
88
89         /*
90          * Adjust rule action and qual to offset its varnos, so that we can
91          * merge its rtable with the main parsetree's rtable.
92          *
93          * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
94          * will be in the SELECT part, and we have to modify that rather than
95          * the top-level INSERT (kluge!).
96          */
97         sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
98
99         OffsetVarNodes((Node *) sub_action, rt_length, 0);
100         OffsetVarNodes(rule_qual, rt_length, 0);
101         /* but references to *OLD* should point at original rt_index */
102         ChangeVarNodes((Node *) sub_action,
103                                    PRS2_OLD_VARNO + rt_length, rt_index, 0);
104         ChangeVarNodes(rule_qual,
105                                    PRS2_OLD_VARNO + rt_length, rt_index, 0);
106
107         /*
108          * Generate expanded rtable consisting of main parsetree's rtable plus
109          * rule action's rtable; this becomes the complete rtable for the rule
110          * action.      Some of the entries may be unused after we finish
111          * rewriting, but if we tried to remove them we'd have a much harder
112          * job to adjust RT indexes in the query's Vars.  It's OK to have
113          * unused RT entries, since planner will ignore them.
114          *
115          * NOTE: because planner will destructively alter rtable, we must ensure
116          * that rule action's rtable is separate and shares no substructure
117          * with the main rtable.  Hence do a deep copy here.
118          *
119          * Also, we must disable write-access checking in all the RT entries
120          * copied from the main query.  This is safe since in fact the rule
121          * action won't write on them, and it's necessary because the rule
122          * action may have a different commandType than the main query,
123          * causing ExecCheckRTEPerms() to make an inappropriate check.  The
124          * read-access checks can be left enabled, although they're probably
125          * redundant.
126          */
127         main_rtable = (List *) copyObject(parsetree->rtable);
128
129         foreach(rt, main_rtable)
130         {
131                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
132
133                 rte->checkForWrite = false;
134         }
135
136         sub_action->rtable = nconc(main_rtable, sub_action->rtable);
137
138         /*
139          * Each rule action's jointree should be the main parsetree's jointree
140          * plus that rule's jointree, but usually *without* the original
141          * rtindex that we're replacing (if present, which it won't be for
142          * INSERT). Note that if the rule action refers to OLD, its jointree
143          * will add a reference to rt_index.  If the rule action doesn't refer
144          * to OLD, but either the rule_qual or the user query quals do, then
145          * we need to keep the original rtindex in the jointree to provide
146          * data for the quals.  We don't want the original rtindex to be
147          * joined twice, however, so avoid keeping it if the rule action
148          * mentions it.
149          *
150          * As above, the action's jointree must not share substructure with the
151          * main parsetree's.
152          */
153         if (sub_action->commandType != CMD_UTILITY)
154         {
155                 bool            keeporig;
156                 List       *newjointree;
157
158                 Assert(sub_action->jointree != NULL);
159                 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
160                                                                                   rt_index, 0)) &&
161                         (rangeTableEntry_used(rule_qual, rt_index, 0) ||
162                   rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
163                 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
164                 if (newjointree != NIL)
165                 {
166                         /*
167                          * If sub_action is a setop, manipulating its jointree will do
168                          * no good at all, because the jointree is dummy.  (Perhaps
169                          * someday we could push the joining and quals down to the
170                          * member statements of the setop?)
171                          */
172                         if (sub_action->setOperations != NULL)
173                                 ereport(ERROR,
174                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
175                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
176
177                         sub_action->jointree->fromlist =
178                                 nconc(newjointree, sub_action->jointree->fromlist);
179                 }
180         }
181
182         /*
183          * We copy the qualifications of the parsetree to the action and vice
184          * versa. So force hasSubLinks if one of them has it. If this is not
185          * right, the flag will get cleared later, but we mustn't risk having
186          * it not set when it needs to be.      (XXX this should probably be
187          * handled by AddQual and friends, not here...)
188          */
189         if (parsetree->hasSubLinks)
190                 sub_action->hasSubLinks = TRUE;
191         else if (sub_action->hasSubLinks)
192                 parsetree->hasSubLinks = TRUE;
193
194         /*
195          * Event Qualification forces copying of parsetree and splitting into
196          * two queries one w/rule_qual, one w/NOT rule_qual. Also add user
197          * query qual onto rule action
198          */
199         AddQual(sub_action, rule_qual);
200
201         AddQual(sub_action, parsetree->jointree->quals);
202
203         /*
204          * Rewrite new.attribute w/ right hand side of target-list entry for
205          * appropriate field name in insert/update.
206          *
207          * KLUGE ALERT: since ResolveNew returns a mutated copy, we can't just
208          * apply it to sub_action; we have to remember to update the sublink
209          * inside rule_action, too.
210          */
211         if (event == CMD_INSERT || event == CMD_UPDATE)
212         {
213                 sub_action = (Query *) ResolveNew((Node *) sub_action,
214                                                                                   new_varno,
215                                                                                   0,
216                                                                                   parsetree->targetList,
217                                                                                   event,
218                                                                                   current_varno);
219                 if (sub_action_ptr)
220                         *sub_action_ptr = sub_action;
221                 else
222                         rule_action = sub_action;
223         }
224
225         return rule_action;
226 }
227
228 /*
229  * Copy the query's jointree list, and optionally attempt to remove any
230  * occurrence of the given rt_index as a top-level join item (we do not look
231  * for it within join items; this is OK because we are only expecting to find
232  * it as an UPDATE or DELETE target relation, which will be at the top level
233  * of the join).  Returns modified jointree list --- this is a separate copy
234  * sharing no nodes with the original.
235  */
236 static List *
237 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
238 {
239         List       *newjointree = copyObject(parsetree->jointree->fromlist);
240         List       *jjt;
241
242         if (removert)
243         {
244                 foreach(jjt, newjointree)
245                 {
246                         RangeTblRef *rtr = lfirst(jjt);
247
248                         if (IsA(rtr, RangeTblRef) &&
249                                 rtr->rtindex == rt_index)
250                         {
251                                 newjointree = lremove(rtr, newjointree);
252                                 /* foreach is safe because we exit loop after lremove... */
253                                 break;
254                         }
255                 }
256         }
257         return newjointree;
258 }
259
260
261 /*
262  * rewriteTargetList - rewrite INSERT/UPDATE targetlist into standard form
263  *
264  * This has the following responsibilities:
265  *
266  * 1. For an INSERT, add tlist entries to compute default values for any
267  * attributes that have defaults and are not assigned to in the given tlist.
268  * (We do not insert anything for default-less attributes, however.  The
269  * planner will later insert NULLs for them, but there's no reason to slow
270  * down rewriter processing with extra tlist nodes.)  Also, for both INSERT
271  * and UPDATE, replace explicit DEFAULT specifications with column default
272  * expressions.
273  *
274  * 2. Merge multiple entries for the same target attribute, or declare error
275  * if we can't.  Presently, multiple entries are only allowed for UPDATE of
276  * an array field, for example "UPDATE table SET foo[2] = 42, foo[4] = 43".
277  * We can merge such operations into a single assignment op.  Essentially,
278  * the expression we want to produce in this case is like
279  *              foo = array_set(array_set(foo, 2, 42), 4, 43)
280  *
281  * 3. Sort the tlist into standard order: non-junk fields in order by resno,
282  * then junk fields (these in no particular order).
283  *
284  * We must do items 1 and 2 before firing rewrite rules, else rewritten
285  * references to NEW.foo will produce wrong or incomplete results.      Item 3
286  * is not needed for rewriting, but will be needed by the planner, and we
287  * can do it essentially for free while handling items 1 and 2.
288  */
289 static void
290 rewriteTargetList(Query *parsetree, Relation target_relation)
291 {
292         CmdType         commandType = parsetree->commandType;
293         List       *tlist = parsetree->targetList;
294         List       *new_tlist = NIL;
295         int                     attrno,
296                                 numattrs;
297         List       *temp;
298
299         /*
300          * Scan the tuple description in the relation's relcache entry to make
301          * sure we have all the user attributes in the right order.
302          */
303         numattrs = RelationGetNumberOfAttributes(target_relation);
304
305         for (attrno = 1; attrno <= numattrs; attrno++)
306         {
307                 Form_pg_attribute att_tup = target_relation->rd_att->attrs[attrno - 1];
308                 TargetEntry *new_tle = NULL;
309
310                 /* We can ignore deleted attributes */
311                 if (att_tup->attisdropped)
312                         continue;
313
314                 /*
315                  * Look for targetlist entries matching this attr.      We match by
316                  * resno, but the resname should match too.
317                  *
318                  * Junk attributes are not candidates to be matched.
319                  */
320                 foreach(temp, tlist)
321                 {
322                         TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
323                         Resdom     *resdom = old_tle->resdom;
324
325                         if (!resdom->resjunk && resdom->resno == attrno)
326                         {
327                                 Assert(strcmp(resdom->resname,
328                                                           NameStr(att_tup->attname)) == 0);
329                                 new_tle = process_matched_tle(old_tle, new_tle);
330                                 /* keep scanning to detect multiple assignments to attr */
331                         }
332                 }
333
334                 /*
335                  * Handle the two cases where we need to insert a default
336                  * expression: it's an INSERT and there's no tlist entry for the
337                  * column, or the tlist entry is a DEFAULT placeholder node.
338                  */
339                 if ((new_tle == NULL && commandType == CMD_INSERT) ||
340                   (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)))
341                 {
342                         Node       *new_expr;
343
344                         new_expr = build_column_default(target_relation, attrno);
345
346                         /*
347                          * If there is no default (ie, default is effectively NULL),
348                          * we can omit the tlist entry in the INSERT case, since the
349                          * planner can insert a NULL for itself, and there's no point
350                          * in spending any more rewriter cycles on the entry.  But in
351                          * the UPDATE case we've got to explicitly set the column to
352                          * NULL.
353                          */
354                         if (!new_expr)
355                         {
356                                 if (commandType == CMD_INSERT)
357                                         new_tle = NULL;
358                                 else
359                                 {
360                                         new_expr = (Node *) makeConst(att_tup->atttypid,
361                                                                                                   att_tup->attlen,
362                                                                                                   (Datum) 0,
363                                                                                                   true, /* isnull */
364                                                                                                   att_tup->attbyval);
365                                         /* this is to catch a NOT NULL domain constraint */
366                                         new_expr = coerce_to_domain(new_expr,
367                                                                                                 InvalidOid,
368                                                                                                 att_tup->atttypid,
369                                                                                                 COERCE_IMPLICIT_CAST);
370                                 }
371                         }
372
373                         if (new_expr)
374                                 new_tle = makeTargetEntry(makeResdom(attrno,
375                                                                                                          att_tup->atttypid,
376                                                                                                          att_tup->atttypmod,
377                                                                           pstrdup(NameStr(att_tup->attname)),
378                                                                                                          false),
379                                                                                   (Expr *) new_expr);
380                 }
381
382                 if (new_tle)
383                         new_tlist = lappend(new_tlist, new_tle);
384         }
385
386         /*
387          * Copy all resjunk tlist entries to the end of the new tlist, and
388          * assign them resnos above the last real resno.
389          *
390          * Typical junk entries include ORDER BY or GROUP BY expressions (are
391          * these actually possible in an INSERT or UPDATE?), system attribute
392          * references, etc.
393          */
394         foreach(temp, tlist)
395         {
396                 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
397                 Resdom     *resdom = old_tle->resdom;
398
399                 if (resdom->resjunk)
400                 {
401                         /* Get the resno right, but don't copy unnecessarily */
402                         if (resdom->resno != attrno)
403                         {
404                                 resdom = (Resdom *) copyObject((Node *) resdom);
405                                 resdom->resno = attrno;
406                                 old_tle = makeTargetEntry(resdom, old_tle->expr);
407                         }
408                         new_tlist = lappend(new_tlist, old_tle);
409                         attrno++;
410                 }
411                 else
412                 {
413                         /* Let's just make sure we processed all the non-junk items */
414                         if (resdom->resno < 1 || resdom->resno > numattrs)
415                                 elog(ERROR, "bogus resno %d in targetlist", resdom->resno);
416                 }
417         }
418
419         parsetree->targetList = new_tlist;
420 }
421
422
423 /*
424  * Convert a matched TLE from the original tlist into a correct new TLE.
425  *
426  * This routine detects and handles multiple assignments to the same target
427  * attribute.
428  */
429 static TargetEntry *
430 process_matched_tle(TargetEntry *src_tle,
431                                         TargetEntry *prior_tle)
432 {
433         Resdom     *resdom = src_tle->resdom;
434         Node       *priorbottom;
435         ArrayRef   *newexpr;
436
437         if (prior_tle == NULL)
438         {
439                 /*
440                  * Normal case where this is the first assignment to the
441                  * attribute.
442                  */
443                 return src_tle;
444         }
445
446         /*
447          * Multiple assignments to same attribute.      Allow only if all are
448          * array-assign operators with same bottom array object.
449          */
450         if (src_tle->expr == NULL || !IsA(src_tle->expr, ArrayRef) ||
451                 ((ArrayRef *) src_tle->expr)->refassgnexpr == NULL ||
452                 prior_tle->expr == NULL || !IsA(prior_tle->expr, ArrayRef) ||
453                 ((ArrayRef *) prior_tle->expr)->refassgnexpr == NULL ||
454                 ((ArrayRef *) src_tle->expr)->refrestype !=
455                 ((ArrayRef *) prior_tle->expr)->refrestype)
456                 ereport(ERROR,
457                                 (errcode(ERRCODE_SYNTAX_ERROR),
458                                  errmsg("multiple assignments to same attribute \"%s\"",
459                                                 resdom->resname)));
460
461         /*
462          * Prior TLE could be a nest of ArrayRefs if we do this more than
463          * once.
464          */
465         priorbottom = (Node *) ((ArrayRef *) prior_tle->expr)->refexpr;
466         while (priorbottom != NULL && IsA(priorbottom, ArrayRef) &&
467                    ((ArrayRef *) priorbottom)->refassgnexpr != NULL)
468                 priorbottom = (Node *) ((ArrayRef *) priorbottom)->refexpr;
469         if (!equal(priorbottom, ((ArrayRef *) src_tle->expr)->refexpr))
470                 ereport(ERROR,
471                                 (errcode(ERRCODE_SYNTAX_ERROR),
472                                  errmsg("multiple assignments to same attribute \"%s\"",
473                                                 resdom->resname)));
474
475         /*
476          * Looks OK to nest 'em.
477          */
478         newexpr = makeNode(ArrayRef);
479         memcpy(newexpr, src_tle->expr, sizeof(ArrayRef));
480         newexpr->refexpr = prior_tle->expr;
481
482         return makeTargetEntry(resdom, (Expr *) newexpr);
483 }
484
485
486 /*
487  * Make an expression tree for the default value for a column.
488  *
489  * If there is no default, return a NULL instead.
490  */
491 Node *
492 build_column_default(Relation rel, int attrno)
493 {
494         TupleDesc       rd_att = rel->rd_att;
495         Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
496         Oid                     atttype = att_tup->atttypid;
497         int32           atttypmod = att_tup->atttypmod;
498         Node       *expr = NULL;
499         Oid                     exprtype;
500
501         /*
502          * Scan to see if relation has a default for this column.
503          */
504         if (rd_att->constr && rd_att->constr->num_defval > 0)
505         {
506                 AttrDefault *defval = rd_att->constr->defval;
507                 int                     ndef = rd_att->constr->num_defval;
508
509                 while (--ndef >= 0)
510                 {
511                         if (attrno == defval[ndef].adnum)
512                         {
513                                 /*
514                                  * Found it, convert string representation to node tree.
515                                  */
516                                 expr = stringToNode(defval[ndef].adbin);
517                                 break;
518                         }
519                 }
520         }
521
522         if (expr == NULL)
523         {
524                 /*
525                  * No per-column default, so look for a default for the type
526                  * itself.
527                  */
528                 if (att_tup->attisset)
529                 {
530                         /*
531                          * Set attributes are represented as OIDs no matter what the
532                          * set element type is, and the element type's default is
533                          * irrelevant too.
534                          */
535                 }
536                 else
537                         expr = get_typdefault(atttype);
538         }
539
540         if (expr == NULL)
541                 return NULL;                    /* No default anywhere */
542
543         /*
544          * Make sure the value is coerced to the target column type; this will
545          * generally be true already, but there seem to be some corner cases
546          * involving domain defaults where it might not be true. This should
547          * match the parser's processing of non-defaulted expressions --- see
548          * updateTargetListEntry().
549          */
550         exprtype = exprType(expr);
551
552         expr = coerce_to_target_type(NULL,      /* no UNKNOWN params here */
553                                                                  expr, exprtype,
554                                                                  atttype, atttypmod,
555                                                                  COERCION_ASSIGNMENT,
556                                                                  COERCE_IMPLICIT_CAST);
557         if (expr == NULL)
558                 ereport(ERROR,
559                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
560                                  errmsg("column \"%s\" is of type %s"
561                                                 " but default expression is of type %s",
562                                                 NameStr(att_tup->attname),
563                                                 format_type_be(atttype),
564                                                 format_type_be(exprtype)),
565                    errhint("You will need to rewrite or cast the expression.")));
566
567         return expr;
568 }
569
570
571 /*
572  * matchLocks -
573  *        match the list of locks and returns the matching rules
574  */
575 static List *
576 matchLocks(CmdType event,
577                    RuleLock *rulelocks,
578                    int varno,
579                    Query *parsetree)
580 {
581         List       *matching_locks = NIL;
582         int                     nlocks;
583         int                     i;
584
585         if (rulelocks == NULL)
586                 return NIL;
587
588         if (parsetree->commandType != CMD_SELECT)
589         {
590                 if (parsetree->resultRelation != varno)
591                         return NIL;
592         }
593
594         nlocks = rulelocks->numLocks;
595
596         for (i = 0; i < nlocks; i++)
597         {
598                 RewriteRule *oneLock = rulelocks->rules[i];
599
600                 if (oneLock->event == event)
601                 {
602                         if (parsetree->commandType != CMD_SELECT ||
603                                 (oneLock->attrno == -1 ?
604                                  rangeTableEntry_used((Node *) parsetree, varno, 0) :
605                                  attribute_used((Node *) parsetree,
606                                                                 varno, oneLock->attrno, 0)))
607                                 matching_locks = lappend(matching_locks, oneLock);
608                 }
609         }
610
611         return matching_locks;
612 }
613
614
615 static Query *
616 ApplyRetrieveRule(Query *parsetree,
617                                   RewriteRule *rule,
618                                   int rt_index,
619                                   bool relation_level,
620                                   Relation relation,
621                                   bool relIsUsed,
622                                   List *activeRIRs)
623 {
624         Query      *rule_action;
625         RangeTblEntry *rte,
626                            *subrte;
627
628         if (length(rule->actions) != 1)
629                 elog(ERROR, "expected just one rule action");
630         if (rule->qual != NULL)
631                 elog(ERROR, "cannot handle qualified ON SELECT rule");
632         if (!relation_level)
633                 elog(ERROR, "cannot handle per-attribute ON SELECT rule");
634
635         /*
636          * Make a modifiable copy of the view query, and recursively expand
637          * any view references inside it.
638          */
639         rule_action = copyObject(lfirst(rule->actions));
640
641         rule_action = fireRIRrules(rule_action, activeRIRs);
642
643         /*
644          * VIEWs are really easy --- just plug the view query in as a
645          * subselect, replacing the relation's original RTE.
646          */
647         rte = rt_fetch(rt_index, parsetree->rtable);
648
649         rte->rtekind = RTE_SUBQUERY;
650         rte->relid = InvalidOid;
651         rte->subquery = rule_action;
652         rte->inh = false;                       /* must not be set for a subquery */
653
654         /*
655          * We move the view's permission check data down to its rangetable.
656          * The checks will actually be done against the *OLD* entry therein.
657          */
658         subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
659         Assert(subrte->relid == relation->rd_id);
660         subrte->checkForRead = rte->checkForRead;
661         subrte->checkForWrite = rte->checkForWrite;
662         subrte->checkAsUser = rte->checkAsUser;
663
664         rte->checkForRead = false;      /* no permission check on subquery itself */
665         rte->checkForWrite = false;
666         rte->checkAsUser = InvalidOid;
667
668         /*
669          * FOR UPDATE of view?
670          */
671         if (intMember(rt_index, parsetree->rowMarks))
672         {
673                 /*
674                  * Remove the view from the list of rels that will actually be
675                  * marked FOR UPDATE by the executor.  It will still be access-
676                  * checked for write access, though.
677                  */
678                 parsetree->rowMarks = lremovei(rt_index, parsetree->rowMarks);
679
680                 /*
681                  * Set up the view's referenced tables as if FOR UPDATE.
682                  */
683                 markQueryForUpdate(rule_action, true);
684         }
685
686         return parsetree;
687 }
688
689 /*
690  * Recursively mark all relations used by a view as FOR UPDATE.
691  *
692  * This may generate an invalid query, eg if some sub-query uses an
693  * aggregate.  We leave it to the planner to detect that.
694  *
695  * NB: this must agree with the parser's transformForUpdate() routine.
696  */
697 static void
698 markQueryForUpdate(Query *qry, bool skipOldNew)
699 {
700         Index           rti = 0;
701         List       *l;
702
703         foreach(l, qry->rtable)
704         {
705                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
706
707                 rti++;
708
709                 /* Ignore OLD and NEW entries if we are at top level of view */
710                 if (skipOldNew &&
711                         (rti == PRS2_OLD_VARNO || rti == PRS2_NEW_VARNO))
712                         continue;
713
714                 if (rte->rtekind == RTE_RELATION)
715                 {
716                         if (!intMember(rti, qry->rowMarks))
717                                 qry->rowMarks = lappendi(qry->rowMarks, rti);
718                         rte->checkForWrite = true;
719                 }
720                 else if (rte->rtekind == RTE_SUBQUERY)
721                 {
722                         /* FOR UPDATE of subquery is propagated to subquery's rels */
723                         markQueryForUpdate(rte->subquery, false);
724                 }
725         }
726 }
727
728
729 /*
730  * fireRIRonSubLink -
731  *      Apply fireRIRrules() to each SubLink (subselect in expression) found
732  *      in the given tree.
733  *
734  * NOTE: although this has the form of a walker, we cheat and modify the
735  * SubLink nodes in-place.      It is caller's responsibility to ensure that
736  * no unwanted side-effects occur!
737  *
738  * This is unlike most of the other routines that recurse into subselects,
739  * because we must take control at the SubLink node in order to replace
740  * the SubLink's subselect link with the possibly-rewritten subquery.
741  */
742 static bool
743 fireRIRonSubLink(Node *node, List *activeRIRs)
744 {
745         if (node == NULL)
746                 return false;
747         if (IsA(node, SubLink))
748         {
749                 SubLink    *sub = (SubLink *) node;
750
751                 /* Do what we came for */
752                 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
753                                                                                            activeRIRs);
754                 /* Fall through to process lefthand args of SubLink */
755         }
756
757         /*
758          * Do NOT recurse into Query nodes, because fireRIRrules already
759          * processed subselects of subselects for us.
760          */
761         return expression_tree_walker(node, fireRIRonSubLink,
762                                                                   (void *) activeRIRs);
763 }
764
765
766 /*
767  * fireRIRrules -
768  *      Apply all RIR rules on each rangetable entry in a query
769  */
770 static Query *
771 fireRIRrules(Query *parsetree, List *activeRIRs)
772 {
773         int                     rt_index;
774
775         /*
776          * don't try to convert this into a foreach loop, because rtable list
777          * can get changed each time through...
778          */
779         rt_index = 0;
780         while (rt_index < length(parsetree->rtable))
781         {
782                 RangeTblEntry *rte;
783                 Relation        rel;
784                 List       *locks;
785                 RuleLock   *rules;
786                 RewriteRule *rule;
787                 LOCKMODE        lockmode;
788                 bool            relIsUsed;
789                 int                     i;
790
791                 ++rt_index;
792
793                 rte = rt_fetch(rt_index, parsetree->rtable);
794
795                 /*
796                  * A subquery RTE can't have associated rules, so there's nothing
797                  * to do to this level of the query, but we must recurse into the
798                  * subquery to expand any rule references in it.
799                  */
800                 if (rte->rtekind == RTE_SUBQUERY)
801                 {
802                         rte->subquery = fireRIRrules(rte->subquery, activeRIRs);
803                         continue;
804                 }
805
806                 /*
807                  * Joins and other non-relation RTEs can be ignored completely.
808                  */
809                 if (rte->rtekind != RTE_RELATION)
810                         continue;
811
812                 /*
813                  * If the table is not referenced in the query, then we ignore it.
814                  * This prevents infinite expansion loop due to new rtable entries
815                  * inserted by expansion of a rule. A table is referenced if it is
816                  * part of the join set (a source table), or is referenced by any
817                  * Var nodes, or is the result table.
818                  */
819                 relIsUsed = rangeTableEntry_used((Node *) parsetree, rt_index, 0);
820
821                 if (!relIsUsed && rt_index != parsetree->resultRelation)
822                         continue;
823
824                 /*
825                  * This may well be the first access to the relation during the
826                  * current statement (it will be, if this Query was extracted from
827                  * a rule or somehow got here other than via the parser).
828                  * Therefore, grab the appropriate lock type for the relation, and
829                  * do not release it until end of transaction.  This protects the
830                  * rewriter and planner against schema changes mid-query.
831                  *
832                  * If the relation is the query's result relation, then
833                  * RewriteQuery() already got the right lock on it, so we need no
834                  * additional lock. Otherwise, check to see if the relation is
835                  * accessed FOR UPDATE or not.
836                  */
837                 if (rt_index == parsetree->resultRelation)
838                         lockmode = NoLock;
839                 else if (intMember(rt_index, parsetree->rowMarks))
840                         lockmode = RowShareLock;
841                 else
842                         lockmode = AccessShareLock;
843
844                 rel = heap_open(rte->relid, lockmode);
845
846                 /*
847                  * Collect the RIR rules that we must apply
848                  */
849                 rules = rel->rd_rules;
850                 if (rules == NULL)
851                 {
852                         heap_close(rel, NoLock);
853                         continue;
854                 }
855                 locks = NIL;
856                 for (i = 0; i < rules->numLocks; i++)
857                 {
858                         rule = rules->rules[i];
859                         if (rule->event != CMD_SELECT)
860                                 continue;
861
862                         if (rule->attrno > 0)
863                         {
864                                 /* per-attr rule; do we need it? */
865                                 if (!attribute_used((Node *) parsetree, rt_index,
866                                                                         rule->attrno, 0))
867                                         continue;
868                         }
869
870                         locks = lappend(locks, rule);
871                 }
872
873                 /*
874                  * If we found any, apply them --- but first check for recursion!
875                  */
876                 if (locks != NIL)
877                 {
878                         List       *newActiveRIRs;
879                         List       *l;
880
881                         if (oidMember(RelationGetRelid(rel), activeRIRs))
882                                 ereport(ERROR,
883                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
884                                                  errmsg("infinite recursion detected in rules for relation \"%s\"",
885                                                                 RelationGetRelationName(rel))));
886                         newActiveRIRs = lconso(RelationGetRelid(rel), activeRIRs);
887
888                         foreach(l, locks)
889                         {
890                                 rule = lfirst(l);
891
892                                 parsetree = ApplyRetrieveRule(parsetree,
893                                                                                           rule,
894                                                                                           rt_index,
895                                                                                           rule->attrno == -1,
896                                                                                           rel,
897                                                                                           relIsUsed,
898                                                                                           newActiveRIRs);
899                         }
900                 }
901
902                 heap_close(rel, NoLock);
903         }
904
905         /*
906          * Recurse into sublink subqueries, too.  But we already did the ones
907          * in the rtable.
908          */
909         if (parsetree->hasSubLinks)
910                 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
911                                                   QTW_IGNORE_RT_SUBQUERIES);
912
913         /*
914          * If the query was marked having aggregates, check if this is still
915          * true after rewriting.  Ditto for sublinks.  Note there should be no
916          * aggs in the qual at this point.      (Does this code still do anything
917          * useful?      The view-becomes-subselect-in-FROM approach doesn't look
918          * like it could remove aggs or sublinks...)
919          */
920         if (parsetree->hasAggs)
921         {
922                 parsetree->hasAggs = checkExprHasAggs((Node *) parsetree);
923                 if (parsetree->hasAggs)
924                         if (checkExprHasAggs((Node *) parsetree->jointree))
925                                 elog(ERROR, "failed to remove aggregates from qual");
926         }
927         if (parsetree->hasSubLinks)
928                 parsetree->hasSubLinks = checkExprHasSubLink((Node *) parsetree);
929
930         return parsetree;
931 }
932
933
934 /*
935  * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
936  * qualification.  This is used to generate suitable "else clauses" for
937  * conditional INSTEAD rules.  (Unfortunately we must use "x IS NOT TRUE",
938  * not just "NOT x" which the planner is much smarter about, else we will
939  * do the wrong thing when the qual evaluates to NULL.)
940  *
941  * The rule_qual may contain references to OLD or NEW.  OLD references are
942  * replaced by references to the specified rt_index (the relation that the
943  * rule applies to).  NEW references are only possible for INSERT and UPDATE
944  * queries on the relation itself, and so they should be replaced by copies
945  * of the related entries in the query's own targetlist.
946  */
947 static Query *
948 CopyAndAddInvertedQual(Query *parsetree,
949                                            Node *rule_qual,
950                                            int rt_index,
951                                            CmdType event)
952 {
953         Query      *new_tree = (Query *) copyObject(parsetree);
954         Node       *new_qual = (Node *) copyObject(rule_qual);
955
956         /* Fix references to OLD */
957         ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
958         /* Fix references to NEW */
959         if (event == CMD_INSERT || event == CMD_UPDATE)
960                 new_qual = ResolveNew(new_qual,
961                                                           PRS2_NEW_VARNO,
962                                                           0,
963                                                           parsetree->targetList,
964                                                           event,
965                                                           rt_index);
966         /* And attach the fixed qual */
967         AddInvertedQual(new_tree, new_qual);
968
969         return new_tree;
970 }
971
972
973 /*
974  *      fireRules -
975  *         Iterate through rule locks applying rules.
976  *
977  * Input arguments:
978  *      parsetree - original query
979  *      rt_index - RT index of result relation in original query
980  *      event - type of rule event
981  *      locks - list of rules to fire
982  * Output arguments:
983  *      *instead_flag - set TRUE if any unqualified INSTEAD rule is found
984  *                                      (must be initialized to FALSE)
985  *      *qual_product - filled with modified original query if any qualified
986  *                                      INSTEAD rule is found (must be initialized to NULL)
987  * Return value:
988  *      list of rule actions adjusted for use with this query
989  *
990  * Qualified INSTEAD rules generate their action with the qualification
991  * condition added.  They also generate a modified version of the original
992  * query with the negated qualification added, so that it will run only for
993  * rows that the qualified action doesn't act on.  (If there are multiple
994  * qualified INSTEAD rules, we AND all the negated quals onto a single
995  * modified original query.)  We won't execute the original, unmodified
996  * query if we find either qualified or unqualified INSTEAD rules.      If
997  * we find both, the modified original query is discarded too.
998  */
999 static List *
1000 fireRules(Query *parsetree,
1001                   int rt_index,
1002                   CmdType event,
1003                   List *locks,
1004                   bool *instead_flag,
1005                   Query **qual_product)
1006 {
1007         List       *results = NIL;
1008         List       *i;
1009
1010         foreach(i, locks)
1011         {
1012                 RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
1013                 Node       *event_qual = rule_lock->qual;
1014                 List       *actions = rule_lock->actions;
1015                 QuerySource qsrc;
1016                 List       *r;
1017
1018                 /* Determine correct QuerySource value for actions */
1019                 if (rule_lock->isInstead)
1020                 {
1021                         if (event_qual != NULL)
1022                                 qsrc = QSRC_QUAL_INSTEAD_RULE;
1023                         else
1024                         {
1025                                 qsrc = QSRC_INSTEAD_RULE;
1026                                 *instead_flag = true;   /* report unqualified INSTEAD */
1027                         }
1028                 }
1029                 else
1030                         qsrc = QSRC_NON_INSTEAD_RULE;
1031
1032                 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
1033                 {
1034                         /*
1035                          * If there are INSTEAD rules with qualifications, the
1036                          * original query is still performed. But all the negated rule
1037                          * qualifications of the INSTEAD rules are added so it does
1038                          * its actions only in cases where the rule quals of all
1039                          * INSTEAD rules are false. Think of it as the default action
1040                          * in a case. We save this in *qual_product so RewriteQuery()
1041                          * can add it to the query list after we mangled it up enough.
1042                          *
1043                          * If we have already found an unqualified INSTEAD rule, then
1044                          * *qual_product won't be used, so don't bother building it.
1045                          */
1046                         if (!*instead_flag)
1047                         {
1048                                 if (*qual_product == NULL)
1049                                         *qual_product = parsetree;
1050                                 *qual_product = CopyAndAddInvertedQual(*qual_product,
1051                                                                                                            event_qual,
1052                                                                                                            rt_index,
1053                                                                                                            event);
1054                         }
1055                 }
1056
1057                 /* Now process the rule's actions and add them to the result list */
1058                 foreach(r, actions)
1059                 {
1060                         Query      *rule_action = lfirst(r);
1061
1062                         if (rule_action->commandType == CMD_NOTHING)
1063                                 continue;
1064
1065                         rule_action = rewriteRuleAction(parsetree, rule_action,
1066                                                                                         event_qual, rt_index, event);
1067
1068                         rule_action->querySource = qsrc;
1069                         rule_action->canSetTag = false;         /* might change later */
1070
1071                         results = lappend(results, rule_action);
1072                 }
1073         }
1074
1075         return results;
1076 }
1077
1078
1079 /*
1080  * RewriteQuery -
1081  *        rewrites the query and apply the rules again on the queries rewritten
1082  *
1083  * rewrite_events is a list of open query-rewrite actions, so we can detect
1084  * infinite recursion.
1085  */
1086 static List *
1087 RewriteQuery(Query *parsetree, List *rewrite_events)
1088 {
1089         CmdType         event = parsetree->commandType;
1090         bool            instead = false;
1091         Query      *qual_product = NULL;
1092         List       *rewritten = NIL;
1093
1094         /*
1095          * If the statement is an update, insert or delete - fire rules on it.
1096          *
1097          * SELECT rules are handled later when we have all the queries that
1098          * should get executed.  Also, utilities aren't rewritten at all (do
1099          * we still need that check?)
1100          */
1101         if (event != CMD_SELECT && event != CMD_UTILITY)
1102         {
1103                 int                     result_relation;
1104                 RangeTblEntry *rt_entry;
1105                 Relation        rt_entry_relation;
1106                 List       *locks;
1107
1108                 result_relation = parsetree->resultRelation;
1109                 Assert(result_relation != 0);
1110                 rt_entry = rt_fetch(result_relation, parsetree->rtable);
1111                 Assert(rt_entry->rtekind == RTE_RELATION);
1112
1113                 /*
1114                  * This may well be the first access to the result relation during
1115                  * the current statement (it will be, if this Query was extracted
1116                  * from a rule or somehow got here other than via the parser).
1117                  * Therefore, grab the appropriate lock type for a result
1118                  * relation, and do not release it until end of transaction.  This
1119                  * protects the rewriter and planner against schema changes
1120                  * mid-query.
1121                  */
1122                 rt_entry_relation = heap_open(rt_entry->relid, RowExclusiveLock);
1123
1124                 /*
1125                  * If it's an INSERT or UPDATE, rewrite the targetlist into
1126                  * standard form.  This will be needed by the planner anyway, and
1127                  * doing it now ensures that any references to NEW.field will
1128                  * behave sanely.
1129                  */
1130                 if (event == CMD_INSERT || event == CMD_UPDATE)
1131                         rewriteTargetList(parsetree, rt_entry_relation);
1132
1133                 /*
1134                  * Collect and apply the appropriate rules.
1135                  */
1136                 locks = matchLocks(event, rt_entry_relation->rd_rules,
1137                                                    result_relation, parsetree);
1138
1139                 if (locks != NIL)
1140                 {
1141                         List       *product_queries;
1142
1143                         product_queries = fireRules(parsetree,
1144                                                                                 result_relation,
1145                                                                                 event,
1146                                                                                 locks,
1147                                                                                 &instead,
1148                                                                                 &qual_product);
1149
1150                         /*
1151                          * If we got any product queries, recursively rewrite them ---
1152                          * but first check for recursion!
1153                          */
1154                         if (product_queries != NIL)
1155                         {
1156                                 List       *n;
1157                                 rewrite_event *rev;
1158
1159                                 foreach(n, rewrite_events)
1160                                 {
1161                                         rev = (rewrite_event *) lfirst(n);
1162                                         if (rev->relation == RelationGetRelid(rt_entry_relation) &&
1163                                                 rev->event == event)
1164                                                 ereport(ERROR,
1165                                                          (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1166                                                           errmsg("infinite recursion detected in rules for relation \"%s\"",
1167                                                    RelationGetRelationName(rt_entry_relation))));
1168                                 }
1169
1170                                 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
1171                                 rev->relation = RelationGetRelid(rt_entry_relation);
1172                                 rev->event = event;
1173                                 rewrite_events = lcons(rev, rewrite_events);
1174
1175                                 foreach(n, product_queries)
1176                                 {
1177                                         Query      *pt = (Query *) lfirst(n);
1178                                         List       *newstuff;
1179
1180                                         newstuff = RewriteQuery(pt, rewrite_events);
1181                                         rewritten = nconc(rewritten, newstuff);
1182                                 }
1183                         }
1184                 }
1185
1186                 heap_close(rt_entry_relation, NoLock);  /* keep lock! */
1187         }
1188
1189         /*
1190          * For INSERTs, the original query is done first; for UPDATE/DELETE,
1191          * it is done last.  This is needed because update and delete rule
1192          * actions might not do anything if they are invoked after the update
1193          * or delete is performed. The command counter increment between the
1194          * query executions makes the deleted (and maybe the updated) tuples
1195          * disappear so the scans for them in the rule actions cannot find
1196          * them.
1197          *
1198          * If we found any unqualified INSTEAD, the original query is not done at
1199          * all, in any form.  Otherwise, we add the modified form if qualified
1200          * INSTEADs were found, else the unmodified form.
1201          */
1202         if (!instead)
1203         {
1204                 if (parsetree->commandType == CMD_INSERT)
1205                 {
1206                         if (qual_product != NULL)
1207                                 rewritten = lcons(qual_product, rewritten);
1208                         else
1209                                 rewritten = lcons(parsetree, rewritten);
1210                 }
1211                 else
1212                 {
1213                         if (qual_product != NULL)
1214                                 rewritten = lappend(rewritten, qual_product);
1215                         else
1216                                 rewritten = lappend(rewritten, parsetree);
1217                 }
1218         }
1219
1220         return rewritten;
1221 }
1222
1223
1224 /*
1225  * QueryRewrite -
1226  *        Primary entry point to the query rewriter.
1227  *        Rewrite one query via query rewrite system, possibly returning 0
1228  *        or many queries.
1229  *
1230  * NOTE: The code in QueryRewrite was formerly in pg_parse_and_plan(), and was
1231  * moved here so that it would be invoked during EXPLAIN.
1232  */
1233 List *
1234 QueryRewrite(Query *parsetree)
1235 {
1236         List       *querylist;
1237         List       *results = NIL;
1238         List       *l;
1239         CmdType         origCmdType;
1240         bool            foundOriginalQuery;
1241         Query      *lastInstead;
1242
1243         /*
1244          * Step 1
1245          *
1246          * Apply all non-SELECT rules possibly getting 0 or many queries
1247          */
1248         querylist = RewriteQuery(parsetree, NIL);
1249
1250         /*
1251          * Step 2
1252          *
1253          * Apply all the RIR rules on each query
1254          */
1255         foreach(l, querylist)
1256         {
1257                 Query      *query = (Query *) lfirst(l);
1258
1259                 query = fireRIRrules(query, NIL);
1260
1261                 /*
1262                  * If the query target was rewritten as a view, complain.
1263                  */
1264                 if (query->resultRelation)
1265                 {
1266                         RangeTblEntry *rte = rt_fetch(query->resultRelation,
1267                                                                                   query->rtable);
1268
1269                         if (rte->rtekind == RTE_SUBQUERY)
1270                         {
1271                                 switch (query->commandType)
1272                                 {
1273                                         case CMD_INSERT:
1274                                                 ereport(ERROR,
1275                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1276                                                                  errmsg("cannot insert into a view"),
1277                                                                  errhint("You need an unconditional ON INSERT DO INSTEAD rule.")));
1278                                                 break;
1279                                         case CMD_UPDATE:
1280                                                 ereport(ERROR,
1281                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1282                                                                  errmsg("cannot update a view"),
1283                                                                  errhint("You need an unconditional ON UPDATE DO INSTEAD rule.")));
1284                                                 break;
1285                                         case CMD_DELETE:
1286                                                 ereport(ERROR,
1287                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1288                                                                  errmsg("cannot delete from a view"),
1289                                                                  errhint("You need an unconditional ON DELETE DO INSTEAD rule.")));
1290                                                 break;
1291                                         default:
1292                                                 elog(ERROR, "unrecognized commandType: %d",
1293                                                          (int) query->commandType);
1294                                                 break;
1295                                 }
1296                         }
1297                 }
1298
1299                 results = lappend(results, query);
1300         }
1301
1302         /*
1303          * Step 3
1304          *
1305          * Determine which, if any, of the resulting queries is supposed to set
1306          * the command-result tag; and update the canSetTag fields
1307          * accordingly.
1308          *
1309          * If the original query is still in the list, it sets the command tag.
1310          * Otherwise, the last INSTEAD query of the same kind as the original
1311          * is allowed to set the tag.  (Note these rules can leave us with no
1312          * query setting the tag.  The tcop code has to cope with this by
1313          * setting up a default tag based on the original un-rewritten query.)
1314          *
1315          * The Asserts verify that at most one query in the result list is marked
1316          * canSetTag.  If we aren't checking asserts, we can fall out of the
1317          * loop as soon as we find the original query.
1318          */
1319         origCmdType = parsetree->commandType;
1320         foundOriginalQuery = false;
1321         lastInstead = NULL;
1322
1323         foreach(l, results)
1324         {
1325                 Query      *query = (Query *) lfirst(l);
1326
1327                 if (query->querySource == QSRC_ORIGINAL)
1328                 {
1329                         Assert(query->canSetTag);
1330                         Assert(!foundOriginalQuery);
1331                         foundOriginalQuery = true;
1332 #ifndef USE_ASSERT_CHECKING
1333                         break;
1334 #endif
1335                 }
1336                 else
1337                 {
1338                         Assert(!query->canSetTag);
1339                         if (query->commandType == origCmdType &&
1340                                 (query->querySource == QSRC_INSTEAD_RULE ||
1341                                  query->querySource == QSRC_QUAL_INSTEAD_RULE))
1342                                 lastInstead = query;
1343                 }
1344         }
1345
1346         if (!foundOriginalQuery && lastInstead != NULL)
1347                 lastInstead->canSetTag = true;
1348
1349         return results;
1350 }