]> granicus.if.org Git - postgresql/blob - src/backend/rewrite/rewriteHandler.c
Fix up the remaining places where the expression node structure would lose
[postgresql] / src / backend / rewrite / rewriteHandler.c
1 /*-------------------------------------------------------------------------
2  *
3  * rewriteHandler.c
4  *              Primary module of query rewriter.
5  *
6  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        $PostgreSQL: pgsql/src/backend/rewrite/rewriteHandler.c,v 1.172 2007/03/17 00:11:04 tgl Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "access/heapam.h"
17 #include "catalog/pg_type.h"
18 #include "nodes/makefuncs.h"
19 #include "optimizer/clauses.h"
20 #include "parser/analyze.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_expr.h"
23 #include "parser/parsetree.h"
24 #include "rewrite/rewriteHandler.h"
25 #include "rewrite/rewriteManip.h"
26 #include "utils/builtins.h"
27 #include "utils/lsyscache.h"
28
29
30 /* We use a list of these to detect recursion in RewriteQuery */
31 typedef struct rewrite_event
32 {
33         Oid                     relation;               /* OID of relation having rules */
34         CmdType         event;                  /* type of rule being fired */
35 } rewrite_event;
36
37 static bool acquireLocksOnSubLinks(Node *node, void *context);
38 static Query *rewriteRuleAction(Query *parsetree,
39                                   Query *rule_action,
40                                   Node *rule_qual,
41                                   int rt_index,
42                                   CmdType event,
43                                   bool *returning_flag);
44 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
45 static void rewriteTargetList(Query *parsetree, Relation target_relation,
46                                   List **attrno_list);
47 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
48                                         TargetEntry *prior_tle,
49                                         const char *attrName);
50 static Node *get_assignment_input(Node *node);
51 static void rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation,
52                                  List *attrnos);
53 static void markQueryForLocking(Query *qry, Node *jtnode,
54                                                                 bool forUpdate, bool noWait);
55 static List *matchLocks(CmdType event, RuleLock *rulelocks,
56                    int varno, Query *parsetree);
57 static Query *fireRIRrules(Query *parsetree, List *activeRIRs);
58
59
60 /*
61  * AcquireRewriteLocks -
62  *        Acquire suitable locks on all the relations mentioned in the Query.
63  *        These locks will ensure that the relation schemas don't change under us
64  *        while we are rewriting and planning the query.
65  *
66  * A secondary purpose of this routine is to fix up JOIN RTE references to
67  * dropped columns (see details below).  Because the RTEs are modified in
68  * place, it is generally appropriate for the caller of this routine to have
69  * first done a copyObject() to make a writable copy of the querytree in the
70  * current memory context.
71  *
72  * This processing can, and for efficiency's sake should, be skipped when the
73  * querytree has just been built by the parser: parse analysis already got
74  * all the same locks we'd get here, and the parser will have omitted dropped
75  * columns from JOINs to begin with.  But we must do this whenever we are
76  * dealing with a querytree produced earlier than the current command.
77  *
78  * About JOINs and dropped columns: although the parser never includes an
79  * already-dropped column in a JOIN RTE's alias var list, it is possible for
80  * such a list in a stored rule to include references to dropped columns.
81  * (If the column is not explicitly referenced anywhere else in the query,
82  * the dependency mechanism won't consider it used by the rule and so won't
83  * prevent the column drop.)  To support get_rte_attribute_is_dropped(),
84  * we replace join alias vars that reference dropped columns with NULL Const
85  * nodes.
86  *
87  * (In PostgreSQL 8.0, we did not do this processing but instead had
88  * get_rte_attribute_is_dropped() recurse to detect dropped columns in joins.
89  * That approach had horrible performance unfortunately; in particular
90  * construction of a nested join was O(N^2) in the nesting depth.)
91  */
92 void
93 AcquireRewriteLocks(Query *parsetree)
94 {
95         ListCell   *l;
96         int                     rt_index;
97
98         /*
99          * First, process RTEs of the current query level.
100          */
101         rt_index = 0;
102         foreach(l, parsetree->rtable)
103         {
104                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
105                 Relation        rel;
106                 LOCKMODE        lockmode;
107                 List       *newaliasvars;
108                 Index           curinputvarno;
109                 RangeTblEntry *curinputrte;
110                 ListCell   *ll;
111
112                 ++rt_index;
113                 switch (rte->rtekind)
114                 {
115                         case RTE_RELATION:
116
117                                 /*
118                                  * Grab the appropriate lock type for the relation, and do not
119                                  * release it until end of transaction. This protects the
120                                  * rewriter and planner against schema changes mid-query.
121                                  *
122                                  * If the relation is the query's result relation, then we
123                                  * need RowExclusiveLock.  Otherwise, check to see if the
124                                  * relation is accessed FOR UPDATE/SHARE or not.  We can't
125                                  * just grab AccessShareLock because then the executor would
126                                  * be trying to upgrade the lock, leading to possible
127                                  * deadlocks.
128                                  */
129                                 if (rt_index == parsetree->resultRelation)
130                                         lockmode = RowExclusiveLock;
131                                 else if (get_rowmark(parsetree, rt_index))
132                                         lockmode = RowShareLock;
133                                 else
134                                         lockmode = AccessShareLock;
135
136                                 rel = heap_open(rte->relid, lockmode);
137                                 heap_close(rel, NoLock);
138                                 break;
139
140                         case RTE_JOIN:
141
142                                 /*
143                                  * Scan the join's alias var list to see if any columns have
144                                  * been dropped, and if so replace those Vars with NULL
145                                  * Consts.
146                                  *
147                                  * Since a join has only two inputs, we can expect to see
148                                  * multiple references to the same input RTE; optimize away
149                                  * multiple fetches.
150                                  */
151                                 newaliasvars = NIL;
152                                 curinputvarno = 0;
153                                 curinputrte = NULL;
154                                 foreach(ll, rte->joinaliasvars)
155                                 {
156                                         Var                *aliasvar = (Var *) lfirst(ll);
157
158                                         /*
159                                          * If the list item isn't a simple Var, then it must
160                                          * represent a merged column, ie a USING column, and so it
161                                          * couldn't possibly be dropped, since it's referenced in
162                                          * the join clause.  (Conceivably it could also be a NULL
163                                          * constant already?  But that's OK too.)
164                                          */
165                                         if (IsA(aliasvar, Var))
166                                         {
167                                                 /*
168                                                  * The elements of an alias list have to refer to
169                                                  * earlier RTEs of the same rtable, because that's the
170                                                  * order the planner builds things in.  So we already
171                                                  * processed the referenced RTE, and so it's safe to
172                                                  * use get_rte_attribute_is_dropped on it. (This might
173                                                  * not hold after rewriting or planning, but it's OK
174                                                  * to assume here.)
175                                                  */
176                                                 Assert(aliasvar->varlevelsup == 0);
177                                                 if (aliasvar->varno != curinputvarno)
178                                                 {
179                                                         curinputvarno = aliasvar->varno;
180                                                         if (curinputvarno >= rt_index)
181                                                                 elog(ERROR, "unexpected varno %d in JOIN RTE %d",
182                                                                          curinputvarno, rt_index);
183                                                         curinputrte = rt_fetch(curinputvarno,
184                                                                                                    parsetree->rtable);
185                                                 }
186                                                 if (get_rte_attribute_is_dropped(curinputrte,
187                                                                                                                  aliasvar->varattno))
188                                                 {
189                                                         /*
190                                                          * can't use vartype here, since that might be a
191                                                          * now-dropped type OID, but it doesn't really
192                                                          * matter what type the Const claims to be.
193                                                          */
194                                                         aliasvar = (Var *) makeNullConst(INT4OID);
195                                                 }
196                                         }
197                                         newaliasvars = lappend(newaliasvars, aliasvar);
198                                 }
199                                 rte->joinaliasvars = newaliasvars;
200                                 break;
201
202                         case RTE_SUBQUERY:
203
204                                 /*
205                                  * The subquery RTE itself is all right, but we have to
206                                  * recurse to process the represented subquery.
207                                  */
208                                 AcquireRewriteLocks(rte->subquery);
209                                 break;
210
211                         default:
212                                 /* ignore other types of RTEs */
213                                 break;
214                 }
215         }
216
217         /*
218          * Recurse into sublink subqueries, too.  But we already did the ones in
219          * the rtable.
220          */
221         if (parsetree->hasSubLinks)
222                 query_tree_walker(parsetree, acquireLocksOnSubLinks, NULL,
223                                                   QTW_IGNORE_RT_SUBQUERIES);
224 }
225
226 /*
227  * Walker to find sublink subqueries for AcquireRewriteLocks
228  */
229 static bool
230 acquireLocksOnSubLinks(Node *node, void *context)
231 {
232         if (node == NULL)
233                 return false;
234         if (IsA(node, SubLink))
235         {
236                 SubLink    *sub = (SubLink *) node;
237
238                 /* Do what we came for */
239                 AcquireRewriteLocks((Query *) sub->subselect);
240                 /* Fall through to process lefthand args of SubLink */
241         }
242
243         /*
244          * Do NOT recurse into Query nodes, because AcquireRewriteLocks already
245          * processed subselects of subselects for us.
246          */
247         return expression_tree_walker(node, acquireLocksOnSubLinks, context);
248 }
249
250
251 /*
252  * rewriteRuleAction -
253  *        Rewrite the rule action with appropriate qualifiers (taken from
254  *        the triggering query).
255  *
256  * Input arguments:
257  *      parsetree - original query
258  *      rule_action - one action (query) of a rule
259  *      rule_qual - WHERE condition of rule, or NULL if unconditional
260  *      rt_index - RT index of result relation in original query
261  *      event - type of rule event
262  * Output arguments:
263  *      *returning_flag - set TRUE if we rewrite RETURNING clause in rule_action
264  *                                      (must be initialized to FALSE)
265  * Return value:
266  *      rewritten form of rule_action
267  */
268 static Query *
269 rewriteRuleAction(Query *parsetree,
270                                   Query *rule_action,
271                                   Node *rule_qual,
272                                   int rt_index,
273                                   CmdType event,
274                                   bool *returning_flag)
275 {
276         int                     current_varno,
277                                 new_varno;
278         int                     rt_length;
279         Query      *sub_action;
280         Query     **sub_action_ptr;
281
282         /*
283          * Make modifiable copies of rule action and qual (what we're passed are
284          * the stored versions in the relcache; don't touch 'em!).
285          */
286         rule_action = (Query *) copyObject(rule_action);
287         rule_qual = (Node *) copyObject(rule_qual);
288
289         /*
290          * Acquire necessary locks and fix any deleted JOIN RTE entries.
291          */
292         AcquireRewriteLocks(rule_action);
293         (void) acquireLocksOnSubLinks(rule_qual, NULL);
294
295         current_varno = rt_index;
296         rt_length = list_length(parsetree->rtable);
297         new_varno = PRS2_NEW_VARNO + rt_length;
298
299         /*
300          * Adjust rule action and qual to offset its varnos, so that we can merge
301          * its rtable with the main parsetree's rtable.
302          *
303          * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
304          * will be in the SELECT part, and we have to modify that rather than the
305          * top-level INSERT (kluge!).
306          */
307         sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
308
309         OffsetVarNodes((Node *) sub_action, rt_length, 0);
310         OffsetVarNodes(rule_qual, rt_length, 0);
311         /* but references to *OLD* should point at original rt_index */
312         ChangeVarNodes((Node *) sub_action,
313                                    PRS2_OLD_VARNO + rt_length, rt_index, 0);
314         ChangeVarNodes(rule_qual,
315                                    PRS2_OLD_VARNO + rt_length, rt_index, 0);
316
317         /*
318          * Generate expanded rtable consisting of main parsetree's rtable plus
319          * rule action's rtable; this becomes the complete rtable for the rule
320          * action.      Some of the entries may be unused after we finish rewriting,
321          * but we leave them all in place for two reasons:
322          *
323          * We'd have a much harder job to adjust the query's varnos if we
324          * selectively removed RT entries.
325          *
326          * If the rule is INSTEAD, then the original query won't be executed at
327          * all, and so its rtable must be preserved so that the executor will do
328          * the correct permissions checks on it.
329          *
330          * RT entries that are not referenced in the completed jointree will be
331          * ignored by the planner, so they do not affect query semantics.  But any
332          * permissions checks specified in them will be applied during executor
333          * startup (see ExecCheckRTEPerms()).  This allows us to check that the
334          * caller has, say, insert-permission on a view, when the view is not
335          * semantically referenced at all in the resulting query.
336          *
337          * When a rule is not INSTEAD, the permissions checks done on its copied
338          * RT entries will be redundant with those done during execution of the
339          * original query, but we don't bother to treat that case differently.
340          *
341          * NOTE: because planner will destructively alter rtable, we must ensure
342          * that rule action's rtable is separate and shares no substructure with
343          * the main rtable.  Hence do a deep copy here.
344          */
345         sub_action->rtable = list_concat((List *) copyObject(parsetree->rtable),
346                                                                          sub_action->rtable);
347
348         /*
349          * Each rule action's jointree should be the main parsetree's jointree
350          * plus that rule's jointree, but usually *without* the original rtindex
351          * that we're replacing (if present, which it won't be for INSERT). Note
352          * that if the rule action refers to OLD, its jointree will add a
353          * reference to rt_index.  If the rule action doesn't refer to OLD, but
354          * either the rule_qual or the user query quals do, then we need to keep
355          * the original rtindex in the jointree to provide data for the quals.  We
356          * don't want the original rtindex to be joined twice, however, so avoid
357          * keeping it if the rule action mentions it.
358          *
359          * As above, the action's jointree must not share substructure with the
360          * main parsetree's.
361          */
362         if (sub_action->commandType != CMD_UTILITY)
363         {
364                 bool            keeporig;
365                 List       *newjointree;
366
367                 Assert(sub_action->jointree != NULL);
368                 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
369                                                                                   rt_index, 0)) &&
370                         (rangeTableEntry_used(rule_qual, rt_index, 0) ||
371                          rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
372                 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
373                 if (newjointree != NIL)
374                 {
375                         /*
376                          * If sub_action is a setop, manipulating its jointree will do no
377                          * good at all, because the jointree is dummy.  (Perhaps someday
378                          * we could push the joining and quals down to the member
379                          * statements of the setop?)
380                          */
381                         if (sub_action->setOperations != NULL)
382                                 ereport(ERROR,
383                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
384                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
385
386                         sub_action->jointree->fromlist =
387                                 list_concat(newjointree, sub_action->jointree->fromlist);
388
389                         /*
390                          * There could have been some SubLinks in newjointree, in which
391                          * case we'd better mark the sub_action correctly.
392                          */
393                         if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
394                                 sub_action->hasSubLinks =
395                                         checkExprHasSubLink((Node *) newjointree);
396                 }
397         }
398
399         /*
400          * Event Qualification forces copying of parsetree and splitting into two
401          * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
402          * onto rule action
403          */
404         AddQual(sub_action, rule_qual);
405
406         AddQual(sub_action, parsetree->jointree->quals);
407
408         /*
409          * Rewrite new.attribute w/ right hand side of target-list entry for
410          * appropriate field name in insert/update.
411          *
412          * KLUGE ALERT: since ResolveNew returns a mutated copy, we can't just
413          * apply it to sub_action; we have to remember to update the sublink
414          * inside rule_action, too.
415          */
416         if ((event == CMD_INSERT || event == CMD_UPDATE) &&
417                 sub_action->commandType != CMD_UTILITY)
418         {
419                 sub_action = (Query *) ResolveNew((Node *) sub_action,
420                                                                                   new_varno,
421                                                                                   0,
422                                                                                   rt_fetch(new_varno,
423                                                                                                    sub_action->rtable),
424                                                                                   parsetree->targetList,
425                                                                                   event,
426                                                                                   current_varno);
427                 if (sub_action_ptr)
428                         *sub_action_ptr = sub_action;
429                 else
430                         rule_action = sub_action;
431         }
432
433         /*
434          * If rule_action has a RETURNING clause, then either throw it away if the
435          * triggering query has no RETURNING clause, or rewrite it to emit what
436          * the triggering query's RETURNING clause asks for.  Throw an error if
437          * more than one rule has a RETURNING clause.
438          */
439         if (!parsetree->returningList)
440                 rule_action->returningList = NIL;
441         else if (rule_action->returningList)
442         {
443                 if (*returning_flag)
444                         ereport(ERROR,
445                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
446                                    errmsg("cannot have RETURNING lists in multiple rules")));
447                 *returning_flag = true;
448                 rule_action->returningList = (List *)
449                         ResolveNew((Node *) parsetree->returningList,
450                                            parsetree->resultRelation,
451                                            0,
452                                            rt_fetch(parsetree->resultRelation,
453                                                                 parsetree->rtable),
454                                            rule_action->returningList,
455                                            CMD_SELECT,
456                                            0);
457         }
458
459         return rule_action;
460 }
461
462 /*
463  * Copy the query's jointree list, and optionally attempt to remove any
464  * occurrence of the given rt_index as a top-level join item (we do not look
465  * for it within join items; this is OK because we are only expecting to find
466  * it as an UPDATE or DELETE target relation, which will be at the top level
467  * of the join).  Returns modified jointree list --- this is a separate copy
468  * sharing no nodes with the original.
469  */
470 static List *
471 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
472 {
473         List       *newjointree = copyObject(parsetree->jointree->fromlist);
474         ListCell   *l;
475
476         if (removert)
477         {
478                 foreach(l, newjointree)
479                 {
480                         RangeTblRef *rtr = lfirst(l);
481
482                         if (IsA(rtr, RangeTblRef) &&
483                                 rtr->rtindex == rt_index)
484                         {
485                                 newjointree = list_delete_ptr(newjointree, rtr);
486
487                                 /*
488                                  * foreach is safe because we exit loop after list_delete...
489                                  */
490                                 break;
491                         }
492                 }
493         }
494         return newjointree;
495 }
496
497
498 /*
499  * rewriteTargetList - rewrite INSERT/UPDATE targetlist into standard form
500  *
501  * This has the following responsibilities:
502  *
503  * 1. For an INSERT, add tlist entries to compute default values for any
504  * attributes that have defaults and are not assigned to in the given tlist.
505  * (We do not insert anything for default-less attributes, however.  The
506  * planner will later insert NULLs for them, but there's no reason to slow
507  * down rewriter processing with extra tlist nodes.)  Also, for both INSERT
508  * and UPDATE, replace explicit DEFAULT specifications with column default
509  * expressions.
510  *
511  * 2. Merge multiple entries for the same target attribute, or declare error
512  * if we can't.  Multiple entries are only allowed for INSERT/UPDATE of
513  * portions of an array or record field, for example
514  *                      UPDATE table SET foo[2] = 42, foo[4] = 43;
515  * We can merge such operations into a single assignment op.  Essentially,
516  * the expression we want to produce in this case is like
517  *              foo = array_set(array_set(foo, 2, 42), 4, 43)
518  *
519  * 3. Sort the tlist into standard order: non-junk fields in order by resno,
520  * then junk fields (these in no particular order).
521  *
522  * We must do items 1 and 2 before firing rewrite rules, else rewritten
523  * references to NEW.foo will produce wrong or incomplete results.      Item 3
524  * is not needed for rewriting, but will be needed by the planner, and we
525  * can do it essentially for free while handling items 1 and 2.
526  *
527  * If attrno_list isn't NULL, we return an additional output besides the
528  * rewritten targetlist: an integer list of the assigned-to attnums, in
529  * order of the original tlist's non-junk entries.  This is needed for
530  * processing VALUES RTEs.
531  */
532 static void
533 rewriteTargetList(Query *parsetree, Relation target_relation,
534                                   List **attrno_list)
535 {
536         CmdType         commandType = parsetree->commandType;
537         TargetEntry **new_tles;
538         List       *new_tlist = NIL;
539         List       *junk_tlist = NIL;
540         Form_pg_attribute att_tup;
541         int                     attrno,
542                                 next_junk_attrno,
543                                 numattrs;
544         ListCell   *temp;
545
546         if (attrno_list)                        /* initialize optional result list */
547                 *attrno_list = NIL;
548
549         /*
550          * We process the normal (non-junk) attributes by scanning the input tlist
551          * once and transferring TLEs into an array, then scanning the array to
552          * build an output tlist.  This avoids O(N^2) behavior for large numbers
553          * of attributes.
554          *
555          * Junk attributes are tossed into a separate list during the same tlist
556          * scan, then appended to the reconstructed tlist.
557          */
558         numattrs = RelationGetNumberOfAttributes(target_relation);
559         new_tles = (TargetEntry **) palloc0(numattrs * sizeof(TargetEntry *));
560         next_junk_attrno = numattrs + 1;
561
562         foreach(temp, parsetree->targetList)
563         {
564                 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
565
566                 if (!old_tle->resjunk)
567                 {
568                         /* Normal attr: stash it into new_tles[] */
569                         attrno = old_tle->resno;
570                         if (attrno < 1 || attrno > numattrs)
571                                 elog(ERROR, "bogus resno %d in targetlist", attrno);
572                         att_tup = target_relation->rd_att->attrs[attrno - 1];
573
574                         /* put attrno into attrno_list even if it's dropped */
575                         if (attrno_list)
576                                 *attrno_list = lappend_int(*attrno_list, attrno);
577
578                         /* We can (and must) ignore deleted attributes */
579                         if (att_tup->attisdropped)
580                                 continue;
581
582                         /* Merge with any prior assignment to same attribute */
583                         new_tles[attrno - 1] =
584                                 process_matched_tle(old_tle,
585                                                                         new_tles[attrno - 1],
586                                                                         NameStr(att_tup->attname));
587                 }
588                 else
589                 {
590                         /*
591                          * Copy all resjunk tlist entries to junk_tlist, and assign them
592                          * resnos above the last real resno.
593                          *
594                          * Typical junk entries include ORDER BY or GROUP BY expressions
595                          * (are these actually possible in an INSERT or UPDATE?), system
596                          * attribute references, etc.
597                          */
598
599                         /* Get the resno right, but don't copy unnecessarily */
600                         if (old_tle->resno != next_junk_attrno)
601                         {
602                                 old_tle = flatCopyTargetEntry(old_tle);
603                                 old_tle->resno = next_junk_attrno;
604                         }
605                         junk_tlist = lappend(junk_tlist, old_tle);
606                         next_junk_attrno++;
607                 }
608         }
609
610         for (attrno = 1; attrno <= numattrs; attrno++)
611         {
612                 TargetEntry *new_tle = new_tles[attrno - 1];
613
614                 att_tup = target_relation->rd_att->attrs[attrno - 1];
615
616                 /* We can (and must) ignore deleted attributes */
617                 if (att_tup->attisdropped)
618                         continue;
619
620                 /*
621                  * Handle the two cases where we need to insert a default expression:
622                  * it's an INSERT and there's no tlist entry for the column, or the
623                  * tlist entry is a DEFAULT placeholder node.
624                  */
625                 if ((new_tle == NULL && commandType == CMD_INSERT) ||
626                         (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)))
627                 {
628                         Node       *new_expr;
629
630                         new_expr = build_column_default(target_relation, attrno);
631
632                         /*
633                          * If there is no default (ie, default is effectively NULL), we
634                          * can omit the tlist entry in the INSERT case, since the planner
635                          * can insert a NULL for itself, and there's no point in spending
636                          * any more rewriter cycles on the entry.  But in the UPDATE case
637                          * we've got to explicitly set the column to NULL.
638                          */
639                         if (!new_expr)
640                         {
641                                 if (commandType == CMD_INSERT)
642                                         new_tle = NULL;
643                                 else
644                                 {
645                                         new_expr = (Node *) makeConst(att_tup->atttypid,
646                                                                                                   -1,
647                                                                                                   att_tup->attlen,
648                                                                                                   (Datum) 0,
649                                                                                                   true, /* isnull */
650                                                                                                   att_tup->attbyval);
651                                         /* this is to catch a NOT NULL domain constraint */
652                                         new_expr = coerce_to_domain(new_expr,
653                                                                                                 InvalidOid, -1,
654                                                                                                 att_tup->atttypid,
655                                                                                                 COERCE_IMPLICIT_CAST,
656                                                                                                 false,
657                                                                                                 false);
658                                 }
659                         }
660
661                         if (new_expr)
662                                 new_tle = makeTargetEntry((Expr *) new_expr,
663                                                                                   attrno,
664                                                                                   pstrdup(NameStr(att_tup->attname)),
665                                                                                   false);
666                 }
667
668                 if (new_tle)
669                         new_tlist = lappend(new_tlist, new_tle);
670         }
671
672         pfree(new_tles);
673
674         parsetree->targetList = list_concat(new_tlist, junk_tlist);
675 }
676
677
678 /*
679  * Convert a matched TLE from the original tlist into a correct new TLE.
680  *
681  * This routine detects and handles multiple assignments to the same target
682  * attribute.  (The attribute name is needed only for error messages.)
683  */
684 static TargetEntry *
685 process_matched_tle(TargetEntry *src_tle,
686                                         TargetEntry *prior_tle,
687                                         const char *attrName)
688 {
689         TargetEntry *result;
690         Node       *src_expr;
691         Node       *prior_expr;
692         Node       *src_input;
693         Node       *prior_input;
694         Node       *priorbottom;
695         Node       *newexpr;
696
697         if (prior_tle == NULL)
698         {
699                 /*
700                  * Normal case where this is the first assignment to the attribute.
701                  */
702                 return src_tle;
703         }
704
705         /*----------
706          * Multiple assignments to same attribute.      Allow only if all are
707          * FieldStore or ArrayRef assignment operations.  This is a bit
708          * tricky because what we may actually be looking at is a nest of
709          * such nodes; consider
710          *              UPDATE tab SET col.fld1.subfld1 = x, col.fld2.subfld2 = y
711          * The two expressions produced by the parser will look like
712          *              FieldStore(col, fld1, FieldStore(placeholder, subfld1, x))
713          *              FieldStore(col, fld2, FieldStore(placeholder, subfld2, x))
714          * However, we can ignore the substructure and just consider the top
715          * FieldStore or ArrayRef from each assignment, because it works to
716          * combine these as
717          *              FieldStore(FieldStore(col, fld1,
718          *                                                        FieldStore(placeholder, subfld1, x)),
719          *                                 fld2, FieldStore(placeholder, subfld2, x))
720          * Note the leftmost expression goes on the inside so that the
721          * assignments appear to occur left-to-right.
722          *
723          * For FieldStore, instead of nesting we can generate a single
724          * FieldStore with multiple target fields.      We must nest when
725          * ArrayRefs are involved though.
726          *----------
727          */
728         src_expr = (Node *) src_tle->expr;
729         prior_expr = (Node *) prior_tle->expr;
730         src_input = get_assignment_input(src_expr);
731         prior_input = get_assignment_input(prior_expr);
732         if (src_input == NULL ||
733                 prior_input == NULL ||
734                 exprType(src_expr) != exprType(prior_expr))
735                 ereport(ERROR,
736                                 (errcode(ERRCODE_SYNTAX_ERROR),
737                                  errmsg("multiple assignments to same column \"%s\"",
738                                                 attrName)));
739
740         /*
741          * Prior TLE could be a nest of assignments if we do this more than once.
742          */
743         priorbottom = prior_input;
744         for (;;)
745         {
746                 Node       *newbottom = get_assignment_input(priorbottom);
747
748                 if (newbottom == NULL)
749                         break;                          /* found the original Var reference */
750                 priorbottom = newbottom;
751         }
752         if (!equal(priorbottom, src_input))
753                 ereport(ERROR,
754                                 (errcode(ERRCODE_SYNTAX_ERROR),
755                                  errmsg("multiple assignments to same column \"%s\"",
756                                                 attrName)));
757
758         /*
759          * Looks OK to nest 'em.
760          */
761         if (IsA(src_expr, FieldStore))
762         {
763                 FieldStore *fstore = makeNode(FieldStore);
764
765                 if (IsA(prior_expr, FieldStore))
766                 {
767                         /* combine the two */
768                         memcpy(fstore, prior_expr, sizeof(FieldStore));
769                         fstore->newvals =
770                                 list_concat(list_copy(((FieldStore *) prior_expr)->newvals),
771                                                         list_copy(((FieldStore *) src_expr)->newvals));
772                         fstore->fieldnums =
773                                 list_concat(list_copy(((FieldStore *) prior_expr)->fieldnums),
774                                                         list_copy(((FieldStore *) src_expr)->fieldnums));
775                 }
776                 else
777                 {
778                         /* general case, just nest 'em */
779                         memcpy(fstore, src_expr, sizeof(FieldStore));
780                         fstore->arg = (Expr *) prior_expr;
781                 }
782                 newexpr = (Node *) fstore;
783         }
784         else if (IsA(src_expr, ArrayRef))
785         {
786                 ArrayRef   *aref = makeNode(ArrayRef);
787
788                 memcpy(aref, src_expr, sizeof(ArrayRef));
789                 aref->refexpr = (Expr *) prior_expr;
790                 newexpr = (Node *) aref;
791         }
792         else
793         {
794                 elog(ERROR, "cannot happen");
795                 newexpr = NULL;
796         }
797
798         result = flatCopyTargetEntry(src_tle);
799         result->expr = (Expr *) newexpr;
800         return result;
801 }
802
803 /*
804  * If node is an assignment node, return its input; else return NULL
805  */
806 static Node *
807 get_assignment_input(Node *node)
808 {
809         if (node == NULL)
810                 return NULL;
811         if (IsA(node, FieldStore))
812         {
813                 FieldStore *fstore = (FieldStore *) node;
814
815                 return (Node *) fstore->arg;
816         }
817         else if (IsA(node, ArrayRef))
818         {
819                 ArrayRef   *aref = (ArrayRef *) node;
820
821                 if (aref->refassgnexpr == NULL)
822                         return NULL;
823                 return (Node *) aref->refexpr;
824         }
825         return NULL;
826 }
827
828 /*
829  * Make an expression tree for the default value for a column.
830  *
831  * If there is no default, return a NULL instead.
832  */
833 Node *
834 build_column_default(Relation rel, int attrno)
835 {
836         TupleDesc       rd_att = rel->rd_att;
837         Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
838         Oid                     atttype = att_tup->atttypid;
839         int32           atttypmod = att_tup->atttypmod;
840         Node       *expr = NULL;
841         Oid                     exprtype;
842
843         /*
844          * Scan to see if relation has a default for this column.
845          */
846         if (rd_att->constr && rd_att->constr->num_defval > 0)
847         {
848                 AttrDefault *defval = rd_att->constr->defval;
849                 int                     ndef = rd_att->constr->num_defval;
850
851                 while (--ndef >= 0)
852                 {
853                         if (attrno == defval[ndef].adnum)
854                         {
855                                 /*
856                                  * Found it, convert string representation to node tree.
857                                  */
858                                 expr = stringToNode(defval[ndef].adbin);
859                                 break;
860                         }
861                 }
862         }
863
864         if (expr == NULL)
865         {
866                 /*
867                  * No per-column default, so look for a default for the type itself.
868                  */
869                 expr = get_typdefault(atttype);
870         }
871
872         if (expr == NULL)
873                 return NULL;                    /* No default anywhere */
874
875         /*
876          * Make sure the value is coerced to the target column type; this will
877          * generally be true already, but there seem to be some corner cases
878          * involving domain defaults where it might not be true. This should match
879          * the parser's processing of non-defaulted expressions --- see
880          * transformAssignedExpr().
881          */
882         exprtype = exprType(expr);
883
884         expr = coerce_to_target_type(NULL,      /* no UNKNOWN params here */
885                                                                  expr, exprtype,
886                                                                  atttype, atttypmod,
887                                                                  COERCION_ASSIGNMENT,
888                                                                  COERCE_IMPLICIT_CAST);
889         if (expr == NULL)
890                 ereport(ERROR,
891                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
892                                  errmsg("column \"%s\" is of type %s"
893                                                 " but default expression is of type %s",
894                                                 NameStr(att_tup->attname),
895                                                 format_type_be(atttype),
896                                                 format_type_be(exprtype)),
897                            errhint("You will need to rewrite or cast the expression.")));
898
899         return expr;
900 }
901
902
903 /* Does VALUES RTE contain any SetToDefault items? */
904 static bool
905 searchForDefault(RangeTblEntry *rte)
906 {
907         ListCell   *lc;
908
909         foreach(lc, rte->values_lists)
910         {
911                 List       *sublist = (List *) lfirst(lc);
912                 ListCell   *lc2;
913
914                 foreach(lc2, sublist)
915                 {
916                         Node       *col = (Node *) lfirst(lc2);
917
918                         if (IsA(col, SetToDefault))
919                                 return true;
920                 }
921         }
922         return false;
923 }
924
925 /*
926  * When processing INSERT ... VALUES with a VALUES RTE (ie, multiple VALUES
927  * lists), we have to replace any DEFAULT items in the VALUES lists with
928  * the appropriate default expressions.  The other aspects of rewriteTargetList
929  * need be applied only to the query's targetlist proper.
930  *
931  * Note that we currently can't support subscripted or field assignment
932  * in the multi-VALUES case.  The targetlist will contain simple Vars
933  * referencing the VALUES RTE, and therefore process_matched_tle() will
934  * reject any such attempt with "multiple assignments to same column".
935  */
936 static void
937 rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation, List *attrnos)
938 {
939         List       *newValues;
940         ListCell   *lc;
941
942         /*
943          * Rebuilding all the lists is a pretty expensive proposition in a big
944          * VALUES list, and it's a waste of time if there aren't any DEFAULT
945          * placeholders.  So first scan to see if there are any.
946          */
947         if (!searchForDefault(rte))
948                 return;                                 /* nothing to do */
949
950         /* Check list lengths (we can assume all the VALUES sublists are alike) */
951         Assert(list_length(attrnos) == list_length(linitial(rte->values_lists)));
952
953         newValues = NIL;
954         foreach(lc, rte->values_lists)
955         {
956                 List       *sublist = (List *) lfirst(lc);
957                 List       *newList = NIL;
958                 ListCell   *lc2;
959                 ListCell   *lc3;
960
961                 forboth(lc2, sublist, lc3, attrnos)
962                 {
963                         Node       *col = (Node *) lfirst(lc2);
964                         int                     attrno = lfirst_int(lc3);
965
966                         if (IsA(col, SetToDefault))
967                         {
968                                 Form_pg_attribute att_tup;
969                                 Node       *new_expr;
970
971                                 att_tup = target_relation->rd_att->attrs[attrno - 1];
972
973                                 if (!att_tup->attisdropped)
974                                         new_expr = build_column_default(target_relation, attrno);
975                                 else
976                                         new_expr = NULL;        /* force a NULL if dropped */
977
978                                 /*
979                                  * If there is no default (ie, default is effectively NULL),
980                                  * we've got to explicitly set the column to NULL.
981                                  */
982                                 if (!new_expr)
983                                 {
984                                         new_expr = (Node *) makeConst(att_tup->atttypid,
985                                                                                                   -1,
986                                                                                                   att_tup->attlen,
987                                                                                                   (Datum) 0,
988                                                                                                   true, /* isnull */
989                                                                                                   att_tup->attbyval);
990                                         /* this is to catch a NOT NULL domain constraint */
991                                         new_expr = coerce_to_domain(new_expr,
992                                                                                                 InvalidOid, -1,
993                                                                                                 att_tup->atttypid,
994                                                                                                 COERCE_IMPLICIT_CAST,
995                                                                                                 false,
996                                                                                                 false);
997                                 }
998                                 newList = lappend(newList, new_expr);
999                         }
1000                         else
1001                                 newList = lappend(newList, col);
1002                 }
1003                 newValues = lappend(newValues, newList);
1004         }
1005         rte->values_lists = newValues;
1006 }
1007
1008
1009 /*
1010  * matchLocks -
1011  *        match the list of locks and returns the matching rules
1012  */
1013 static List *
1014 matchLocks(CmdType event,
1015                    RuleLock *rulelocks,
1016                    int varno,
1017                    Query *parsetree)
1018 {
1019         List       *matching_locks = NIL;
1020         int                     nlocks;
1021         int                     i;
1022
1023         if (rulelocks == NULL)
1024                 return NIL;
1025
1026         if (parsetree->commandType != CMD_SELECT)
1027         {
1028                 if (parsetree->resultRelation != varno)
1029                         return NIL;
1030         }
1031
1032         nlocks = rulelocks->numLocks;
1033
1034         for (i = 0; i < nlocks; i++)
1035         {
1036                 RewriteRule *oneLock = rulelocks->rules[i];
1037
1038                 if (oneLock->event == event)
1039                 {
1040                         if (parsetree->commandType != CMD_SELECT ||
1041                                 (oneLock->attrno == -1 ?
1042                                  rangeTableEntry_used((Node *) parsetree, varno, 0) :
1043                                  attribute_used((Node *) parsetree,
1044                                                                 varno, oneLock->attrno, 0)))
1045                                 matching_locks = lappend(matching_locks, oneLock);
1046                 }
1047         }
1048
1049         return matching_locks;
1050 }
1051
1052
1053 /*
1054  * ApplyRetrieveRule - expand an ON SELECT rule
1055  */
1056 static Query *
1057 ApplyRetrieveRule(Query *parsetree,
1058                                   RewriteRule *rule,
1059                                   int rt_index,
1060                                   bool relation_level,
1061                                   Relation relation,
1062                                   List *activeRIRs)
1063 {
1064         Query      *rule_action;
1065         RangeTblEntry *rte,
1066                            *subrte;
1067         RowMarkClause *rc;
1068
1069         if (list_length(rule->actions) != 1)
1070                 elog(ERROR, "expected just one rule action");
1071         if (rule->qual != NULL)
1072                 elog(ERROR, "cannot handle qualified ON SELECT rule");
1073         if (!relation_level)
1074                 elog(ERROR, "cannot handle per-attribute ON SELECT rule");
1075
1076         /*
1077          * Make a modifiable copy of the view query, and acquire needed locks on
1078          * the relations it mentions.
1079          */
1080         rule_action = copyObject(linitial(rule->actions));
1081
1082         AcquireRewriteLocks(rule_action);
1083
1084         /*
1085          * Recursively expand any view references inside the view.
1086          */
1087         rule_action = fireRIRrules(rule_action, activeRIRs);
1088
1089         /*
1090          * VIEWs are really easy --- just plug the view query in as a subselect,
1091          * replacing the relation's original RTE.
1092          */
1093         rte = rt_fetch(rt_index, parsetree->rtable);
1094
1095         rte->rtekind = RTE_SUBQUERY;
1096         rte->relid = InvalidOid;
1097         rte->subquery = rule_action;
1098         rte->inh = false;                       /* must not be set for a subquery */
1099
1100         /*
1101          * We move the view's permission check data down to its rangetable. The
1102          * checks will actually be done against the *OLD* entry therein.
1103          */
1104         subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
1105         Assert(subrte->relid == relation->rd_id);
1106         subrte->requiredPerms = rte->requiredPerms;
1107         subrte->checkAsUser = rte->checkAsUser;
1108
1109         rte->requiredPerms = 0;         /* no permission check on subquery itself */
1110         rte->checkAsUser = InvalidOid;
1111
1112         /*
1113          * FOR UPDATE/SHARE of view?
1114          */
1115         if ((rc = get_rowmark(parsetree, rt_index)) != NULL)
1116         {
1117                 /*
1118                  * Remove the view from the list of rels that will actually be marked
1119                  * FOR UPDATE/SHARE by the executor.  It will still be access-checked
1120                  * for write access, though.
1121                  */
1122                 parsetree->rowMarks = list_delete_ptr(parsetree->rowMarks, rc);
1123
1124                 /*
1125                  * Set up the view's referenced tables as if FOR UPDATE/SHARE.
1126                  */
1127                 markQueryForLocking(rule_action, (Node *) rule_action->jointree,
1128                                                         rc->forUpdate, rc->noWait);
1129         }
1130
1131         return parsetree;
1132 }
1133
1134 /*
1135  * Recursively mark all relations used by a view as FOR UPDATE/SHARE.
1136  *
1137  * This may generate an invalid query, eg if some sub-query uses an
1138  * aggregate.  We leave it to the planner to detect that.
1139  *
1140  * NB: this must agree with the parser's transformLockingClause() routine.
1141  * However, unlike the parser we have to be careful not to mark a view's
1142  * OLD and NEW rels for updating.  The best way to handle that seems to be
1143  * to scan the jointree to determine which rels are used.
1144  */
1145 static void
1146 markQueryForLocking(Query *qry, Node *jtnode, bool forUpdate, bool noWait)
1147 {
1148         if (jtnode == NULL)
1149                 return;
1150         if (IsA(jtnode, RangeTblRef))
1151         {
1152                 int                     rti = ((RangeTblRef *) jtnode)->rtindex;
1153                 RangeTblEntry *rte = rt_fetch(rti, qry->rtable);
1154
1155                 if (rte->rtekind == RTE_RELATION)
1156                 {
1157                         applyLockingClause(qry, rti, forUpdate, noWait);
1158                         rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1159                 }
1160                 else if (rte->rtekind == RTE_SUBQUERY)
1161                 {
1162                         /* FOR UPDATE/SHARE of subquery is propagated to subquery's rels */
1163                         markQueryForLocking(rte->subquery, (Node *) rte->subquery->jointree,
1164                                                                 forUpdate, noWait);
1165                 }
1166         }
1167         else if (IsA(jtnode, FromExpr))
1168         {
1169                 FromExpr   *f = (FromExpr *) jtnode;
1170                 ListCell   *l;
1171
1172                 foreach(l, f->fromlist)
1173                         markQueryForLocking(qry, lfirst(l), forUpdate, noWait);
1174         }
1175         else if (IsA(jtnode, JoinExpr))
1176         {
1177                 JoinExpr   *j = (JoinExpr *) jtnode;
1178
1179                 markQueryForLocking(qry, j->larg, forUpdate, noWait);
1180                 markQueryForLocking(qry, j->rarg, forUpdate, noWait);
1181         }
1182         else
1183                 elog(ERROR, "unrecognized node type: %d",
1184                          (int) nodeTag(jtnode));
1185 }
1186
1187
1188 /*
1189  * fireRIRonSubLink -
1190  *      Apply fireRIRrules() to each SubLink (subselect in expression) found
1191  *      in the given tree.
1192  *
1193  * NOTE: although this has the form of a walker, we cheat and modify the
1194  * SubLink nodes in-place.      It is caller's responsibility to ensure that
1195  * no unwanted side-effects occur!
1196  *
1197  * This is unlike most of the other routines that recurse into subselects,
1198  * because we must take control at the SubLink node in order to replace
1199  * the SubLink's subselect link with the possibly-rewritten subquery.
1200  */
1201 static bool
1202 fireRIRonSubLink(Node *node, List *activeRIRs)
1203 {
1204         if (node == NULL)
1205                 return false;
1206         if (IsA(node, SubLink))
1207         {
1208                 SubLink    *sub = (SubLink *) node;
1209
1210                 /* Do what we came for */
1211                 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
1212                                                                                            activeRIRs);
1213                 /* Fall through to process lefthand args of SubLink */
1214         }
1215
1216         /*
1217          * Do NOT recurse into Query nodes, because fireRIRrules already processed
1218          * subselects of subselects for us.
1219          */
1220         return expression_tree_walker(node, fireRIRonSubLink,
1221                                                                   (void *) activeRIRs);
1222 }
1223
1224
1225 /*
1226  * fireRIRrules -
1227  *      Apply all RIR rules on each rangetable entry in a query
1228  */
1229 static Query *
1230 fireRIRrules(Query *parsetree, List *activeRIRs)
1231 {
1232         int                     rt_index;
1233
1234         /*
1235          * don't try to convert this into a foreach loop, because rtable list can
1236          * get changed each time through...
1237          */
1238         rt_index = 0;
1239         while (rt_index < list_length(parsetree->rtable))
1240         {
1241                 RangeTblEntry *rte;
1242                 Relation        rel;
1243                 List       *locks;
1244                 RuleLock   *rules;
1245                 RewriteRule *rule;
1246                 int                     i;
1247
1248                 ++rt_index;
1249
1250                 rte = rt_fetch(rt_index, parsetree->rtable);
1251
1252                 /*
1253                  * A subquery RTE can't have associated rules, so there's nothing to
1254                  * do to this level of the query, but we must recurse into the
1255                  * subquery to expand any rule references in it.
1256                  */
1257                 if (rte->rtekind == RTE_SUBQUERY)
1258                 {
1259                         rte->subquery = fireRIRrules(rte->subquery, activeRIRs);
1260                         continue;
1261                 }
1262
1263                 /*
1264                  * Joins and other non-relation RTEs can be ignored completely.
1265                  */
1266                 if (rte->rtekind != RTE_RELATION)
1267                         continue;
1268
1269                 /*
1270                  * If the table is not referenced in the query, then we ignore it.
1271                  * This prevents infinite expansion loop due to new rtable entries
1272                  * inserted by expansion of a rule. A table is referenced if it is
1273                  * part of the join set (a source table), or is referenced by any Var
1274                  * nodes, or is the result table.
1275                  */
1276                 if (rt_index != parsetree->resultRelation &&
1277                         !rangeTableEntry_used((Node *) parsetree, rt_index, 0))
1278                         continue;
1279
1280                 /*
1281                  * We can use NoLock here since either the parser or
1282                  * AcquireRewriteLocks should have locked the rel already.
1283                  */
1284                 rel = heap_open(rte->relid, NoLock);
1285
1286                 /*
1287                  * Collect the RIR rules that we must apply
1288                  */
1289                 rules = rel->rd_rules;
1290                 if (rules == NULL)
1291                 {
1292                         heap_close(rel, NoLock);
1293                         continue;
1294                 }
1295                 locks = NIL;
1296                 for (i = 0; i < rules->numLocks; i++)
1297                 {
1298                         rule = rules->rules[i];
1299                         if (rule->event != CMD_SELECT)
1300                                 continue;
1301
1302                         if (rule->attrno > 0)
1303                         {
1304                                 /* per-attr rule; do we need it? */
1305                                 if (!attribute_used((Node *) parsetree, rt_index,
1306                                                                         rule->attrno, 0))
1307                                         continue;
1308                         }
1309
1310                         locks = lappend(locks, rule);
1311                 }
1312
1313                 /*
1314                  * If we found any, apply them --- but first check for recursion!
1315                  */
1316                 if (locks != NIL)
1317                 {
1318                         ListCell   *l;
1319
1320                         if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
1321                                 ereport(ERROR,
1322                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1323                                                  errmsg("infinite recursion detected in rules for relation \"%s\"",
1324                                                                 RelationGetRelationName(rel))));
1325                         activeRIRs = lcons_oid(RelationGetRelid(rel), activeRIRs);
1326
1327                         foreach(l, locks)
1328                         {
1329                                 rule = lfirst(l);
1330
1331                                 parsetree = ApplyRetrieveRule(parsetree,
1332                                                                                           rule,
1333                                                                                           rt_index,
1334                                                                                           rule->attrno == -1,
1335                                                                                           rel,
1336                                                                                           activeRIRs);
1337                         }
1338
1339                         activeRIRs = list_delete_first(activeRIRs);
1340                 }
1341
1342                 heap_close(rel, NoLock);
1343         }
1344
1345         /*
1346          * Recurse into sublink subqueries, too.  But we already did the ones in
1347          * the rtable.
1348          */
1349         if (parsetree->hasSubLinks)
1350                 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
1351                                                   QTW_IGNORE_RT_SUBQUERIES);
1352
1353         return parsetree;
1354 }
1355
1356
1357 /*
1358  * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
1359  * qualification.  This is used to generate suitable "else clauses" for
1360  * conditional INSTEAD rules.  (Unfortunately we must use "x IS NOT TRUE",
1361  * not just "NOT x" which the planner is much smarter about, else we will
1362  * do the wrong thing when the qual evaluates to NULL.)
1363  *
1364  * The rule_qual may contain references to OLD or NEW.  OLD references are
1365  * replaced by references to the specified rt_index (the relation that the
1366  * rule applies to).  NEW references are only possible for INSERT and UPDATE
1367  * queries on the relation itself, and so they should be replaced by copies
1368  * of the related entries in the query's own targetlist.
1369  */
1370 static Query *
1371 CopyAndAddInvertedQual(Query *parsetree,
1372                                            Node *rule_qual,
1373                                            int rt_index,
1374                                            CmdType event)
1375 {
1376         /* Don't scribble on the passed qual (it's in the relcache!) */
1377         Node       *new_qual = (Node *) copyObject(rule_qual);
1378
1379         /*
1380          * In case there are subqueries in the qual, acquire necessary locks and
1381          * fix any deleted JOIN RTE entries.  (This is somewhat redundant with
1382          * rewriteRuleAction, but not entirely ... consider restructuring so that
1383          * we only need to process the qual this way once.)
1384          */
1385         (void) acquireLocksOnSubLinks(new_qual, NULL);
1386
1387         /* Fix references to OLD */
1388         ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
1389         /* Fix references to NEW */
1390         if (event == CMD_INSERT || event == CMD_UPDATE)
1391                 new_qual = ResolveNew(new_qual,
1392                                                           PRS2_NEW_VARNO,
1393                                                           0,
1394                                                           rt_fetch(rt_index, parsetree->rtable),
1395                                                           parsetree->targetList,
1396                                                           event,
1397                                                           rt_index);
1398         /* And attach the fixed qual */
1399         AddInvertedQual(parsetree, new_qual);
1400
1401         return parsetree;
1402 }
1403
1404
1405 /*
1406  *      fireRules -
1407  *         Iterate through rule locks applying rules.
1408  *
1409  * Input arguments:
1410  *      parsetree - original query
1411  *      rt_index - RT index of result relation in original query
1412  *      event - type of rule event
1413  *      locks - list of rules to fire
1414  * Output arguments:
1415  *      *instead_flag - set TRUE if any unqualified INSTEAD rule is found
1416  *                                      (must be initialized to FALSE)
1417  *      *returning_flag - set TRUE if we rewrite RETURNING clause in any rule
1418  *                                      (must be initialized to FALSE)
1419  *      *qual_product - filled with modified original query if any qualified
1420  *                                      INSTEAD rule is found (must be initialized to NULL)
1421  * Return value:
1422  *      list of rule actions adjusted for use with this query
1423  *
1424  * Qualified INSTEAD rules generate their action with the qualification
1425  * condition added.  They also generate a modified version of the original
1426  * query with the negated qualification added, so that it will run only for
1427  * rows that the qualified action doesn't act on.  (If there are multiple
1428  * qualified INSTEAD rules, we AND all the negated quals onto a single
1429  * modified original query.)  We won't execute the original, unmodified
1430  * query if we find either qualified or unqualified INSTEAD rules.      If
1431  * we find both, the modified original query is discarded too.
1432  */
1433 static List *
1434 fireRules(Query *parsetree,
1435                   int rt_index,
1436                   CmdType event,
1437                   List *locks,
1438                   bool *instead_flag,
1439                   bool *returning_flag,
1440                   Query **qual_product)
1441 {
1442         List       *results = NIL;
1443         ListCell   *l;
1444
1445         foreach(l, locks)
1446         {
1447                 RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
1448                 Node       *event_qual = rule_lock->qual;
1449                 List       *actions = rule_lock->actions;
1450                 QuerySource qsrc;
1451                 ListCell   *r;
1452
1453                 /* Determine correct QuerySource value for actions */
1454                 if (rule_lock->isInstead)
1455                 {
1456                         if (event_qual != NULL)
1457                                 qsrc = QSRC_QUAL_INSTEAD_RULE;
1458                         else
1459                         {
1460                                 qsrc = QSRC_INSTEAD_RULE;
1461                                 *instead_flag = true;   /* report unqualified INSTEAD */
1462                         }
1463                 }
1464                 else
1465                         qsrc = QSRC_NON_INSTEAD_RULE;
1466
1467                 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
1468                 {
1469                         /*
1470                          * If there are INSTEAD rules with qualifications, the original
1471                          * query is still performed. But all the negated rule
1472                          * qualifications of the INSTEAD rules are added so it does its
1473                          * actions only in cases where the rule quals of all INSTEAD rules
1474                          * are false. Think of it as the default action in a case. We save
1475                          * this in *qual_product so RewriteQuery() can add it to the query
1476                          * list after we mangled it up enough.
1477                          *
1478                          * If we have already found an unqualified INSTEAD rule, then
1479                          * *qual_product won't be used, so don't bother building it.
1480                          */
1481                         if (!*instead_flag)
1482                         {
1483                                 if (*qual_product == NULL)
1484                                         *qual_product = copyObject(parsetree);
1485                                 *qual_product = CopyAndAddInvertedQual(*qual_product,
1486                                                                                                            event_qual,
1487                                                                                                            rt_index,
1488                                                                                                            event);
1489                         }
1490                 }
1491
1492                 /* Now process the rule's actions and add them to the result list */
1493                 foreach(r, actions)
1494                 {
1495                         Query      *rule_action = lfirst(r);
1496
1497                         if (rule_action->commandType == CMD_NOTHING)
1498                                 continue;
1499
1500                         rule_action = rewriteRuleAction(parsetree, rule_action,
1501                                                                                         event_qual, rt_index, event,
1502                                                                                         returning_flag);
1503
1504                         rule_action->querySource = qsrc;
1505                         rule_action->canSetTag = false;         /* might change later */
1506
1507                         results = lappend(results, rule_action);
1508                 }
1509         }
1510
1511         return results;
1512 }
1513
1514
1515 /*
1516  * RewriteQuery -
1517  *        rewrites the query and apply the rules again on the queries rewritten
1518  *
1519  * rewrite_events is a list of open query-rewrite actions, so we can detect
1520  * infinite recursion.
1521  */
1522 static List *
1523 RewriteQuery(Query *parsetree, List *rewrite_events)
1524 {
1525         CmdType         event = parsetree->commandType;
1526         bool            instead = false;
1527         bool            returning = false;
1528         Query      *qual_product = NULL;
1529         List       *rewritten = NIL;
1530
1531         /*
1532          * If the statement is an update, insert or delete - fire rules on it.
1533          *
1534          * SELECT rules are handled later when we have all the queries that should
1535          * get executed.  Also, utilities aren't rewritten at all (do we still
1536          * need that check?)
1537          */
1538         if (event != CMD_SELECT && event != CMD_UTILITY)
1539         {
1540                 int                     result_relation;
1541                 RangeTblEntry *rt_entry;
1542                 Relation        rt_entry_relation;
1543                 List       *locks;
1544
1545                 result_relation = parsetree->resultRelation;
1546                 Assert(result_relation != 0);
1547                 rt_entry = rt_fetch(result_relation, parsetree->rtable);
1548                 Assert(rt_entry->rtekind == RTE_RELATION);
1549
1550                 /*
1551                  * We can use NoLock here since either the parser or
1552                  * AcquireRewriteLocks should have locked the rel already.
1553                  */
1554                 rt_entry_relation = heap_open(rt_entry->relid, NoLock);
1555
1556                 /*
1557                  * If it's an INSERT or UPDATE, rewrite the targetlist into standard
1558                  * form.  This will be needed by the planner anyway, and doing it now
1559                  * ensures that any references to NEW.field will behave sanely.
1560                  */
1561                 if (event == CMD_UPDATE)
1562                         rewriteTargetList(parsetree, rt_entry_relation, NULL);
1563                 else if (event == CMD_INSERT)
1564                 {
1565                         RangeTblEntry *values_rte = NULL;
1566
1567                         /*
1568                          * If it's an INSERT ... VALUES (...), (...), ... there will be a
1569                          * single RTE for the VALUES targetlists.
1570                          */
1571                         if (list_length(parsetree->jointree->fromlist) == 1)
1572                         {
1573                                 RangeTblRef *rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
1574
1575                                 if (IsA(rtr, RangeTblRef))
1576                                 {
1577                                         RangeTblEntry *rte = rt_fetch(rtr->rtindex,
1578                                                                                                   parsetree->rtable);
1579
1580                                         if (rte->rtekind == RTE_VALUES)
1581                                                 values_rte = rte;
1582                                 }
1583                         }
1584
1585                         if (values_rte)
1586                         {
1587                                 List       *attrnos;
1588
1589                                 /* Process the main targetlist ... */
1590                                 rewriteTargetList(parsetree, rt_entry_relation, &attrnos);
1591                                 /* ... and the VALUES expression lists */
1592                                 rewriteValuesRTE(values_rte, rt_entry_relation, attrnos);
1593                         }
1594                         else
1595                         {
1596                                 /* Process just the main targetlist */
1597                                 rewriteTargetList(parsetree, rt_entry_relation, NULL);
1598                         }
1599                 }
1600
1601                 /*
1602                  * Collect and apply the appropriate rules.
1603                  */
1604                 locks = matchLocks(event, rt_entry_relation->rd_rules,
1605                                                    result_relation, parsetree);
1606
1607                 if (locks != NIL)
1608                 {
1609                         List       *product_queries;
1610
1611                         product_queries = fireRules(parsetree,
1612                                                                                 result_relation,
1613                                                                                 event,
1614                                                                                 locks,
1615                                                                                 &instead,
1616                                                                                 &returning,
1617                                                                                 &qual_product);
1618
1619                         /*
1620                          * If we got any product queries, recursively rewrite them --- but
1621                          * first check for recursion!
1622                          */
1623                         if (product_queries != NIL)
1624                         {
1625                                 ListCell   *n;
1626                                 rewrite_event *rev;
1627
1628                                 foreach(n, rewrite_events)
1629                                 {
1630                                         rev = (rewrite_event *) lfirst(n);
1631                                         if (rev->relation == RelationGetRelid(rt_entry_relation) &&
1632                                                 rev->event == event)
1633                                                 ereport(ERROR,
1634                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1635                                                                  errmsg("infinite recursion detected in rules for relation \"%s\"",
1636                                                            RelationGetRelationName(rt_entry_relation))));
1637                                 }
1638
1639                                 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
1640                                 rev->relation = RelationGetRelid(rt_entry_relation);
1641                                 rev->event = event;
1642                                 rewrite_events = lcons(rev, rewrite_events);
1643
1644                                 foreach(n, product_queries)
1645                                 {
1646                                         Query      *pt = (Query *) lfirst(n);
1647                                         List       *newstuff;
1648
1649                                         newstuff = RewriteQuery(pt, rewrite_events);
1650                                         rewritten = list_concat(rewritten, newstuff);
1651                                 }
1652
1653                                 rewrite_events = list_delete_first(rewrite_events);
1654                         }
1655                 }
1656
1657                 /*
1658                  * If there is an INSTEAD, and the original query has a RETURNING, we
1659                  * have to have found a RETURNING in the rule(s), else fail. (Because
1660                  * DefineQueryRewrite only allows RETURNING in unconditional INSTEAD
1661                  * rules, there's no need to worry whether the substituted RETURNING
1662                  * will actually be executed --- it must be.)
1663                  */
1664                 if ((instead || qual_product != NULL) &&
1665                         parsetree->returningList &&
1666                         !returning)
1667                 {
1668                         switch (event)
1669                         {
1670                                 case CMD_INSERT:
1671                                         ereport(ERROR,
1672                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1673                                                  errmsg("cannot perform INSERT RETURNING on relation \"%s\"",
1674                                                                 RelationGetRelationName(rt_entry_relation)),
1675                                                          errhint("You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.")));
1676                                         break;
1677                                 case CMD_UPDATE:
1678                                         ereport(ERROR,
1679                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1680                                                  errmsg("cannot perform UPDATE RETURNING on relation \"%s\"",
1681                                                                 RelationGetRelationName(rt_entry_relation)),
1682                                                          errhint("You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.")));
1683                                         break;
1684                                 case CMD_DELETE:
1685                                         ereport(ERROR,
1686                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1687                                                  errmsg("cannot perform DELETE RETURNING on relation \"%s\"",
1688                                                                 RelationGetRelationName(rt_entry_relation)),
1689                                                          errhint("You need an unconditional ON DELETE DO INSTEAD rule with a RETURNING clause.")));
1690                                         break;
1691                                 default:
1692                                         elog(ERROR, "unrecognized commandType: %d",
1693                                                  (int) event);
1694                                         break;
1695                         }
1696                 }
1697
1698                 heap_close(rt_entry_relation, NoLock);
1699         }
1700
1701         /*
1702          * For INSERTs, the original query is done first; for UPDATE/DELETE, it is
1703          * done last.  This is needed because update and delete rule actions might
1704          * not do anything if they are invoked after the update or delete is
1705          * performed. The command counter increment between the query executions
1706          * makes the deleted (and maybe the updated) tuples disappear so the scans
1707          * for them in the rule actions cannot find them.
1708          *
1709          * If we found any unqualified INSTEAD, the original query is not done at
1710          * all, in any form.  Otherwise, we add the modified form if qualified
1711          * INSTEADs were found, else the unmodified form.
1712          */
1713         if (!instead)
1714         {
1715                 if (parsetree->commandType == CMD_INSERT)
1716                 {
1717                         if (qual_product != NULL)
1718                                 rewritten = lcons(qual_product, rewritten);
1719                         else
1720                                 rewritten = lcons(parsetree, rewritten);
1721                 }
1722                 else
1723                 {
1724                         if (qual_product != NULL)
1725                                 rewritten = lappend(rewritten, qual_product);
1726                         else
1727                                 rewritten = lappend(rewritten, parsetree);
1728                 }
1729         }
1730
1731         return rewritten;
1732 }
1733
1734
1735 /*
1736  * QueryRewrite -
1737  *        Primary entry point to the query rewriter.
1738  *        Rewrite one query via query rewrite system, possibly returning 0
1739  *        or many queries.
1740  *
1741  * NOTE: the parsetree must either have come straight from the parser,
1742  * or have been scanned by AcquireRewriteLocks to acquire suitable locks.
1743  */
1744 List *
1745 QueryRewrite(Query *parsetree)
1746 {
1747         List       *querylist;
1748         List       *results = NIL;
1749         ListCell   *l;
1750         CmdType         origCmdType;
1751         bool            foundOriginalQuery;
1752         Query      *lastInstead;
1753
1754         /*
1755          * Step 1
1756          *
1757          * Apply all non-SELECT rules possibly getting 0 or many queries
1758          */
1759         querylist = RewriteQuery(parsetree, NIL);
1760
1761         /*
1762          * Step 2
1763          *
1764          * Apply all the RIR rules on each query
1765          */
1766         foreach(l, querylist)
1767         {
1768                 Query      *query = (Query *) lfirst(l);
1769
1770                 query = fireRIRrules(query, NIL);
1771
1772                 /*
1773                  * If the query target was rewritten as a view, complain.
1774                  */
1775                 if (query->resultRelation)
1776                 {
1777                         RangeTblEntry *rte = rt_fetch(query->resultRelation,
1778                                                                                   query->rtable);
1779
1780                         if (rte->rtekind == RTE_SUBQUERY)
1781                         {
1782                                 switch (query->commandType)
1783                                 {
1784                                         case CMD_INSERT:
1785                                                 ereport(ERROR,
1786                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1787                                                                  errmsg("cannot insert into a view"),
1788                                                                  errhint("You need an unconditional ON INSERT DO INSTEAD rule.")));
1789                                                 break;
1790                                         case CMD_UPDATE:
1791                                                 ereport(ERROR,
1792                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1793                                                                  errmsg("cannot update a view"),
1794                                                                  errhint("You need an unconditional ON UPDATE DO INSTEAD rule.")));
1795                                                 break;
1796                                         case CMD_DELETE:
1797                                                 ereport(ERROR,
1798                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1799                                                                  errmsg("cannot delete from a view"),
1800                                                                  errhint("You need an unconditional ON DELETE DO INSTEAD rule.")));
1801                                                 break;
1802                                         default:
1803                                                 elog(ERROR, "unrecognized commandType: %d",
1804                                                          (int) query->commandType);
1805                                                 break;
1806                                 }
1807                         }
1808                 }
1809
1810                 results = lappend(results, query);
1811         }
1812
1813         /*
1814          * Step 3
1815          *
1816          * Determine which, if any, of the resulting queries is supposed to set
1817          * the command-result tag; and update the canSetTag fields accordingly.
1818          *
1819          * If the original query is still in the list, it sets the command tag.
1820          * Otherwise, the last INSTEAD query of the same kind as the original is
1821          * allowed to set the tag.      (Note these rules can leave us with no query
1822          * setting the tag.  The tcop code has to cope with this by setting up a
1823          * default tag based on the original un-rewritten query.)
1824          *
1825          * The Asserts verify that at most one query in the result list is marked
1826          * canSetTag.  If we aren't checking asserts, we can fall out of the loop
1827          * as soon as we find the original query.
1828          */
1829         origCmdType = parsetree->commandType;
1830         foundOriginalQuery = false;
1831         lastInstead = NULL;
1832
1833         foreach(l, results)
1834         {
1835                 Query      *query = (Query *) lfirst(l);
1836
1837                 if (query->querySource == QSRC_ORIGINAL)
1838                 {
1839                         Assert(query->canSetTag);
1840                         Assert(!foundOriginalQuery);
1841                         foundOriginalQuery = true;
1842 #ifndef USE_ASSERT_CHECKING
1843                         break;
1844 #endif
1845                 }
1846                 else
1847                 {
1848                         Assert(!query->canSetTag);
1849                         if (query->commandType == origCmdType &&
1850                                 (query->querySource == QSRC_INSTEAD_RULE ||
1851                                  query->querySource == QSRC_QUAL_INSTEAD_RULE))
1852                                 lastInstead = query;
1853                 }
1854         }
1855
1856         if (!foundOriginalQuery && lastInstead != NULL)
1857                 lastInstead->canSetTag = true;
1858
1859         return results;
1860 }