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