1 /*-------------------------------------------------------------------------
4 * Primary module of query rewriter.
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.126 2003/08/04 00:43:22 momjian Exp $
12 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/pg_operator.h"
18 #include "catalog/pg_type.h"
19 #include "miscadmin.h"
20 #include "nodes/makefuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/prep.h"
23 #include "optimizer/var.h"
24 #include "parser/analyze.h"
25 #include "parser/parse_coerce.h"
26 #include "parser/parse_expr.h"
27 #include "parser/parse_oper.h"
28 #include "parser/parse_type.h"
29 #include "parser/parsetree.h"
30 #include "rewrite/rewriteHandler.h"
31 #include "rewrite/rewriteManip.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
36 /* We use a list of these to detect recursion in RewriteQuery */
37 typedef struct rewrite_event
39 Oid relation; /* OID of relation having rules */
40 CmdType event; /* type of rule being fired */
43 static Query *rewriteRuleAction(Query *parsetree,
48 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
49 static void rewriteTargetList(Query *parsetree, Relation target_relation);
50 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
51 TargetEntry *prior_tle);
52 static void markQueryForUpdate(Query *qry, bool skipOldNew);
53 static List *matchLocks(CmdType event, RuleLock *rulelocks,
54 int varno, Query *parsetree);
55 static Query *fireRIRrules(Query *parsetree, List *activeRIRs);
60 * Rewrite the rule action with appropriate qualifiers (taken from
61 * the triggering query).
64 rewriteRuleAction(Query *parsetree,
75 Query **sub_action_ptr;
79 * Make modifiable copies of rule action and qual (what we're passed
80 * are the stored versions in the relcache; don't touch 'em!).
82 rule_action = (Query *) copyObject(rule_action);
83 rule_qual = (Node *) copyObject(rule_qual);
85 current_varno = rt_index;
86 rt_length = length(parsetree->rtable);
87 new_varno = PRS2_NEW_VARNO + rt_length;
90 * Adjust rule action and qual to offset its varnos, so that we can
91 * merge its rtable with the main parsetree's rtable.
93 * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
94 * will be in the SELECT part, and we have to modify that rather than
95 * the top-level INSERT (kluge!).
97 sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
99 OffsetVarNodes((Node *) sub_action, rt_length, 0);
100 OffsetVarNodes(rule_qual, rt_length, 0);
101 /* but references to *OLD* should point at original rt_index */
102 ChangeVarNodes((Node *) sub_action,
103 PRS2_OLD_VARNO + rt_length, rt_index, 0);
104 ChangeVarNodes(rule_qual,
105 PRS2_OLD_VARNO + rt_length, rt_index, 0);
108 * Generate expanded rtable consisting of main parsetree's rtable plus
109 * rule action's rtable; this becomes the complete rtable for the rule
110 * action. Some of the entries may be unused after we finish
111 * rewriting, but if we tried to remove them we'd have a much harder
112 * job to adjust RT indexes in the query's Vars. It's OK to have
113 * unused RT entries, since planner will ignore them.
115 * NOTE: because planner will destructively alter rtable, we must ensure
116 * that rule action's rtable is separate and shares no substructure
117 * with the main rtable. Hence do a deep copy here.
119 * Also, we must disable write-access checking in all the RT entries
120 * copied from the main query. This is safe since in fact the rule
121 * action won't write on them, and it's necessary because the rule
122 * action may have a different commandType than the main query,
123 * causing ExecCheckRTEPerms() to make an inappropriate check. The
124 * read-access checks can be left enabled, although they're probably
127 main_rtable = (List *) copyObject(parsetree->rtable);
129 foreach(rt, main_rtable)
131 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
133 rte->checkForWrite = false;
136 sub_action->rtable = nconc(main_rtable, sub_action->rtable);
139 * Each rule action's jointree should be the main parsetree's jointree
140 * plus that rule's jointree, but usually *without* the original
141 * rtindex that we're replacing (if present, which it won't be for
142 * INSERT). Note that if the rule action refers to OLD, its jointree
143 * will add a reference to rt_index. If the rule action doesn't refer
144 * to OLD, but either the rule_qual or the user query quals do, then
145 * we need to keep the original rtindex in the jointree to provide
146 * data for the quals. We don't want the original rtindex to be
147 * joined twice, however, so avoid keeping it if the rule action
150 * As above, the action's jointree must not share substructure with the
153 if (sub_action->commandType != CMD_UTILITY)
158 Assert(sub_action->jointree != NULL);
159 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
161 (rangeTableEntry_used(rule_qual, rt_index, 0) ||
162 rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
163 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
164 if (newjointree != NIL)
167 * If sub_action is a setop, manipulating its jointree will do
168 * no good at all, because the jointree is dummy. (Perhaps
169 * someday we could push the joining and quals down to the
170 * member statements of the setop?)
172 if (sub_action->setOperations != NULL)
174 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
175 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
177 sub_action->jointree->fromlist =
178 nconc(newjointree, sub_action->jointree->fromlist);
183 * We copy the qualifications of the parsetree to the action and vice
184 * versa. So force hasSubLinks if one of them has it. If this is not
185 * right, the flag will get cleared later, but we mustn't risk having
186 * it not set when it needs to be. (XXX this should probably be
187 * handled by AddQual and friends, not here...)
189 if (parsetree->hasSubLinks)
190 sub_action->hasSubLinks = TRUE;
191 else if (sub_action->hasSubLinks)
192 parsetree->hasSubLinks = TRUE;
195 * Event Qualification forces copying of parsetree and splitting into
196 * two queries one w/rule_qual, one w/NOT rule_qual. Also add user
197 * query qual onto rule action
199 AddQual(sub_action, rule_qual);
201 AddQual(sub_action, parsetree->jointree->quals);
204 * Rewrite new.attribute w/ right hand side of target-list entry for
205 * appropriate field name in insert/update.
207 * KLUGE ALERT: since ResolveNew returns a mutated copy, we can't just
208 * apply it to sub_action; we have to remember to update the sublink
209 * inside rule_action, too.
211 if (event == CMD_INSERT || event == CMD_UPDATE)
213 sub_action = (Query *) ResolveNew((Node *) sub_action,
216 parsetree->targetList,
220 *sub_action_ptr = sub_action;
222 rule_action = sub_action;
229 * Copy the query's jointree list, and optionally attempt to remove any
230 * occurrence of the given rt_index as a top-level join item (we do not look
231 * for it within join items; this is OK because we are only expecting to find
232 * it as an UPDATE or DELETE target relation, which will be at the top level
233 * of the join). Returns modified jointree list --- this is a separate copy
234 * sharing no nodes with the original.
237 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
239 List *newjointree = copyObject(parsetree->jointree->fromlist);
244 foreach(jjt, newjointree)
246 RangeTblRef *rtr = lfirst(jjt);
248 if (IsA(rtr, RangeTblRef) &&
249 rtr->rtindex == rt_index)
251 newjointree = lremove(rtr, newjointree);
252 /* foreach is safe because we exit loop after lremove... */
262 * rewriteTargetList - rewrite INSERT/UPDATE targetlist into standard form
264 * This has the following responsibilities:
266 * 1. For an INSERT, add tlist entries to compute default values for any
267 * attributes that have defaults and are not assigned to in the given tlist.
268 * (We do not insert anything for default-less attributes, however. The
269 * planner will later insert NULLs for them, but there's no reason to slow
270 * down rewriter processing with extra tlist nodes.) Also, for both INSERT
271 * and UPDATE, replace explicit DEFAULT specifications with column default
274 * 2. Merge multiple entries for the same target attribute, or declare error
275 * if we can't. Presently, multiple entries are only allowed for UPDATE of
276 * an array field, for example "UPDATE table SET foo[2] = 42, foo[4] = 43".
277 * We can merge such operations into a single assignment op. Essentially,
278 * the expression we want to produce in this case is like
279 * foo = array_set(array_set(foo, 2, 42), 4, 43)
281 * 3. Sort the tlist into standard order: non-junk fields in order by resno,
282 * then junk fields (these in no particular order).
284 * We must do items 1 and 2 before firing rewrite rules, else rewritten
285 * references to NEW.foo will produce wrong or incomplete results. Item 3
286 * is not needed for rewriting, but will be needed by the planner, and we
287 * can do it essentially for free while handling items 1 and 2.
290 rewriteTargetList(Query *parsetree, Relation target_relation)
292 CmdType commandType = parsetree->commandType;
293 List *tlist = parsetree->targetList;
294 List *new_tlist = NIL;
300 * Scan the tuple description in the relation's relcache entry to make
301 * sure we have all the user attributes in the right order.
303 numattrs = RelationGetNumberOfAttributes(target_relation);
305 for (attrno = 1; attrno <= numattrs; attrno++)
307 Form_pg_attribute att_tup = target_relation->rd_att->attrs[attrno - 1];
308 TargetEntry *new_tle = NULL;
310 /* We can ignore deleted attributes */
311 if (att_tup->attisdropped)
315 * Look for targetlist entries matching this attr. We match by
316 * resno, but the resname should match too.
318 * Junk attributes are not candidates to be matched.
322 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
323 Resdom *resdom = old_tle->resdom;
325 if (!resdom->resjunk && resdom->resno == attrno)
327 Assert(strcmp(resdom->resname,
328 NameStr(att_tup->attname)) == 0);
329 new_tle = process_matched_tle(old_tle, new_tle);
330 /* keep scanning to detect multiple assignments to attr */
335 * Handle the two cases where we need to insert a default
336 * expression: it's an INSERT and there's no tlist entry for the
337 * column, or the tlist entry is a DEFAULT placeholder node.
339 if ((new_tle == NULL && commandType == CMD_INSERT) ||
340 (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)))
344 new_expr = build_column_default(target_relation, attrno);
347 * If there is no default (ie, default is effectively NULL),
348 * we can omit the tlist entry in the INSERT case, since the
349 * planner can insert a NULL for itself, and there's no point
350 * in spending any more rewriter cycles on the entry. But in
351 * the UPDATE case we've got to explicitly set the column to
356 if (commandType == CMD_INSERT)
360 new_expr = (Node *) makeConst(att_tup->atttypid,
365 /* this is to catch a NOT NULL domain constraint */
366 new_expr = coerce_to_domain(new_expr,
369 COERCE_IMPLICIT_CAST);
374 new_tle = makeTargetEntry(makeResdom(attrno,
377 pstrdup(NameStr(att_tup->attname)),
383 new_tlist = lappend(new_tlist, new_tle);
387 * Copy all resjunk tlist entries to the end of the new tlist, and
388 * assign them resnos above the last real resno.
390 * Typical junk entries include ORDER BY or GROUP BY expressions (are
391 * these actually possible in an INSERT or UPDATE?), system attribute
396 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
397 Resdom *resdom = old_tle->resdom;
401 /* Get the resno right, but don't copy unnecessarily */
402 if (resdom->resno != attrno)
404 resdom = (Resdom *) copyObject((Node *) resdom);
405 resdom->resno = attrno;
406 old_tle = makeTargetEntry(resdom, old_tle->expr);
408 new_tlist = lappend(new_tlist, old_tle);
413 /* Let's just make sure we processed all the non-junk items */
414 if (resdom->resno < 1 || resdom->resno > numattrs)
415 elog(ERROR, "bogus resno %d in targetlist", resdom->resno);
419 parsetree->targetList = new_tlist;
424 * Convert a matched TLE from the original tlist into a correct new TLE.
426 * This routine detects and handles multiple assignments to the same target
430 process_matched_tle(TargetEntry *src_tle,
431 TargetEntry *prior_tle)
433 Resdom *resdom = src_tle->resdom;
437 if (prior_tle == NULL)
440 * Normal case where this is the first assignment to the
447 * Multiple assignments to same attribute. Allow only if all are
448 * array-assign operators with same bottom array object.
450 if (src_tle->expr == NULL || !IsA(src_tle->expr, ArrayRef) ||
451 ((ArrayRef *) src_tle->expr)->refassgnexpr == NULL ||
452 prior_tle->expr == NULL || !IsA(prior_tle->expr, ArrayRef) ||
453 ((ArrayRef *) prior_tle->expr)->refassgnexpr == NULL ||
454 ((ArrayRef *) src_tle->expr)->refrestype !=
455 ((ArrayRef *) prior_tle->expr)->refrestype)
457 (errcode(ERRCODE_SYNTAX_ERROR),
458 errmsg("multiple assignments to same attribute \"%s\"",
462 * Prior TLE could be a nest of ArrayRefs if we do this more than
465 priorbottom = (Node *) ((ArrayRef *) prior_tle->expr)->refexpr;
466 while (priorbottom != NULL && IsA(priorbottom, ArrayRef) &&
467 ((ArrayRef *) priorbottom)->refassgnexpr != NULL)
468 priorbottom = (Node *) ((ArrayRef *) priorbottom)->refexpr;
469 if (!equal(priorbottom, ((ArrayRef *) src_tle->expr)->refexpr))
471 (errcode(ERRCODE_SYNTAX_ERROR),
472 errmsg("multiple assignments to same attribute \"%s\"",
476 * Looks OK to nest 'em.
478 newexpr = makeNode(ArrayRef);
479 memcpy(newexpr, src_tle->expr, sizeof(ArrayRef));
480 newexpr->refexpr = prior_tle->expr;
482 return makeTargetEntry(resdom, (Expr *) newexpr);
487 * Make an expression tree for the default value for a column.
489 * If there is no default, return a NULL instead.
492 build_column_default(Relation rel, int attrno)
494 TupleDesc rd_att = rel->rd_att;
495 Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
496 Oid atttype = att_tup->atttypid;
497 int32 atttypmod = att_tup->atttypmod;
502 * Scan to see if relation has a default for this column.
504 if (rd_att->constr && rd_att->constr->num_defval > 0)
506 AttrDefault *defval = rd_att->constr->defval;
507 int ndef = rd_att->constr->num_defval;
511 if (attrno == defval[ndef].adnum)
514 * Found it, convert string representation to node tree.
516 expr = stringToNode(defval[ndef].adbin);
525 * No per-column default, so look for a default for the type
528 if (att_tup->attisset)
531 * Set attributes are represented as OIDs no matter what the
532 * set element type is, and the element type's default is
537 expr = get_typdefault(atttype);
541 return NULL; /* No default anywhere */
544 * Make sure the value is coerced to the target column type; this will
545 * generally be true already, but there seem to be some corner cases
546 * involving domain defaults where it might not be true. This should
547 * match the parser's processing of non-defaulted expressions --- see
548 * updateTargetListEntry().
550 exprtype = exprType(expr);
552 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
556 COERCE_IMPLICIT_CAST);
559 (errcode(ERRCODE_DATATYPE_MISMATCH),
560 errmsg("column \"%s\" is of type %s"
561 " but default expression is of type %s",
562 NameStr(att_tup->attname),
563 format_type_be(atttype),
564 format_type_be(exprtype)),
565 errhint("You will need to rewrite or cast the expression.")));
573 * match the list of locks and returns the matching rules
576 matchLocks(CmdType event,
581 List *matching_locks = NIL;
585 if (rulelocks == NULL)
588 if (parsetree->commandType != CMD_SELECT)
590 if (parsetree->resultRelation != varno)
594 nlocks = rulelocks->numLocks;
596 for (i = 0; i < nlocks; i++)
598 RewriteRule *oneLock = rulelocks->rules[i];
600 if (oneLock->event == event)
602 if (parsetree->commandType != CMD_SELECT ||
603 (oneLock->attrno == -1 ?
604 rangeTableEntry_used((Node *) parsetree, varno, 0) :
605 attribute_used((Node *) parsetree,
606 varno, oneLock->attrno, 0)))
607 matching_locks = lappend(matching_locks, oneLock);
611 return matching_locks;
616 ApplyRetrieveRule(Query *parsetree,
628 if (length(rule->actions) != 1)
629 elog(ERROR, "expected just one rule action");
630 if (rule->qual != NULL)
631 elog(ERROR, "cannot handle qualified ON SELECT rule");
633 elog(ERROR, "cannot handle per-attribute ON SELECT rule");
636 * Make a modifiable copy of the view query, and recursively expand
637 * any view references inside it.
639 rule_action = copyObject(lfirst(rule->actions));
641 rule_action = fireRIRrules(rule_action, activeRIRs);
644 * VIEWs are really easy --- just plug the view query in as a
645 * subselect, replacing the relation's original RTE.
647 rte = rt_fetch(rt_index, parsetree->rtable);
649 rte->rtekind = RTE_SUBQUERY;
650 rte->relid = InvalidOid;
651 rte->subquery = rule_action;
652 rte->inh = false; /* must not be set for a subquery */
655 * We move the view's permission check data down to its rangetable.
656 * The checks will actually be done against the *OLD* entry therein.
658 subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
659 Assert(subrte->relid == relation->rd_id);
660 subrte->checkForRead = rte->checkForRead;
661 subrte->checkForWrite = rte->checkForWrite;
662 subrte->checkAsUser = rte->checkAsUser;
664 rte->checkForRead = false; /* no permission check on subquery itself */
665 rte->checkForWrite = false;
666 rte->checkAsUser = InvalidOid;
669 * FOR UPDATE of view?
671 if (intMember(rt_index, parsetree->rowMarks))
674 * Remove the view from the list of rels that will actually be
675 * marked FOR UPDATE by the executor. It will still be access-
676 * checked for write access, though.
678 parsetree->rowMarks = lremovei(rt_index, parsetree->rowMarks);
681 * Set up the view's referenced tables as if FOR UPDATE.
683 markQueryForUpdate(rule_action, true);
690 * Recursively mark all relations used by a view as FOR UPDATE.
692 * This may generate an invalid query, eg if some sub-query uses an
693 * aggregate. We leave it to the planner to detect that.
695 * NB: this must agree with the parser's transformForUpdate() routine.
698 markQueryForUpdate(Query *qry, bool skipOldNew)
703 foreach(l, qry->rtable)
705 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
709 /* Ignore OLD and NEW entries if we are at top level of view */
711 (rti == PRS2_OLD_VARNO || rti == PRS2_NEW_VARNO))
714 if (rte->rtekind == RTE_RELATION)
716 if (!intMember(rti, qry->rowMarks))
717 qry->rowMarks = lappendi(qry->rowMarks, rti);
718 rte->checkForWrite = true;
720 else if (rte->rtekind == RTE_SUBQUERY)
722 /* FOR UPDATE of subquery is propagated to subquery's rels */
723 markQueryForUpdate(rte->subquery, false);
731 * Apply fireRIRrules() to each SubLink (subselect in expression) found
734 * NOTE: although this has the form of a walker, we cheat and modify the
735 * SubLink nodes in-place. It is caller's responsibility to ensure that
736 * no unwanted side-effects occur!
738 * This is unlike most of the other routines that recurse into subselects,
739 * because we must take control at the SubLink node in order to replace
740 * the SubLink's subselect link with the possibly-rewritten subquery.
743 fireRIRonSubLink(Node *node, List *activeRIRs)
747 if (IsA(node, SubLink))
749 SubLink *sub = (SubLink *) node;
751 /* Do what we came for */
752 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
754 /* Fall through to process lefthand args of SubLink */
758 * Do NOT recurse into Query nodes, because fireRIRrules already
759 * processed subselects of subselects for us.
761 return expression_tree_walker(node, fireRIRonSubLink,
762 (void *) activeRIRs);
768 * Apply all RIR rules on each rangetable entry in a query
771 fireRIRrules(Query *parsetree, List *activeRIRs)
776 * don't try to convert this into a foreach loop, because rtable list
777 * can get changed each time through...
780 while (rt_index < length(parsetree->rtable))
793 rte = rt_fetch(rt_index, parsetree->rtable);
796 * A subquery RTE can't have associated rules, so there's nothing
797 * to do to this level of the query, but we must recurse into the
798 * subquery to expand any rule references in it.
800 if (rte->rtekind == RTE_SUBQUERY)
802 rte->subquery = fireRIRrules(rte->subquery, activeRIRs);
807 * Joins and other non-relation RTEs can be ignored completely.
809 if (rte->rtekind != RTE_RELATION)
813 * If the table is not referenced in the query, then we ignore it.
814 * This prevents infinite expansion loop due to new rtable entries
815 * inserted by expansion of a rule. A table is referenced if it is
816 * part of the join set (a source table), or is referenced by any
817 * Var nodes, or is the result table.
819 relIsUsed = rangeTableEntry_used((Node *) parsetree, rt_index, 0);
821 if (!relIsUsed && rt_index != parsetree->resultRelation)
825 * This may well be the first access to the relation during the
826 * current statement (it will be, if this Query was extracted from
827 * a rule or somehow got here other than via the parser).
828 * Therefore, grab the appropriate lock type for the relation, and
829 * do not release it until end of transaction. This protects the
830 * rewriter and planner against schema changes mid-query.
832 * If the relation is the query's result relation, then
833 * RewriteQuery() already got the right lock on it, so we need no
834 * additional lock. Otherwise, check to see if the relation is
835 * accessed FOR UPDATE or not.
837 if (rt_index == parsetree->resultRelation)
839 else if (intMember(rt_index, parsetree->rowMarks))
840 lockmode = RowShareLock;
842 lockmode = AccessShareLock;
844 rel = heap_open(rte->relid, lockmode);
847 * Collect the RIR rules that we must apply
849 rules = rel->rd_rules;
852 heap_close(rel, NoLock);
856 for (i = 0; i < rules->numLocks; i++)
858 rule = rules->rules[i];
859 if (rule->event != CMD_SELECT)
862 if (rule->attrno > 0)
864 /* per-attr rule; do we need it? */
865 if (!attribute_used((Node *) parsetree, rt_index,
870 locks = lappend(locks, rule);
874 * If we found any, apply them --- but first check for recursion!
881 if (oidMember(RelationGetRelid(rel), activeRIRs))
883 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
884 errmsg("infinite recursion detected in rules for relation \"%s\"",
885 RelationGetRelationName(rel))));
886 newActiveRIRs = lconso(RelationGetRelid(rel), activeRIRs);
892 parsetree = ApplyRetrieveRule(parsetree,
902 heap_close(rel, NoLock);
906 * Recurse into sublink subqueries, too. But we already did the ones
909 if (parsetree->hasSubLinks)
910 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
911 QTW_IGNORE_RT_SUBQUERIES);
914 * If the query was marked having aggregates, check if this is still
915 * true after rewriting. Ditto for sublinks. Note there should be no
916 * aggs in the qual at this point. (Does this code still do anything
917 * useful? The view-becomes-subselect-in-FROM approach doesn't look
918 * like it could remove aggs or sublinks...)
920 if (parsetree->hasAggs)
922 parsetree->hasAggs = checkExprHasAggs((Node *) parsetree);
923 if (parsetree->hasAggs)
924 if (checkExprHasAggs((Node *) parsetree->jointree))
925 elog(ERROR, "failed to remove aggregates from qual");
927 if (parsetree->hasSubLinks)
928 parsetree->hasSubLinks = checkExprHasSubLink((Node *) parsetree);
935 * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
936 * qualification. This is used to generate suitable "else clauses" for
937 * conditional INSTEAD rules. (Unfortunately we must use "x IS NOT TRUE",
938 * not just "NOT x" which the planner is much smarter about, else we will
939 * do the wrong thing when the qual evaluates to NULL.)
941 * The rule_qual may contain references to OLD or NEW. OLD references are
942 * replaced by references to the specified rt_index (the relation that the
943 * rule applies to). NEW references are only possible for INSERT and UPDATE
944 * queries on the relation itself, and so they should be replaced by copies
945 * of the related entries in the query's own targetlist.
948 CopyAndAddInvertedQual(Query *parsetree,
953 Query *new_tree = (Query *) copyObject(parsetree);
954 Node *new_qual = (Node *) copyObject(rule_qual);
956 /* Fix references to OLD */
957 ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
958 /* Fix references to NEW */
959 if (event == CMD_INSERT || event == CMD_UPDATE)
960 new_qual = ResolveNew(new_qual,
963 parsetree->targetList,
966 /* And attach the fixed qual */
967 AddInvertedQual(new_tree, new_qual);
975 * Iterate through rule locks applying rules.
978 * parsetree - original query
979 * rt_index - RT index of result relation in original query
980 * event - type of rule event
981 * locks - list of rules to fire
983 * *instead_flag - set TRUE if any unqualified INSTEAD rule is found
984 * (must be initialized to FALSE)
985 * *qual_product - filled with modified original query if any qualified
986 * INSTEAD rule is found (must be initialized to NULL)
988 * list of rule actions adjusted for use with this query
990 * Qualified INSTEAD rules generate their action with the qualification
991 * condition added. They also generate a modified version of the original
992 * query with the negated qualification added, so that it will run only for
993 * rows that the qualified action doesn't act on. (If there are multiple
994 * qualified INSTEAD rules, we AND all the negated quals onto a single
995 * modified original query.) We won't execute the original, unmodified
996 * query if we find either qualified or unqualified INSTEAD rules. If
997 * we find both, the modified original query is discarded too.
1000 fireRules(Query *parsetree,
1005 Query **qual_product)
1007 List *results = NIL;
1012 RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
1013 Node *event_qual = rule_lock->qual;
1014 List *actions = rule_lock->actions;
1018 /* Determine correct QuerySource value for actions */
1019 if (rule_lock->isInstead)
1021 if (event_qual != NULL)
1022 qsrc = QSRC_QUAL_INSTEAD_RULE;
1025 qsrc = QSRC_INSTEAD_RULE;
1026 *instead_flag = true; /* report unqualified INSTEAD */
1030 qsrc = QSRC_NON_INSTEAD_RULE;
1032 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
1035 * If there are INSTEAD rules with qualifications, the
1036 * original query is still performed. But all the negated rule
1037 * qualifications of the INSTEAD rules are added so it does
1038 * its actions only in cases where the rule quals of all
1039 * INSTEAD rules are false. Think of it as the default action
1040 * in a case. We save this in *qual_product so RewriteQuery()
1041 * can add it to the query list after we mangled it up enough.
1043 * If we have already found an unqualified INSTEAD rule, then
1044 * *qual_product won't be used, so don't bother building it.
1048 if (*qual_product == NULL)
1049 *qual_product = parsetree;
1050 *qual_product = CopyAndAddInvertedQual(*qual_product,
1057 /* Now process the rule's actions and add them to the result list */
1060 Query *rule_action = lfirst(r);
1062 if (rule_action->commandType == CMD_NOTHING)
1065 rule_action = rewriteRuleAction(parsetree, rule_action,
1066 event_qual, rt_index, event);
1068 rule_action->querySource = qsrc;
1069 rule_action->canSetTag = false; /* might change later */
1071 results = lappend(results, rule_action);
1081 * rewrites the query and apply the rules again on the queries rewritten
1083 * rewrite_events is a list of open query-rewrite actions, so we can detect
1084 * infinite recursion.
1087 RewriteQuery(Query *parsetree, List *rewrite_events)
1089 CmdType event = parsetree->commandType;
1090 bool instead = false;
1091 Query *qual_product = NULL;
1092 List *rewritten = NIL;
1095 * If the statement is an update, insert or delete - fire rules on it.
1097 * SELECT rules are handled later when we have all the queries that
1098 * should get executed. Also, utilities aren't rewritten at all (do
1099 * we still need that check?)
1101 if (event != CMD_SELECT && event != CMD_UTILITY)
1103 int result_relation;
1104 RangeTblEntry *rt_entry;
1105 Relation rt_entry_relation;
1108 result_relation = parsetree->resultRelation;
1109 Assert(result_relation != 0);
1110 rt_entry = rt_fetch(result_relation, parsetree->rtable);
1111 Assert(rt_entry->rtekind == RTE_RELATION);
1114 * This may well be the first access to the result relation during
1115 * the current statement (it will be, if this Query was extracted
1116 * from a rule or somehow got here other than via the parser).
1117 * Therefore, grab the appropriate lock type for a result
1118 * relation, and do not release it until end of transaction. This
1119 * protects the rewriter and planner against schema changes
1122 rt_entry_relation = heap_open(rt_entry->relid, RowExclusiveLock);
1125 * If it's an INSERT or UPDATE, rewrite the targetlist into
1126 * standard form. This will be needed by the planner anyway, and
1127 * doing it now ensures that any references to NEW.field will
1130 if (event == CMD_INSERT || event == CMD_UPDATE)
1131 rewriteTargetList(parsetree, rt_entry_relation);
1134 * Collect and apply the appropriate rules.
1136 locks = matchLocks(event, rt_entry_relation->rd_rules,
1137 result_relation, parsetree);
1141 List *product_queries;
1143 product_queries = fireRules(parsetree,
1151 * If we got any product queries, recursively rewrite them ---
1152 * but first check for recursion!
1154 if (product_queries != NIL)
1159 foreach(n, rewrite_events)
1161 rev = (rewrite_event *) lfirst(n);
1162 if (rev->relation == RelationGetRelid(rt_entry_relation) &&
1163 rev->event == event)
1165 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1166 errmsg("infinite recursion detected in rules for relation \"%s\"",
1167 RelationGetRelationName(rt_entry_relation))));
1170 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
1171 rev->relation = RelationGetRelid(rt_entry_relation);
1173 rewrite_events = lcons(rev, rewrite_events);
1175 foreach(n, product_queries)
1177 Query *pt = (Query *) lfirst(n);
1180 newstuff = RewriteQuery(pt, rewrite_events);
1181 rewritten = nconc(rewritten, newstuff);
1186 heap_close(rt_entry_relation, NoLock); /* keep lock! */
1190 * For INSERTs, the original query is done first; for UPDATE/DELETE,
1191 * it is done last. This is needed because update and delete rule
1192 * actions might not do anything if they are invoked after the update
1193 * or delete is performed. The command counter increment between the
1194 * query executions makes the deleted (and maybe the updated) tuples
1195 * disappear so the scans for them in the rule actions cannot find
1198 * If we found any unqualified INSTEAD, the original query is not done at
1199 * all, in any form. Otherwise, we add the modified form if qualified
1200 * INSTEADs were found, else the unmodified form.
1204 if (parsetree->commandType == CMD_INSERT)
1206 if (qual_product != NULL)
1207 rewritten = lcons(qual_product, rewritten);
1209 rewritten = lcons(parsetree, rewritten);
1213 if (qual_product != NULL)
1214 rewritten = lappend(rewritten, qual_product);
1216 rewritten = lappend(rewritten, parsetree);
1226 * Primary entry point to the query rewriter.
1227 * Rewrite one query via query rewrite system, possibly returning 0
1230 * NOTE: The code in QueryRewrite was formerly in pg_parse_and_plan(), and was
1231 * moved here so that it would be invoked during EXPLAIN.
1234 QueryRewrite(Query *parsetree)
1237 List *results = NIL;
1239 CmdType origCmdType;
1240 bool foundOriginalQuery;
1246 * Apply all non-SELECT rules possibly getting 0 or many queries
1248 querylist = RewriteQuery(parsetree, NIL);
1253 * Apply all the RIR rules on each query
1255 foreach(l, querylist)
1257 Query *query = (Query *) lfirst(l);
1259 query = fireRIRrules(query, NIL);
1262 * If the query target was rewritten as a view, complain.
1264 if (query->resultRelation)
1266 RangeTblEntry *rte = rt_fetch(query->resultRelation,
1269 if (rte->rtekind == RTE_SUBQUERY)
1271 switch (query->commandType)
1275 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1276 errmsg("cannot insert into a view"),
1277 errhint("You need an unconditional ON INSERT DO INSTEAD rule.")));
1281 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1282 errmsg("cannot update a view"),
1283 errhint("You need an unconditional ON UPDATE DO INSTEAD rule.")));
1287 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1288 errmsg("cannot delete from a view"),
1289 errhint("You need an unconditional ON DELETE DO INSTEAD rule.")));
1292 elog(ERROR, "unrecognized commandType: %d",
1293 (int) query->commandType);
1299 results = lappend(results, query);
1305 * Determine which, if any, of the resulting queries is supposed to set
1306 * the command-result tag; and update the canSetTag fields
1309 * If the original query is still in the list, it sets the command tag.
1310 * Otherwise, the last INSTEAD query of the same kind as the original
1311 * is allowed to set the tag. (Note these rules can leave us with no
1312 * query setting the tag. The tcop code has to cope with this by
1313 * setting up a default tag based on the original un-rewritten query.)
1315 * The Asserts verify that at most one query in the result list is marked
1316 * canSetTag. If we aren't checking asserts, we can fall out of the
1317 * loop as soon as we find the original query.
1319 origCmdType = parsetree->commandType;
1320 foundOriginalQuery = false;
1325 Query *query = (Query *) lfirst(l);
1327 if (query->querySource == QSRC_ORIGINAL)
1329 Assert(query->canSetTag);
1330 Assert(!foundOriginalQuery);
1331 foundOriginalQuery = true;
1332 #ifndef USE_ASSERT_CHECKING
1338 Assert(!query->canSetTag);
1339 if (query->commandType == origCmdType &&
1340 (query->querySource == QSRC_INSTEAD_RULE ||
1341 query->querySource == QSRC_QUAL_INSTEAD_RULE))
1342 lastInstead = query;
1346 if (!foundOriginalQuery && lastInstead != NULL)
1347 lastInstead->canSetTag = true;