1 /*-------------------------------------------------------------------------
4 * Primary module of query rewriter.
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/rewrite/rewriteHandler.c
12 *-------------------------------------------------------------------------
16 #include "access/sysattr.h"
17 #include "catalog/pg_type.h"
18 #include "commands/trigger.h"
19 #include "foreign/fdwapi.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/analyze.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parsetree.h"
25 #include "rewrite/rewriteDefine.h"
26 #include "rewrite/rewriteHandler.h"
27 #include "rewrite/rewriteManip.h"
28 #include "utils/builtins.h"
29 #include "utils/lsyscache.h"
30 #include "utils/rel.h"
33 /* We use a list of these to detect recursion in RewriteQuery */
34 typedef struct rewrite_event
36 Oid relation; /* OID of relation having rules */
37 CmdType event; /* type of rule being fired */
40 static bool acquireLocksOnSubLinks(Node *node, void *context);
41 static Query *rewriteRuleAction(Query *parsetree,
46 bool *returning_flag);
47 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
48 static void rewriteTargetListIU(Query *parsetree, Relation target_relation,
50 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
51 TargetEntry *prior_tle,
52 const char *attrName);
53 static Node *get_assignment_input(Node *node);
54 static void rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation,
56 static void rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
57 Relation target_relation);
58 static void markQueryForLocking(Query *qry, Node *jtnode,
59 LockClauseStrength strength, bool noWait, bool pushedDown);
60 static List *matchLocks(CmdType event, RuleLock *rulelocks,
61 int varno, Query *parsetree);
62 static Query *fireRIRrules(Query *parsetree, List *activeRIRs,
63 bool forUpdatePushedDown);
64 static bool view_has_instead_trigger(Relation view, CmdType event);
65 static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist);
69 * AcquireRewriteLocks -
70 * Acquire suitable locks on all the relations mentioned in the Query.
71 * These locks will ensure that the relation schemas don't change under us
72 * while we are rewriting and planning the query.
74 * forUpdatePushedDown indicates that a pushed-down FOR [KEY] UPDATE/SHARE applies
75 * to the current subquery, requiring all rels to be opened with RowShareLock.
76 * This should always be false at the start of the recursion.
78 * A secondary purpose of this routine is to fix up JOIN RTE references to
79 * dropped columns (see details below). Because the RTEs are modified in
80 * place, it is generally appropriate for the caller of this routine to have
81 * first done a copyObject() to make a writable copy of the querytree in the
82 * current memory context.
84 * This processing can, and for efficiency's sake should, be skipped when the
85 * querytree has just been built by the parser: parse analysis already got
86 * all the same locks we'd get here, and the parser will have omitted dropped
87 * columns from JOINs to begin with. But we must do this whenever we are
88 * dealing with a querytree produced earlier than the current command.
90 * About JOINs and dropped columns: although the parser never includes an
91 * already-dropped column in a JOIN RTE's alias var list, it is possible for
92 * such a list in a stored rule to include references to dropped columns.
93 * (If the column is not explicitly referenced anywhere else in the query,
94 * the dependency mechanism won't consider it used by the rule and so won't
95 * prevent the column drop.) To support get_rte_attribute_is_dropped(), we
96 * replace join alias vars that reference dropped columns with null pointers.
98 * (In PostgreSQL 8.0, we did not do this processing but instead had
99 * get_rte_attribute_is_dropped() recurse to detect dropped columns in joins.
100 * That approach had horrible performance unfortunately; in particular
101 * construction of a nested join was O(N^2) in the nesting depth.)
104 AcquireRewriteLocks(Query *parsetree, bool forUpdatePushedDown)
110 * First, process RTEs of the current query level.
113 foreach(l, parsetree->rtable)
115 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
120 RangeTblEntry *curinputrte;
124 switch (rte->rtekind)
129 * Grab the appropriate lock type for the relation, and do not
130 * release it until end of transaction. This protects the
131 * rewriter and planner against schema changes mid-query.
133 * If the relation is the query's result relation, then we
134 * need RowExclusiveLock. Otherwise, check to see if the
135 * relation is accessed FOR [KEY] UPDATE/SHARE or not. We
136 * can't just grab AccessShareLock because then the executor
137 * would be trying to upgrade the lock, leading to possible
140 if (rt_index == parsetree->resultRelation)
141 lockmode = RowExclusiveLock;
142 else if (forUpdatePushedDown ||
143 get_parse_rowmark(parsetree, rt_index) != NULL)
144 lockmode = RowShareLock;
146 lockmode = AccessShareLock;
148 rel = heap_open(rte->relid, lockmode);
151 * While we have the relation open, update the RTE's relkind,
152 * just in case it changed since this rule was made.
154 rte->relkind = rel->rd_rel->relkind;
156 heap_close(rel, NoLock);
162 * Scan the join's alias var list to see if any columns have
163 * been dropped, and if so replace those Vars with null
166 * Since a join has only two inputs, we can expect to see
167 * multiple references to the same input RTE; optimize away
173 foreach(ll, rte->joinaliasvars)
175 Var *aliasitem = (Var *) lfirst(ll);
176 Var *aliasvar = aliasitem;
178 /* Look through any implicit coercion */
179 aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
182 * If the list item isn't a simple Var, then it must
183 * represent a merged column, ie a USING column, and so it
184 * couldn't possibly be dropped, since it's referenced in
185 * the join clause. (Conceivably it could also be a null
186 * pointer already? But that's OK too.)
188 if (aliasvar && IsA(aliasvar, Var))
191 * The elements of an alias list have to refer to
192 * earlier RTEs of the same rtable, because that's the
193 * order the planner builds things in. So we already
194 * processed the referenced RTE, and so it's safe to
195 * use get_rte_attribute_is_dropped on it. (This might
196 * not hold after rewriting or planning, but it's OK
199 Assert(aliasvar->varlevelsup == 0);
200 if (aliasvar->varno != curinputvarno)
202 curinputvarno = aliasvar->varno;
203 if (curinputvarno >= rt_index)
204 elog(ERROR, "unexpected varno %d in JOIN RTE %d",
205 curinputvarno, rt_index);
206 curinputrte = rt_fetch(curinputvarno,
209 if (get_rte_attribute_is_dropped(curinputrte,
212 /* Replace the join alias item with a NULL */
216 newaliasvars = lappend(newaliasvars, aliasitem);
218 rte->joinaliasvars = newaliasvars;
224 * The subquery RTE itself is all right, but we have to
225 * recurse to process the represented subquery.
227 AcquireRewriteLocks(rte->subquery,
228 (forUpdatePushedDown ||
229 get_parse_rowmark(parsetree, rt_index) != NULL));
233 /* ignore other types of RTEs */
238 /* Recurse into subqueries in WITH */
239 foreach(l, parsetree->cteList)
241 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
243 AcquireRewriteLocks((Query *) cte->ctequery, false);
247 * Recurse into sublink subqueries, too. But we already did the ones in
248 * the rtable and cteList.
250 if (parsetree->hasSubLinks)
251 query_tree_walker(parsetree, acquireLocksOnSubLinks, NULL,
252 QTW_IGNORE_RC_SUBQUERIES);
256 * Walker to find sublink subqueries for AcquireRewriteLocks
259 acquireLocksOnSubLinks(Node *node, void *context)
263 if (IsA(node, SubLink))
265 SubLink *sub = (SubLink *) node;
267 /* Do what we came for */
268 AcquireRewriteLocks((Query *) sub->subselect, false);
269 /* Fall through to process lefthand args of SubLink */
273 * Do NOT recurse into Query nodes, because AcquireRewriteLocks already
274 * processed subselects of subselects for us.
276 return expression_tree_walker(node, acquireLocksOnSubLinks, context);
281 * rewriteRuleAction -
282 * Rewrite the rule action with appropriate qualifiers (taken from
283 * the triggering query).
286 * parsetree - original query
287 * rule_action - one action (query) of a rule
288 * rule_qual - WHERE condition of rule, or NULL if unconditional
289 * rt_index - RT index of result relation in original query
290 * event - type of rule event
292 * *returning_flag - set TRUE if we rewrite RETURNING clause in rule_action
293 * (must be initialized to FALSE)
295 * rewritten form of rule_action
298 rewriteRuleAction(Query *parsetree,
303 bool *returning_flag)
309 Query **sub_action_ptr;
312 * Make modifiable copies of rule action and qual (what we're passed are
313 * the stored versions in the relcache; don't touch 'em!).
315 rule_action = (Query *) copyObject(rule_action);
316 rule_qual = (Node *) copyObject(rule_qual);
319 * Acquire necessary locks and fix any deleted JOIN RTE entries.
321 AcquireRewriteLocks(rule_action, false);
322 (void) acquireLocksOnSubLinks(rule_qual, NULL);
324 current_varno = rt_index;
325 rt_length = list_length(parsetree->rtable);
326 new_varno = PRS2_NEW_VARNO + rt_length;
329 * Adjust rule action and qual to offset its varnos, so that we can merge
330 * its rtable with the main parsetree's rtable.
332 * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
333 * will be in the SELECT part, and we have to modify that rather than the
334 * top-level INSERT (kluge!).
336 sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
338 OffsetVarNodes((Node *) sub_action, rt_length, 0);
339 OffsetVarNodes(rule_qual, rt_length, 0);
340 /* but references to OLD should point at original rt_index */
341 ChangeVarNodes((Node *) sub_action,
342 PRS2_OLD_VARNO + rt_length, rt_index, 0);
343 ChangeVarNodes(rule_qual,
344 PRS2_OLD_VARNO + rt_length, rt_index, 0);
347 * Generate expanded rtable consisting of main parsetree's rtable plus
348 * rule action's rtable; this becomes the complete rtable for the rule
349 * action. Some of the entries may be unused after we finish rewriting,
350 * but we leave them all in place for two reasons:
352 * We'd have a much harder job to adjust the query's varnos if we
353 * selectively removed RT entries.
355 * If the rule is INSTEAD, then the original query won't be executed at
356 * all, and so its rtable must be preserved so that the executor will do
357 * the correct permissions checks on it.
359 * RT entries that are not referenced in the completed jointree will be
360 * ignored by the planner, so they do not affect query semantics. But any
361 * permissions checks specified in them will be applied during executor
362 * startup (see ExecCheckRTEPerms()). This allows us to check that the
363 * caller has, say, insert-permission on a view, when the view is not
364 * semantically referenced at all in the resulting query.
366 * When a rule is not INSTEAD, the permissions checks done on its copied
367 * RT entries will be redundant with those done during execution of the
368 * original query, but we don't bother to treat that case differently.
370 * NOTE: because planner will destructively alter rtable, we must ensure
371 * that rule action's rtable is separate and shares no substructure with
372 * the main rtable. Hence do a deep copy here.
374 sub_action->rtable = list_concat((List *) copyObject(parsetree->rtable),
378 * There could have been some SubLinks in parsetree's rtable, in which
379 * case we'd better mark the sub_action correctly.
381 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
385 foreach(lc, parsetree->rtable)
387 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
389 switch (rte->rtekind)
392 sub_action->hasSubLinks =
393 checkExprHasSubLink((Node *) rte->functions);
396 sub_action->hasSubLinks =
397 checkExprHasSubLink((Node *) rte->values_lists);
400 /* other RTE types don't contain bare expressions */
403 if (sub_action->hasSubLinks)
404 break; /* no need to keep scanning rtable */
409 * Each rule action's jointree should be the main parsetree's jointree
410 * plus that rule's jointree, but usually *without* the original rtindex
411 * that we're replacing (if present, which it won't be for INSERT). Note
412 * that if the rule action refers to OLD, its jointree will add a
413 * reference to rt_index. If the rule action doesn't refer to OLD, but
414 * either the rule_qual or the user query quals do, then we need to keep
415 * the original rtindex in the jointree to provide data for the quals. We
416 * don't want the original rtindex to be joined twice, however, so avoid
417 * keeping it if the rule action mentions it.
419 * As above, the action's jointree must not share substructure with the
422 if (sub_action->commandType != CMD_UTILITY)
427 Assert(sub_action->jointree != NULL);
428 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
430 (rangeTableEntry_used(rule_qual, rt_index, 0) ||
431 rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
432 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
433 if (newjointree != NIL)
436 * If sub_action is a setop, manipulating its jointree will do no
437 * good at all, because the jointree is dummy. (Perhaps someday
438 * we could push the joining and quals down to the member
439 * statements of the setop?)
441 if (sub_action->setOperations != NULL)
443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
444 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
446 sub_action->jointree->fromlist =
447 list_concat(newjointree, sub_action->jointree->fromlist);
450 * There could have been some SubLinks in newjointree, in which
451 * case we'd better mark the sub_action correctly.
453 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
454 sub_action->hasSubLinks =
455 checkExprHasSubLink((Node *) newjointree);
460 * If the original query has any CTEs, copy them into the rule action. But
461 * we don't need them for a utility action.
463 if (parsetree->cteList != NIL && sub_action->commandType != CMD_UTILITY)
468 * Annoying implementation restriction: because CTEs are identified by
469 * name within a cteList, we can't merge a CTE from the original query
470 * if it has the same name as any CTE in the rule action.
472 * This could possibly be fixed by using some sort of internally
473 * generated ID, instead of names, to link CTE RTEs to their CTEs.
475 foreach(lc, parsetree->cteList)
477 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
480 foreach(lc2, sub_action->cteList)
482 CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(lc2);
484 if (strcmp(cte->ctename, cte2->ctename) == 0)
486 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
487 errmsg("WITH query name \"%s\" appears in both a rule action and the query being rewritten",
492 /* OK, it's safe to combine the CTE lists */
493 sub_action->cteList = list_concat(sub_action->cteList,
494 copyObject(parsetree->cteList));
498 * Event Qualification forces copying of parsetree and splitting into two
499 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
502 AddQual(sub_action, rule_qual);
504 AddQual(sub_action, parsetree->jointree->quals);
507 * Rewrite new.attribute with right hand side of target-list entry for
508 * appropriate field name in insert/update.
510 * KLUGE ALERT: since ReplaceVarsFromTargetList returns a mutated copy, we
511 * can't just apply it to sub_action; we have to remember to update the
512 * sublink inside rule_action, too.
514 if ((event == CMD_INSERT || event == CMD_UPDATE) &&
515 sub_action->commandType != CMD_UTILITY)
517 sub_action = (Query *)
518 ReplaceVarsFromTargetList((Node *) sub_action,
521 rt_fetch(new_varno, sub_action->rtable),
522 parsetree->targetList,
523 (event == CMD_UPDATE) ?
524 REPLACEVARS_CHANGE_VARNO :
525 REPLACEVARS_SUBSTITUTE_NULL,
529 *sub_action_ptr = sub_action;
531 rule_action = sub_action;
535 * If rule_action has a RETURNING clause, then either throw it away if the
536 * triggering query has no RETURNING clause, or rewrite it to emit what
537 * the triggering query's RETURNING clause asks for. Throw an error if
538 * more than one rule has a RETURNING clause.
540 if (!parsetree->returningList)
541 rule_action->returningList = NIL;
542 else if (rule_action->returningList)
546 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
547 errmsg("cannot have RETURNING lists in multiple rules")));
548 *returning_flag = true;
549 rule_action->returningList = (List *)
550 ReplaceVarsFromTargetList((Node *) parsetree->returningList,
551 parsetree->resultRelation,
553 rt_fetch(parsetree->resultRelation,
555 rule_action->returningList,
556 REPLACEVARS_REPORT_ERROR,
558 &rule_action->hasSubLinks);
561 * There could have been some SubLinks in parsetree's returningList,
562 * in which case we'd better mark the rule_action correctly.
564 if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
565 rule_action->hasSubLinks =
566 checkExprHasSubLink((Node *) rule_action->returningList);
573 * Copy the query's jointree list, and optionally attempt to remove any
574 * occurrence of the given rt_index as a top-level join item (we do not look
575 * for it within join items; this is OK because we are only expecting to find
576 * it as an UPDATE or DELETE target relation, which will be at the top level
577 * of the join). Returns modified jointree list --- this is a separate copy
578 * sharing no nodes with the original.
581 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
583 List *newjointree = copyObject(parsetree->jointree->fromlist);
588 foreach(l, newjointree)
590 RangeTblRef *rtr = lfirst(l);
592 if (IsA(rtr, RangeTblRef) &&
593 rtr->rtindex == rt_index)
595 newjointree = list_delete_ptr(newjointree, rtr);
598 * foreach is safe because we exit loop after list_delete...
609 * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
611 * This has the following responsibilities:
613 * 1. For an INSERT, add tlist entries to compute default values for any
614 * attributes that have defaults and are not assigned to in the given tlist.
615 * (We do not insert anything for default-less attributes, however. The
616 * planner will later insert NULLs for them, but there's no reason to slow
617 * down rewriter processing with extra tlist nodes.) Also, for both INSERT
618 * and UPDATE, replace explicit DEFAULT specifications with column default
621 * 2. For an UPDATE on a trigger-updatable view, add tlist entries for any
622 * unassigned-to attributes, assigning them their old values. These will
623 * later get expanded to the output values of the view. (This is equivalent
624 * to what the planner's expand_targetlist() will do for UPDATE on a regular
625 * table, but it's more convenient to do it here while we still have easy
626 * access to the view's original RT index.) This is only necessary for
627 * trigger-updatable views, for which the view remains the result relation of
628 * the query. For auto-updatable views we must not do this, since it might
629 * add assignments to non-updatable view columns. For rule-updatable views it
630 * is unnecessary extra work, since the query will be rewritten with a
631 * different result relation which will be processed when we recurse via
634 * 3. Merge multiple entries for the same target attribute, or declare error
635 * if we can't. Multiple entries are only allowed for INSERT/UPDATE of
636 * portions of an array or record field, for example
637 * UPDATE table SET foo[2] = 42, foo[4] = 43;
638 * We can merge such operations into a single assignment op. Essentially,
639 * the expression we want to produce in this case is like
640 * foo = array_set(array_set(foo, 2, 42), 4, 43)
642 * 4. Sort the tlist into standard order: non-junk fields in order by resno,
643 * then junk fields (these in no particular order).
645 * We must do items 1,2,3 before firing rewrite rules, else rewritten
646 * references to NEW.foo will produce wrong or incomplete results. Item 4
647 * is not needed for rewriting, but will be needed by the planner, and we
648 * can do it essentially for free while handling the other items.
650 * If attrno_list isn't NULL, we return an additional output besides the
651 * rewritten targetlist: an integer list of the assigned-to attnums, in
652 * order of the original tlist's non-junk entries. This is needed for
653 * processing VALUES RTEs.
656 rewriteTargetListIU(Query *parsetree, Relation target_relation,
659 CmdType commandType = parsetree->commandType;
660 TargetEntry **new_tles;
661 List *new_tlist = NIL;
662 List *junk_tlist = NIL;
663 Form_pg_attribute att_tup;
669 if (attrno_list) /* initialize optional result list */
673 * We process the normal (non-junk) attributes by scanning the input tlist
674 * once and transferring TLEs into an array, then scanning the array to
675 * build an output tlist. This avoids O(N^2) behavior for large numbers
678 * Junk attributes are tossed into a separate list during the same tlist
679 * scan, then appended to the reconstructed tlist.
681 numattrs = RelationGetNumberOfAttributes(target_relation);
682 new_tles = (TargetEntry **) palloc0(numattrs * sizeof(TargetEntry *));
683 next_junk_attrno = numattrs + 1;
685 foreach(temp, parsetree->targetList)
687 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
689 if (!old_tle->resjunk)
691 /* Normal attr: stash it into new_tles[] */
692 attrno = old_tle->resno;
693 if (attrno < 1 || attrno > numattrs)
694 elog(ERROR, "bogus resno %d in targetlist", attrno);
695 att_tup = target_relation->rd_att->attrs[attrno - 1];
697 /* put attrno into attrno_list even if it's dropped */
699 *attrno_list = lappend_int(*attrno_list, attrno);
701 /* We can (and must) ignore deleted attributes */
702 if (att_tup->attisdropped)
705 /* Merge with any prior assignment to same attribute */
706 new_tles[attrno - 1] =
707 process_matched_tle(old_tle,
708 new_tles[attrno - 1],
709 NameStr(att_tup->attname));
714 * Copy all resjunk tlist entries to junk_tlist, and assign them
715 * resnos above the last real resno.
717 * Typical junk entries include ORDER BY or GROUP BY expressions
718 * (are these actually possible in an INSERT or UPDATE?), system
719 * attribute references, etc.
722 /* Get the resno right, but don't copy unnecessarily */
723 if (old_tle->resno != next_junk_attrno)
725 old_tle = flatCopyTargetEntry(old_tle);
726 old_tle->resno = next_junk_attrno;
728 junk_tlist = lappend(junk_tlist, old_tle);
733 for (attrno = 1; attrno <= numattrs; attrno++)
735 TargetEntry *new_tle = new_tles[attrno - 1];
737 att_tup = target_relation->rd_att->attrs[attrno - 1];
739 /* We can (and must) ignore deleted attributes */
740 if (att_tup->attisdropped)
744 * Handle the two cases where we need to insert a default expression:
745 * it's an INSERT and there's no tlist entry for the column, or the
746 * tlist entry is a DEFAULT placeholder node.
748 if ((new_tle == NULL && commandType == CMD_INSERT) ||
749 (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)))
753 new_expr = build_column_default(target_relation, attrno);
756 * If there is no default (ie, default is effectively NULL), we
757 * can omit the tlist entry in the INSERT case, since the planner
758 * can insert a NULL for itself, and there's no point in spending
759 * any more rewriter cycles on the entry. But in the UPDATE case
760 * we've got to explicitly set the column to NULL.
764 if (commandType == CMD_INSERT)
768 new_expr = (Node *) makeConst(att_tup->atttypid,
770 att_tup->attcollation,
775 /* this is to catch a NOT NULL domain constraint */
776 new_expr = coerce_to_domain(new_expr,
779 COERCE_IMPLICIT_CAST,
787 new_tle = makeTargetEntry((Expr *) new_expr,
789 pstrdup(NameStr(att_tup->attname)),
794 * For an UPDATE on a trigger-updatable view, provide a dummy entry
795 * whenever there is no explicit assignment.
797 if (new_tle == NULL && commandType == CMD_UPDATE &&
798 target_relation->rd_rel->relkind == RELKIND_VIEW &&
799 view_has_instead_trigger(target_relation, CMD_UPDATE))
803 new_expr = (Node *) makeVar(parsetree->resultRelation,
807 att_tup->attcollation,
810 new_tle = makeTargetEntry((Expr *) new_expr,
812 pstrdup(NameStr(att_tup->attname)),
817 new_tlist = lappend(new_tlist, new_tle);
822 parsetree->targetList = list_concat(new_tlist, junk_tlist);
827 * Convert a matched TLE from the original tlist into a correct new TLE.
829 * This routine detects and handles multiple assignments to the same target
830 * attribute. (The attribute name is needed only for error messages.)
833 process_matched_tle(TargetEntry *src_tle,
834 TargetEntry *prior_tle,
835 const char *attrName)
845 if (prior_tle == NULL)
848 * Normal case where this is the first assignment to the attribute.
854 * Multiple assignments to same attribute. Allow only if all are
855 * FieldStore or ArrayRef assignment operations. This is a bit
856 * tricky because what we may actually be looking at is a nest of
857 * such nodes; consider
858 * UPDATE tab SET col.fld1.subfld1 = x, col.fld2.subfld2 = y
859 * The two expressions produced by the parser will look like
860 * FieldStore(col, fld1, FieldStore(placeholder, subfld1, x))
861 * FieldStore(col, fld2, FieldStore(placeholder, subfld2, x))
862 * However, we can ignore the substructure and just consider the top
863 * FieldStore or ArrayRef from each assignment, because it works to
865 * FieldStore(FieldStore(col, fld1,
866 * FieldStore(placeholder, subfld1, x)),
867 * fld2, FieldStore(placeholder, subfld2, x))
868 * Note the leftmost expression goes on the inside so that the
869 * assignments appear to occur left-to-right.
871 * For FieldStore, instead of nesting we can generate a single
872 * FieldStore with multiple target fields. We must nest when
873 * ArrayRefs are involved though.
876 src_expr = (Node *) src_tle->expr;
877 prior_expr = (Node *) prior_tle->expr;
878 src_input = get_assignment_input(src_expr);
879 prior_input = get_assignment_input(prior_expr);
880 if (src_input == NULL ||
881 prior_input == NULL ||
882 exprType(src_expr) != exprType(prior_expr))
884 (errcode(ERRCODE_SYNTAX_ERROR),
885 errmsg("multiple assignments to same column \"%s\"",
889 * Prior TLE could be a nest of assignments if we do this more than once.
891 priorbottom = prior_input;
894 Node *newbottom = get_assignment_input(priorbottom);
896 if (newbottom == NULL)
897 break; /* found the original Var reference */
898 priorbottom = newbottom;
900 if (!equal(priorbottom, src_input))
902 (errcode(ERRCODE_SYNTAX_ERROR),
903 errmsg("multiple assignments to same column \"%s\"",
907 * Looks OK to nest 'em.
909 if (IsA(src_expr, FieldStore))
911 FieldStore *fstore = makeNode(FieldStore);
913 if (IsA(prior_expr, FieldStore))
915 /* combine the two */
916 memcpy(fstore, prior_expr, sizeof(FieldStore));
918 list_concat(list_copy(((FieldStore *) prior_expr)->newvals),
919 list_copy(((FieldStore *) src_expr)->newvals));
921 list_concat(list_copy(((FieldStore *) prior_expr)->fieldnums),
922 list_copy(((FieldStore *) src_expr)->fieldnums));
926 /* general case, just nest 'em */
927 memcpy(fstore, src_expr, sizeof(FieldStore));
928 fstore->arg = (Expr *) prior_expr;
930 newexpr = (Node *) fstore;
932 else if (IsA(src_expr, ArrayRef))
934 ArrayRef *aref = makeNode(ArrayRef);
936 memcpy(aref, src_expr, sizeof(ArrayRef));
937 aref->refexpr = (Expr *) prior_expr;
938 newexpr = (Node *) aref;
942 elog(ERROR, "cannot happen");
946 result = flatCopyTargetEntry(src_tle);
947 result->expr = (Expr *) newexpr;
952 * If node is an assignment node, return its input; else return NULL
955 get_assignment_input(Node *node)
959 if (IsA(node, FieldStore))
961 FieldStore *fstore = (FieldStore *) node;
963 return (Node *) fstore->arg;
965 else if (IsA(node, ArrayRef))
967 ArrayRef *aref = (ArrayRef *) node;
969 if (aref->refassgnexpr == NULL)
971 return (Node *) aref->refexpr;
977 * Make an expression tree for the default value for a column.
979 * If there is no default, return a NULL instead.
982 build_column_default(Relation rel, int attrno)
984 TupleDesc rd_att = rel->rd_att;
985 Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
986 Oid atttype = att_tup->atttypid;
987 int32 atttypmod = att_tup->atttypmod;
992 * Scan to see if relation has a default for this column.
994 if (rd_att->constr && rd_att->constr->num_defval > 0)
996 AttrDefault *defval = rd_att->constr->defval;
997 int ndef = rd_att->constr->num_defval;
1001 if (attrno == defval[ndef].adnum)
1004 * Found it, convert string representation to node tree.
1006 expr = stringToNode(defval[ndef].adbin);
1015 * No per-column default, so look for a default for the type itself.
1017 expr = get_typdefault(atttype);
1021 return NULL; /* No default anywhere */
1024 * Make sure the value is coerced to the target column type; this will
1025 * generally be true already, but there seem to be some corner cases
1026 * involving domain defaults where it might not be true. This should match
1027 * the parser's processing of non-defaulted expressions --- see
1028 * transformAssignedExpr().
1030 exprtype = exprType(expr);
1032 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1035 COERCION_ASSIGNMENT,
1036 COERCE_IMPLICIT_CAST,
1040 (errcode(ERRCODE_DATATYPE_MISMATCH),
1041 errmsg("column \"%s\" is of type %s"
1042 " but default expression is of type %s",
1043 NameStr(att_tup->attname),
1044 format_type_be(atttype),
1045 format_type_be(exprtype)),
1046 errhint("You will need to rewrite or cast the expression.")));
1052 /* Does VALUES RTE contain any SetToDefault items? */
1054 searchForDefault(RangeTblEntry *rte)
1058 foreach(lc, rte->values_lists)
1060 List *sublist = (List *) lfirst(lc);
1063 foreach(lc2, sublist)
1065 Node *col = (Node *) lfirst(lc2);
1067 if (IsA(col, SetToDefault))
1075 * When processing INSERT ... VALUES with a VALUES RTE (ie, multiple VALUES
1076 * lists), we have to replace any DEFAULT items in the VALUES lists with
1077 * the appropriate default expressions. The other aspects of targetlist
1078 * rewriting need be applied only to the query's targetlist proper.
1080 * Note that we currently can't support subscripted or field assignment
1081 * in the multi-VALUES case. The targetlist will contain simple Vars
1082 * referencing the VALUES RTE, and therefore process_matched_tle() will
1083 * reject any such attempt with "multiple assignments to same column".
1086 rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation, List *attrnos)
1092 * Rebuilding all the lists is a pretty expensive proposition in a big
1093 * VALUES list, and it's a waste of time if there aren't any DEFAULT
1094 * placeholders. So first scan to see if there are any.
1096 if (!searchForDefault(rte))
1097 return; /* nothing to do */
1099 /* Check list lengths (we can assume all the VALUES sublists are alike) */
1100 Assert(list_length(attrnos) == list_length(linitial(rte->values_lists)));
1103 foreach(lc, rte->values_lists)
1105 List *sublist = (List *) lfirst(lc);
1106 List *newList = NIL;
1110 forboth(lc2, sublist, lc3, attrnos)
1112 Node *col = (Node *) lfirst(lc2);
1113 int attrno = lfirst_int(lc3);
1115 if (IsA(col, SetToDefault))
1117 Form_pg_attribute att_tup;
1120 att_tup = target_relation->rd_att->attrs[attrno - 1];
1122 if (!att_tup->attisdropped)
1123 new_expr = build_column_default(target_relation, attrno);
1125 new_expr = NULL; /* force a NULL if dropped */
1128 * If there is no default (ie, default is effectively NULL),
1129 * we've got to explicitly set the column to NULL.
1133 new_expr = (Node *) makeConst(att_tup->atttypid,
1135 att_tup->attcollation,
1140 /* this is to catch a NOT NULL domain constraint */
1141 new_expr = coerce_to_domain(new_expr,
1144 COERCE_IMPLICIT_CAST,
1149 newList = lappend(newList, new_expr);
1152 newList = lappend(newList, col);
1154 newValues = lappend(newValues, newList);
1156 rte->values_lists = newValues;
1161 * rewriteTargetListUD - rewrite UPDATE/DELETE targetlist as needed
1163 * This function adds a "junk" TLE that is needed to allow the executor to
1164 * find the original row for the update or delete. When the target relation
1165 * is a regular table, the junk TLE emits the ctid attribute of the original
1166 * row. When the target relation is a view, there is no ctid, so we instead
1167 * emit a whole-row Var that will contain the "old" values of the view row.
1168 * If it's a foreign table, we let the FDW decide what to add.
1170 * For UPDATE queries, this is applied after rewriteTargetListIU. The
1171 * ordering isn't actually critical at the moment.
1174 rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
1175 Relation target_relation)
1178 const char *attrname;
1181 if (target_relation->rd_rel->relkind == RELKIND_RELATION ||
1182 target_relation->rd_rel->relkind == RELKIND_MATVIEW)
1185 * Emit CTID so that executor can find the row to update or delete.
1187 var = makeVar(parsetree->resultRelation,
1188 SelfItemPointerAttributeNumber,
1196 else if (target_relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1199 * Let the foreign table's FDW add whatever junk TLEs it wants.
1201 FdwRoutine *fdwroutine;
1203 fdwroutine = GetFdwRoutineForRelation(target_relation, false);
1205 if (fdwroutine->AddForeignUpdateTargets != NULL)
1206 fdwroutine->AddForeignUpdateTargets(parsetree, target_rte,
1214 * Emit whole-row Var so that executor will have the "old" view row to
1215 * pass to the INSTEAD OF trigger.
1217 var = makeWholeRowVar(target_rte,
1218 parsetree->resultRelation,
1222 attrname = "wholerow";
1225 tle = makeTargetEntry((Expr *) var,
1226 list_length(parsetree->targetList) + 1,
1230 parsetree->targetList = lappend(parsetree->targetList, tle);
1236 * match the list of locks and returns the matching rules
1239 matchLocks(CmdType event,
1240 RuleLock *rulelocks,
1244 List *matching_locks = NIL;
1248 if (rulelocks == NULL)
1251 if (parsetree->commandType != CMD_SELECT)
1253 if (parsetree->resultRelation != varno)
1257 nlocks = rulelocks->numLocks;
1259 for (i = 0; i < nlocks; i++)
1261 RewriteRule *oneLock = rulelocks->rules[i];
1264 * Suppress ON INSERT/UPDATE/DELETE rules that are disabled or
1265 * configured to not fire during the current sessions replication
1266 * role. ON SELECT rules will always be applied in order to keep views
1267 * working even in LOCAL or REPLICA role.
1269 if (oneLock->event != CMD_SELECT)
1271 if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
1273 if (oneLock->enabled == RULE_FIRES_ON_ORIGIN ||
1274 oneLock->enabled == RULE_DISABLED)
1277 else /* ORIGIN or LOCAL ROLE */
1279 if (oneLock->enabled == RULE_FIRES_ON_REPLICA ||
1280 oneLock->enabled == RULE_DISABLED)
1285 if (oneLock->event == event)
1287 if (parsetree->commandType != CMD_SELECT ||
1288 rangeTableEntry_used((Node *) parsetree, varno, 0))
1289 matching_locks = lappend(matching_locks, oneLock);
1293 return matching_locks;
1298 * ApplyRetrieveRule - expand an ON SELECT rule
1301 ApplyRetrieveRule(Query *parsetree,
1306 bool forUpdatePushedDown)
1313 if (list_length(rule->actions) != 1)
1314 elog(ERROR, "expected just one rule action");
1315 if (rule->qual != NULL)
1316 elog(ERROR, "cannot handle qualified ON SELECT rule");
1318 if (rt_index == parsetree->resultRelation)
1321 * We have a view as the result relation of the query, and it wasn't
1322 * rewritten by any rule. This case is supported if there is an
1323 * INSTEAD OF trigger that will trap attempts to insert/update/delete
1324 * view rows. The executor will check that; for the moment just plow
1325 * ahead. We have two cases:
1327 * For INSERT, we needn't do anything. The unmodified RTE will serve
1328 * fine as the result relation.
1330 * For UPDATE/DELETE, we need to expand the view so as to have source
1331 * data for the operation. But we also need an unmodified RTE to
1332 * serve as the target. So, copy the RTE and add the copy to the
1333 * rangetable. Note that the copy does not get added to the jointree.
1334 * Also note that there's a hack in fireRIRrules to avoid calling this
1335 * function again when it arrives at the copied RTE.
1337 if (parsetree->commandType == CMD_INSERT)
1339 else if (parsetree->commandType == CMD_UPDATE ||
1340 parsetree->commandType == CMD_DELETE)
1342 RangeTblEntry *newrte;
1344 rte = rt_fetch(rt_index, parsetree->rtable);
1345 newrte = copyObject(rte);
1346 parsetree->rtable = lappend(parsetree->rtable, newrte);
1347 parsetree->resultRelation = list_length(parsetree->rtable);
1350 * There's no need to do permissions checks twice, so wipe out the
1351 * permissions info for the original RTE (we prefer to keep the
1352 * bits set on the result RTE).
1354 rte->requiredPerms = 0;
1355 rte->checkAsUser = InvalidOid;
1356 rte->selectedCols = NULL;
1357 rte->modifiedCols = NULL;
1360 * For the most part, Vars referencing the view should remain as
1361 * they are, meaning that they implicitly represent OLD values.
1362 * But in the RETURNING list if any, we want such Vars to
1363 * represent NEW values, so change them to reference the new RTE.
1365 * Since ChangeVarNodes scribbles on the tree in-place, copy the
1366 * RETURNING list first for safety.
1368 parsetree->returningList = copyObject(parsetree->returningList);
1369 ChangeVarNodes((Node *) parsetree->returningList, rt_index,
1370 parsetree->resultRelation, 0);
1372 /* Now, continue with expanding the original view RTE */
1375 elog(ERROR, "unrecognized commandType: %d",
1376 (int) parsetree->commandType);
1380 * If FOR [KEY] UPDATE/SHARE of view, be sure we get right initial lock on
1381 * the relations it references.
1383 rc = get_parse_rowmark(parsetree, rt_index);
1384 forUpdatePushedDown |= (rc != NULL);
1387 * Make a modifiable copy of the view query, and acquire needed locks on
1388 * the relations it mentions.
1390 rule_action = copyObject(linitial(rule->actions));
1392 AcquireRewriteLocks(rule_action, forUpdatePushedDown);
1395 * Recursively expand any view references inside the view.
1397 rule_action = fireRIRrules(rule_action, activeRIRs, forUpdatePushedDown);
1400 * Now, plug the view query in as a subselect, replacing the relation's
1403 rte = rt_fetch(rt_index, parsetree->rtable);
1405 rte->rtekind = RTE_SUBQUERY;
1406 rte->relid = InvalidOid;
1407 rte->security_barrier = RelationIsSecurityView(relation);
1408 rte->subquery = rule_action;
1409 rte->inh = false; /* must not be set for a subquery */
1412 * We move the view's permission check data down to its rangetable. The
1413 * checks will actually be done against the OLD entry therein.
1415 subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
1416 Assert(subrte->relid == relation->rd_id);
1417 subrte->requiredPerms = rte->requiredPerms;
1418 subrte->checkAsUser = rte->checkAsUser;
1419 subrte->selectedCols = rte->selectedCols;
1420 subrte->modifiedCols = rte->modifiedCols;
1422 rte->requiredPerms = 0; /* no permission check on subquery itself */
1423 rte->checkAsUser = InvalidOid;
1424 rte->selectedCols = NULL;
1425 rte->modifiedCols = NULL;
1428 * If FOR [KEY] UPDATE/SHARE of view, mark all the contained tables as
1429 * implicit FOR [KEY] UPDATE/SHARE, the same as the parser would have done
1430 * if the view's subquery had been written out explicitly.
1432 * Note: we don't consider forUpdatePushedDown here; such marks will be
1433 * made by recursing from the upper level in markQueryForLocking.
1436 markQueryForLocking(rule_action, (Node *) rule_action->jointree,
1437 rc->strength, rc->noWait, true);
1443 * Recursively mark all relations used by a view as FOR [KEY] UPDATE/SHARE.
1445 * This may generate an invalid query, eg if some sub-query uses an
1446 * aggregate. We leave it to the planner to detect that.
1448 * NB: this must agree with the parser's transformLockingClause() routine.
1449 * However, unlike the parser we have to be careful not to mark a view's
1450 * OLD and NEW rels for updating. The best way to handle that seems to be
1451 * to scan the jointree to determine which rels are used.
1454 markQueryForLocking(Query *qry, Node *jtnode,
1455 LockClauseStrength strength, bool noWait, bool pushedDown)
1459 if (IsA(jtnode, RangeTblRef))
1461 int rti = ((RangeTblRef *) jtnode)->rtindex;
1462 RangeTblEntry *rte = rt_fetch(rti, qry->rtable);
1464 if (rte->rtekind == RTE_RELATION)
1466 applyLockingClause(qry, rti, strength, noWait, pushedDown);
1467 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1469 else if (rte->rtekind == RTE_SUBQUERY)
1471 applyLockingClause(qry, rti, strength, noWait, pushedDown);
1472 /* FOR UPDATE/SHARE of subquery is propagated to subquery's rels */
1473 markQueryForLocking(rte->subquery, (Node *) rte->subquery->jointree,
1474 strength, noWait, true);
1476 /* other RTE types are unaffected by FOR UPDATE */
1478 else if (IsA(jtnode, FromExpr))
1480 FromExpr *f = (FromExpr *) jtnode;
1483 foreach(l, f->fromlist)
1484 markQueryForLocking(qry, lfirst(l), strength, noWait, pushedDown);
1486 else if (IsA(jtnode, JoinExpr))
1488 JoinExpr *j = (JoinExpr *) jtnode;
1490 markQueryForLocking(qry, j->larg, strength, noWait, pushedDown);
1491 markQueryForLocking(qry, j->rarg, strength, noWait, pushedDown);
1494 elog(ERROR, "unrecognized node type: %d",
1495 (int) nodeTag(jtnode));
1500 * fireRIRonSubLink -
1501 * Apply fireRIRrules() to each SubLink (subselect in expression) found
1502 * in the given tree.
1504 * NOTE: although this has the form of a walker, we cheat and modify the
1505 * SubLink nodes in-place. It is caller's responsibility to ensure that
1506 * no unwanted side-effects occur!
1508 * This is unlike most of the other routines that recurse into subselects,
1509 * because we must take control at the SubLink node in order to replace
1510 * the SubLink's subselect link with the possibly-rewritten subquery.
1513 fireRIRonSubLink(Node *node, List *activeRIRs)
1517 if (IsA(node, SubLink))
1519 SubLink *sub = (SubLink *) node;
1521 /* Do what we came for */
1522 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
1524 /* Fall through to process lefthand args of SubLink */
1528 * Do NOT recurse into Query nodes, because fireRIRrules already processed
1529 * subselects of subselects for us.
1531 return expression_tree_walker(node, fireRIRonSubLink,
1532 (void *) activeRIRs);
1538 * Apply all RIR rules on each rangetable entry in a query
1541 fireRIRrules(Query *parsetree, List *activeRIRs, bool forUpdatePushedDown)
1543 int origResultRelation = parsetree->resultRelation;
1548 * don't try to convert this into a foreach loop, because rtable list can
1549 * get changed each time through...
1552 while (rt_index < list_length(parsetree->rtable))
1563 rte = rt_fetch(rt_index, parsetree->rtable);
1566 * A subquery RTE can't have associated rules, so there's nothing to
1567 * do to this level of the query, but we must recurse into the
1568 * subquery to expand any rule references in it.
1570 if (rte->rtekind == RTE_SUBQUERY)
1572 rte->subquery = fireRIRrules(rte->subquery, activeRIRs,
1573 (forUpdatePushedDown ||
1574 get_parse_rowmark(parsetree, rt_index) != NULL));
1579 * Joins and other non-relation RTEs can be ignored completely.
1581 if (rte->rtekind != RTE_RELATION)
1585 * Always ignore RIR rules for materialized views referenced in
1586 * queries. (This does not prevent refreshing MVs, since they aren't
1587 * referenced in their own query definitions.)
1589 * Note: in the future we might want to allow MVs to be conditionally
1590 * expanded as if they were regular views, if they are not scannable.
1591 * In that case this test would need to be postponed till after we've
1592 * opened the rel, so that we could check its state.
1594 if (rte->relkind == RELKIND_MATVIEW)
1598 * If the table is not referenced in the query, then we ignore it.
1599 * This prevents infinite expansion loop due to new rtable entries
1600 * inserted by expansion of a rule. A table is referenced if it is
1601 * part of the join set (a source table), or is referenced by any Var
1602 * nodes, or is the result table.
1604 if (rt_index != parsetree->resultRelation &&
1605 !rangeTableEntry_used((Node *) parsetree, rt_index, 0))
1609 * Also, if this is a new result relation introduced by
1610 * ApplyRetrieveRule, we don't want to do anything more with it.
1612 if (rt_index == parsetree->resultRelation &&
1613 rt_index != origResultRelation)
1617 * We can use NoLock here since either the parser or
1618 * AcquireRewriteLocks should have locked the rel already.
1620 rel = heap_open(rte->relid, NoLock);
1623 * Collect the RIR rules that we must apply
1625 rules = rel->rd_rules;
1628 heap_close(rel, NoLock);
1632 for (i = 0; i < rules->numLocks; i++)
1634 rule = rules->rules[i];
1635 if (rule->event != CMD_SELECT)
1638 locks = lappend(locks, rule);
1642 * If we found any, apply them --- but first check for recursion!
1648 if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
1650 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1651 errmsg("infinite recursion detected in rules for relation \"%s\"",
1652 RelationGetRelationName(rel))));
1653 activeRIRs = lcons_oid(RelationGetRelid(rel), activeRIRs);
1659 parsetree = ApplyRetrieveRule(parsetree,
1664 forUpdatePushedDown);
1667 activeRIRs = list_delete_first(activeRIRs);
1670 heap_close(rel, NoLock);
1673 /* Recurse into subqueries in WITH */
1674 foreach(lc, parsetree->cteList)
1676 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1678 cte->ctequery = (Node *)
1679 fireRIRrules((Query *) cte->ctequery, activeRIRs, false);
1683 * Recurse into sublink subqueries, too. But we already did the ones in
1684 * the rtable and cteList.
1686 if (parsetree->hasSubLinks)
1687 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
1688 QTW_IGNORE_RC_SUBQUERIES);
1695 * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
1696 * qualification. This is used to generate suitable "else clauses" for
1697 * conditional INSTEAD rules. (Unfortunately we must use "x IS NOT TRUE",
1698 * not just "NOT x" which the planner is much smarter about, else we will
1699 * do the wrong thing when the qual evaluates to NULL.)
1701 * The rule_qual may contain references to OLD or NEW. OLD references are
1702 * replaced by references to the specified rt_index (the relation that the
1703 * rule applies to). NEW references are only possible for INSERT and UPDATE
1704 * queries on the relation itself, and so they should be replaced by copies
1705 * of the related entries in the query's own targetlist.
1708 CopyAndAddInvertedQual(Query *parsetree,
1713 /* Don't scribble on the passed qual (it's in the relcache!) */
1714 Node *new_qual = (Node *) copyObject(rule_qual);
1717 * In case there are subqueries in the qual, acquire necessary locks and
1718 * fix any deleted JOIN RTE entries. (This is somewhat redundant with
1719 * rewriteRuleAction, but not entirely ... consider restructuring so that
1720 * we only need to process the qual this way once.)
1722 (void) acquireLocksOnSubLinks(new_qual, NULL);
1724 /* Fix references to OLD */
1725 ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
1726 /* Fix references to NEW */
1727 if (event == CMD_INSERT || event == CMD_UPDATE)
1728 new_qual = ReplaceVarsFromTargetList(new_qual,
1733 parsetree->targetList,
1734 (event == CMD_UPDATE) ?
1735 REPLACEVARS_CHANGE_VARNO :
1736 REPLACEVARS_SUBSTITUTE_NULL,
1738 &parsetree->hasSubLinks);
1739 /* And attach the fixed qual */
1740 AddInvertedQual(parsetree, new_qual);
1748 * Iterate through rule locks applying rules.
1751 * parsetree - original query
1752 * rt_index - RT index of result relation in original query
1753 * event - type of rule event
1754 * locks - list of rules to fire
1756 * *instead_flag - set TRUE if any unqualified INSTEAD rule is found
1757 * (must be initialized to FALSE)
1758 * *returning_flag - set TRUE if we rewrite RETURNING clause in any rule
1759 * (must be initialized to FALSE)
1760 * *qual_product - filled with modified original query if any qualified
1761 * INSTEAD rule is found (must be initialized to NULL)
1763 * list of rule actions adjusted for use with this query
1765 * Qualified INSTEAD rules generate their action with the qualification
1766 * condition added. They also generate a modified version of the original
1767 * query with the negated qualification added, so that it will run only for
1768 * rows that the qualified action doesn't act on. (If there are multiple
1769 * qualified INSTEAD rules, we AND all the negated quals onto a single
1770 * modified original query.) We won't execute the original, unmodified
1771 * query if we find either qualified or unqualified INSTEAD rules. If
1772 * we find both, the modified original query is discarded too.
1775 fireRules(Query *parsetree,
1780 bool *returning_flag,
1781 Query **qual_product)
1783 List *results = NIL;
1788 RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
1789 Node *event_qual = rule_lock->qual;
1790 List *actions = rule_lock->actions;
1794 /* Determine correct QuerySource value for actions */
1795 if (rule_lock->isInstead)
1797 if (event_qual != NULL)
1798 qsrc = QSRC_QUAL_INSTEAD_RULE;
1801 qsrc = QSRC_INSTEAD_RULE;
1802 *instead_flag = true; /* report unqualified INSTEAD */
1806 qsrc = QSRC_NON_INSTEAD_RULE;
1808 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
1811 * If there are INSTEAD rules with qualifications, the original
1812 * query is still performed. But all the negated rule
1813 * qualifications of the INSTEAD rules are added so it does its
1814 * actions only in cases where the rule quals of all INSTEAD rules
1815 * are false. Think of it as the default action in a case. We save
1816 * this in *qual_product so RewriteQuery() can add it to the query
1817 * list after we mangled it up enough.
1819 * If we have already found an unqualified INSTEAD rule, then
1820 * *qual_product won't be used, so don't bother building it.
1824 if (*qual_product == NULL)
1825 *qual_product = copyObject(parsetree);
1826 *qual_product = CopyAndAddInvertedQual(*qual_product,
1833 /* Now process the rule's actions and add them to the result list */
1836 Query *rule_action = lfirst(r);
1838 if (rule_action->commandType == CMD_NOTHING)
1841 rule_action = rewriteRuleAction(parsetree, rule_action,
1842 event_qual, rt_index, event,
1845 rule_action->querySource = qsrc;
1846 rule_action->canSetTag = false; /* might change later */
1848 results = lappend(results, rule_action);
1857 * get_view_query - get the Query from a view's _RETURN rule.
1859 * Caller should have verified that the relation is a view, and therefore
1860 * we should find an ON SELECT action.
1863 get_view_query(Relation view)
1867 Assert(view->rd_rel->relkind == RELKIND_VIEW);
1869 for (i = 0; i < view->rd_rules->numLocks; i++)
1871 RewriteRule *rule = view->rd_rules->rules[i];
1873 if (rule->event == CMD_SELECT)
1875 /* A _RETURN rule should have only one action */
1876 if (list_length(rule->actions) != 1)
1877 elog(ERROR, "invalid _RETURN rule action specification");
1879 return (Query *) linitial(rule->actions);
1883 elog(ERROR, "failed to find _RETURN rule for view");
1884 return NULL; /* keep compiler quiet */
1889 * view_has_instead_trigger - does view have an INSTEAD OF trigger for event?
1891 * If it does, we don't want to treat it as auto-updatable. This test can't
1892 * be folded into view_query_is_auto_updatable because it's not an error
1896 view_has_instead_trigger(Relation view, CmdType event)
1898 TriggerDesc *trigDesc = view->trigdesc;
1903 if (trigDesc && trigDesc->trig_insert_instead_row)
1907 if (trigDesc && trigDesc->trig_update_instead_row)
1911 if (trigDesc && trigDesc->trig_delete_instead_row)
1915 elog(ERROR, "unrecognized CmdType: %d", (int) event);
1923 * view_col_is_auto_updatable - test whether the specified column of a view
1924 * is auto-updatable. Returns NULL (if the column can be updated) or a message
1925 * string giving the reason that it cannot be.
1927 * Note that the checks performed here are local to this view. We do not check
1928 * whether the referenced column of the underlying base relation is updatable.
1931 view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
1933 Var *var = (Var *) tle->expr;
1936 * For now, the only updatable columns we support are those that are Vars
1937 * referring to user columns of the underlying base relation.
1939 * The view targetlist may contain resjunk columns (e.g., a view defined
1940 * like "SELECT * FROM t ORDER BY a+b" is auto-updatable) but such columns
1941 * are not auto-updatable, and in fact should never appear in the outer
1942 * query's targetlist.
1945 return gettext_noop("Junk view columns are not updatable.");
1947 if (!IsA(var, Var) ||
1948 var->varno != rtr->rtindex ||
1949 var->varlevelsup != 0)
1950 return gettext_noop("View columns that are not columns of their base relation are not updatable.");
1952 if (var->varattno < 0)
1953 return gettext_noop("View columns that refer to system columns are not updatable.");
1955 if (var->varattno == 0)
1956 return gettext_noop("View columns that return whole-row references are not updatable.");
1958 return NULL; /* the view column is updatable */
1963 * view_query_is_auto_updatable - test whether the specified view definition
1964 * represents an auto-updatable view. Returns NULL (if the view can be updated)
1965 * or a message string giving the reason that it cannot be.
1967 * If check_cols is true, the view is required to have at least one updatable
1968 * column (necessary for INSERT/UPDATE). Otherwise the view's columns are not
1969 * checked for updatability. See also view_cols_are_auto_updatable.
1971 * Note that the checks performed here are only based on the view definition.
1972 * We do not check whether any base relations referred to by the view are
1976 view_query_is_auto_updatable(Query *viewquery, bool security_barrier,
1980 RangeTblEntry *base_rte;
1983 * Check if the view is simply updatable. According to SQL-92 this means:
1984 * - No DISTINCT clause.
1985 * - Each TLE is a column reference, and each column appears at most once.
1986 * - FROM contains exactly one base relation.
1987 * - No GROUP BY or HAVING clauses.
1988 * - No set operations (UNION, INTERSECT or EXCEPT).
1989 * - No sub-queries in the WHERE clause that reference the target table.
1991 * We ignore that last restriction since it would be complex to enforce
1992 * and there isn't any actual benefit to disallowing sub-queries. (The
1993 * semantic issues that the standard is presumably concerned about don't
1994 * arise in Postgres, since any such sub-query will not see any updates
1995 * executed by the outer query anyway, thanks to MVCC snapshotting.)
1997 * We also relax the second restriction by supporting part of SQL:1999
1998 * feature T111, which allows for a mix of updatable and non-updatable
1999 * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2000 * a non-updatable column.
2002 * In addition we impose these constraints, involving features that are
2003 * not part of SQL-92:
2004 * - No CTEs (WITH clauses).
2005 * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2006 * - No system columns (including whole-row references) in the tlist.
2007 * - No window functions in the tlist.
2008 * - No set-returning functions in the tlist.
2010 * Note that we do these checks without recursively expanding the view.
2011 * If the base relation is a view, we'll recursively deal with it later.
2014 if (viewquery->distinctClause != NIL)
2015 return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2017 if (viewquery->groupClause != NIL)
2018 return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2020 if (viewquery->havingQual != NULL)
2021 return gettext_noop("Views containing HAVING are not automatically updatable.");
2023 if (viewquery->setOperations != NULL)
2024 return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2026 if (viewquery->cteList != NIL)
2027 return gettext_noop("Views containing WITH are not automatically updatable.");
2029 if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2030 return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2033 * We must not allow window functions or set returning functions in the
2034 * targetlist. Otherwise we might end up inserting them into the quals of
2035 * the main query. We must also check for aggregates in the targetlist in
2036 * case they appear without a GROUP BY.
2038 * These restrictions ensure that each row of the view corresponds to a
2039 * unique row in the underlying base relation.
2041 if (viewquery->hasAggs)
2042 return gettext_noop("Views that return aggregate functions are not automatically updatable");
2044 if (viewquery->hasWindowFuncs)
2045 return gettext_noop("Views that return window functions are not automatically updatable");
2047 if (expression_returns_set((Node *) viewquery->targetList))
2048 return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2051 * For now, we also don't support security-barrier views, because of the
2052 * difficulty of keeping upper-level qual expressions away from
2053 * lower-level data. This might get relaxed in the future.
2055 if (security_barrier)
2056 return gettext_noop("Security-barrier views are not automatically updatable.");
2059 * The view query should select from a single base relation, which must be
2060 * a table or another view.
2062 if (list_length(viewquery->jointree->fromlist) != 1)
2063 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2065 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2066 if (!IsA(rtr, RangeTblRef))
2067 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2069 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2070 if (base_rte->rtekind != RTE_RELATION ||
2071 (base_rte->relkind != RELKIND_RELATION &&
2072 base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2073 base_rte->relkind != RELKIND_VIEW))
2074 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2077 * Check that the view has at least one updatable column. This is required
2078 * for INSERT/UPDATE but not for DELETE.
2086 foreach(cell, viewquery->targetList)
2088 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2090 if (view_col_is_auto_updatable(rtr, tle) == NULL)
2098 return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2101 return NULL; /* the view is updatable */
2106 * view_cols_are_auto_updatable - test whether all of the required columns of
2107 * an auto-updatable view are actually updatable. Returns NULL (if all the
2108 * required columns can be updated) or a message string giving the reason that
2111 * This should be used for INSERT/UPDATE to ensure that we don't attempt to
2112 * assign to any non-updatable columns.
2114 * Additionally it may be used to retrieve the set of updatable columns in the
2115 * view, or if one or more of the required columns is not updatable, the name
2116 * of the first offending non-updatable column.
2118 * The caller must have already verified that this is an auto-updatable view
2119 * using view_query_is_auto_updatable.
2121 * Note that the checks performed here are only based on the view definition.
2122 * We do not check whether the referenced columns of the base relation are
2126 view_cols_are_auto_updatable(Query *viewquery,
2127 Bitmapset *required_cols,
2128 Bitmapset **updatable_cols,
2129 char **non_updatable_col)
2136 * The caller should have verified that this view is auto-updatable and
2137 * so there should be a single base relation.
2139 Assert(list_length(viewquery->jointree->fromlist) == 1);
2140 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2141 Assert(IsA(rtr, RangeTblRef));
2143 /* Initialize the optional return values */
2144 if (updatable_cols != NULL)
2145 *updatable_cols = NULL;
2146 if (non_updatable_col != NULL)
2147 *non_updatable_col = NULL;
2149 /* Test each view column for updatability */
2150 col = -FirstLowInvalidHeapAttributeNumber;
2151 foreach(cell, viewquery->targetList)
2153 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2154 const char *col_update_detail;
2157 col_update_detail = view_col_is_auto_updatable(rtr, tle);
2159 if (col_update_detail == NULL)
2161 /* The column is updatable */
2162 if (updatable_cols != NULL)
2163 *updatable_cols = bms_add_member(*updatable_cols, col);
2165 else if (bms_is_member(col, required_cols))
2167 /* The required column is not updatable */
2168 if (non_updatable_col != NULL)
2169 *non_updatable_col = tle->resname;
2170 return col_update_detail;
2174 return NULL; /* all the required view columns are updatable */
2179 * relation_is_updatable - determine which update events the specified
2180 * relation supports.
2182 * Note that views may contain a mix of updatable and non-updatable columns.
2183 * For a view to support INSERT/UPDATE it must have at least one updatable
2184 * column, but there is no such restriction for DELETE. If include_cols is
2185 * non-NULL, then only the specified columns are considered when testing for
2188 * This is used for the information_schema views, which have separate concepts
2189 * of "updatable" and "trigger updatable". A relation is "updatable" if it
2190 * can be updated without the need for triggers (either because it has a
2191 * suitable RULE, or because it is simple enough to be automatically updated).
2192 * A relation is "trigger updatable" if it has a suitable INSTEAD OF trigger.
2193 * The SQL standard regards this as not necessarily updatable, presumably
2194 * because there is no way of knowing what the trigger will actually do.
2195 * The information_schema views therefore call this function with
2196 * include_triggers = false. However, other callers might only care whether
2197 * data-modifying SQL will work, so they can pass include_triggers = true
2198 * to have trigger updatability included in the result.
2200 * The return value is a bitmask of rule event numbers indicating which of
2201 * the INSERT, UPDATE and DELETE operations are supported. (We do it this way
2202 * so that we can test for UPDATE plus DELETE support in a single call.)
2205 relation_is_updatable(Oid reloid,
2206 bool include_triggers,
2207 Bitmapset *include_cols)
2211 RuleLock *rulelocks;
2213 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2215 rel = try_relation_open(reloid, AccessShareLock);
2218 * If the relation doesn't exist, return zero rather than throwing an
2219 * error. This is helpful since scanning an information_schema view under
2220 * MVCC rules can result in referencing rels that have actually been
2226 /* If the relation is a table, it is always updatable */
2227 if (rel->rd_rel->relkind == RELKIND_RELATION)
2229 relation_close(rel, AccessShareLock);
2233 /* Look for unconditional DO INSTEAD rules, and note supported events */
2234 rulelocks = rel->rd_rules;
2235 if (rulelocks != NULL)
2239 for (i = 0; i < rulelocks->numLocks; i++)
2241 if (rulelocks->rules[i]->isInstead &&
2242 rulelocks->rules[i]->qual == NULL)
2244 events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2248 /* If we have rules for all events, we're done */
2249 if (events == ALL_EVENTS)
2251 relation_close(rel, AccessShareLock);
2256 /* Similarly look for INSTEAD OF triggers, if they are to be included */
2257 if (include_triggers)
2259 TriggerDesc *trigDesc = rel->trigdesc;
2263 if (trigDesc->trig_insert_instead_row)
2264 events |= (1 << CMD_INSERT);
2265 if (trigDesc->trig_update_instead_row)
2266 events |= (1 << CMD_UPDATE);
2267 if (trigDesc->trig_delete_instead_row)
2268 events |= (1 << CMD_DELETE);
2270 /* If we have triggers for all events, we're done */
2271 if (events == ALL_EVENTS)
2273 relation_close(rel, AccessShareLock);
2279 /* If this is a foreign table, check which update events it supports */
2280 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2282 FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2284 if (fdwroutine->IsForeignRelUpdatable != NULL)
2285 events |= fdwroutine->IsForeignRelUpdatable(rel);
2288 /* Assume presence of executor functions is sufficient */
2289 if (fdwroutine->ExecForeignInsert != NULL)
2290 events |= (1 << CMD_INSERT);
2291 if (fdwroutine->ExecForeignUpdate != NULL)
2292 events |= (1 << CMD_UPDATE);
2293 if (fdwroutine->ExecForeignDelete != NULL)
2294 events |= (1 << CMD_DELETE);
2297 relation_close(rel, AccessShareLock);
2301 /* Check if this is an automatically updatable view */
2302 if (rel->rd_rel->relkind == RELKIND_VIEW)
2304 Query *viewquery = get_view_query(rel);
2306 if (view_query_is_auto_updatable(viewquery,
2307 RelationIsSecurityView(rel),
2310 Bitmapset *updatable_cols;
2313 RangeTblEntry *base_rte;
2317 * Determine which of the view's columns are updatable. If there
2318 * are none within the set of of columns we are looking at, then
2319 * the view doesn't support INSERT/UPDATE, but it may still
2322 view_cols_are_auto_updatable(viewquery, NULL,
2323 &updatable_cols, NULL);
2325 if (include_cols != NULL)
2326 updatable_cols = bms_int_members(updatable_cols, include_cols);
2328 if (bms_is_empty(updatable_cols))
2329 auto_events = (1 << CMD_DELETE); /* May support DELETE */
2331 auto_events = ALL_EVENTS; /* May support all events */
2334 * The base relation must also support these update commands.
2335 * Tables are always updatable, but for any other kind of base
2336 * relation we must do a recursive check limited to the columns
2337 * referenced by the locally updatable columns in this view.
2339 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2340 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2341 Assert(base_rte->rtekind == RTE_RELATION);
2343 if (base_rte->relkind != RELKIND_RELATION)
2345 baseoid = base_rte->relid;
2346 include_cols = adjust_view_column_set(updatable_cols,
2347 viewquery->targetList);
2348 auto_events &= relation_is_updatable(baseoid,
2352 events |= auto_events;
2356 /* If we reach here, the relation may support some update commands */
2357 relation_close(rel, AccessShareLock);
2363 * adjust_view_column_set - map a set of column numbers according to targetlist
2365 * This is used with simply-updatable views to map column-permissions sets for
2366 * the view columns onto the matching columns in the underlying base relation.
2367 * The targetlist is expected to be a list of plain Vars of the underlying
2368 * relation (as per the checks above in view_query_is_auto_updatable).
2371 adjust_view_column_set(Bitmapset *cols, List *targetlist)
2373 Bitmapset *result = NULL;
2377 tmpcols = bms_copy(cols);
2378 while ((col = bms_first_member(tmpcols)) >= 0)
2380 /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
2381 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
2383 if (attno == InvalidAttrNumber)
2386 * There's a whole-row reference to the view. For permissions
2387 * purposes, treat it as a reference to each column available from
2388 * the view. (We should *not* convert this to a whole-row
2389 * reference to the base relation, since the view may not touch
2390 * all columns of the base relation.)
2394 foreach(lc, targetlist)
2396 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2401 var = (Var *) tle->expr;
2402 Assert(IsA(var, Var));
2403 result = bms_add_member(result,
2404 var->varattno - FirstLowInvalidHeapAttributeNumber);
2410 * Views do not have system columns, so we do not expect to see
2411 * any other system attnos here. If we do find one, the error
2414 TargetEntry *tle = get_tle_by_resno(targetlist, attno);
2416 if (tle != NULL && !tle->resjunk && IsA(tle->expr, Var))
2418 Var *var = (Var *) tle->expr;
2420 result = bms_add_member(result,
2421 var->varattno - FirstLowInvalidHeapAttributeNumber);
2424 elog(ERROR, "attribute number %d not found in view targetlist",
2435 * rewriteTargetView -
2436 * Attempt to rewrite a query where the target relation is a view, so that
2437 * the view's base relation becomes the target relation.
2439 * Note that the base relation here may itself be a view, which may or may not
2440 * have INSTEAD OF triggers or rules to handle the update. That is handled by
2441 * the recursion in RewriteQuery.
2444 rewriteTargetView(Query *parsetree, Relation view)
2447 const char *auto_update_detail;
2451 RangeTblEntry *base_rte;
2452 RangeTblEntry *view_rte;
2453 RangeTblEntry *new_rte;
2455 List *view_targetlist;
2458 /* The view must be updatable, else fail */
2459 viewquery = get_view_query(view);
2461 auto_update_detail =
2462 view_query_is_auto_updatable(viewquery,
2463 RelationIsSecurityView(view),
2464 parsetree->commandType != CMD_DELETE);
2466 if (auto_update_detail)
2468 /* messages here should match execMain.c's CheckValidResultRel */
2469 switch (parsetree->commandType)
2473 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2474 errmsg("cannot insert into view \"%s\"",
2475 RelationGetRelationName(view)),
2476 errdetail_internal("%s", _(auto_update_detail)),
2477 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
2481 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2482 errmsg("cannot update view \"%s\"",
2483 RelationGetRelationName(view)),
2484 errdetail_internal("%s", _(auto_update_detail)),
2485 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
2489 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2490 errmsg("cannot delete from view \"%s\"",
2491 RelationGetRelationName(view)),
2492 errdetail_internal("%s", _(auto_update_detail)),
2493 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
2496 elog(ERROR, "unrecognized CmdType: %d",
2497 (int) parsetree->commandType);
2503 * For INSERT/UPDATE the modified columns must all be updatable. Note that
2504 * we get the modified columns from the query's targetlist, not from the
2505 * result RTE's modifiedCols set, since rewriteTargetListIU may have added
2506 * additional targetlist entries for view defaults, and these must also be
2509 if (parsetree->commandType != CMD_DELETE)
2511 Bitmapset *modified_cols = NULL;
2512 char *non_updatable_col;
2514 foreach(lc, parsetree->targetList)
2516 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2519 modified_cols = bms_add_member(modified_cols,
2520 tle->resno - FirstLowInvalidHeapAttributeNumber);
2523 auto_update_detail = view_cols_are_auto_updatable(viewquery,
2526 &non_updatable_col);
2527 if (auto_update_detail)
2530 * This is a different error, caused by an attempt to update a
2531 * non-updatable column in an otherwise updatable view.
2533 switch (parsetree->commandType)
2537 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2538 errmsg("cannot insert into column \"%s\" of view \"%s\"",
2540 RelationGetRelationName(view)),
2541 errdetail_internal("%s", _(auto_update_detail))));
2545 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2546 errmsg("cannot update column \"%s\" of view \"%s\"",
2548 RelationGetRelationName(view)),
2549 errdetail_internal("%s", _(auto_update_detail))));
2552 elog(ERROR, "unrecognized CmdType: %d",
2553 (int) parsetree->commandType);
2559 /* Locate RTE describing the view in the outer query */
2560 view_rte = rt_fetch(parsetree->resultRelation, parsetree->rtable);
2563 * If we get here, view_query_is_auto_updatable() has verified that the
2564 * view contains a single base relation.
2566 Assert(list_length(viewquery->jointree->fromlist) == 1);
2567 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2568 Assert(IsA(rtr, RangeTblRef));
2570 base_rt_index = rtr->rtindex;
2571 base_rte = rt_fetch(base_rt_index, viewquery->rtable);
2572 Assert(base_rte->rtekind == RTE_RELATION);
2575 * Up to now, the base relation hasn't been touched at all in our query.
2576 * We need to acquire lock on it before we try to do anything with it.
2577 * (The subsequent recursive call of RewriteQuery will suppose that we
2578 * already have the right lock!) Since it will become the query target
2579 * relation, RowExclusiveLock is always the right thing.
2581 base_rel = heap_open(base_rte->relid, RowExclusiveLock);
2584 * While we have the relation open, update the RTE's relkind, just in case
2585 * it changed since this view was made (cf. AcquireRewriteLocks).
2587 base_rte->relkind = base_rel->rd_rel->relkind;
2589 heap_close(base_rel, NoLock);
2592 * Create a new target RTE describing the base relation, and add it to the
2593 * outer query's rangetable. (What's happening in the next few steps is
2594 * very much like what the planner would do to "pull up" the view into the
2595 * outer query. Perhaps someday we should refactor things enough so that
2596 * we can share code with the planner.)
2598 new_rte = (RangeTblEntry *) copyObject(base_rte);
2599 parsetree->rtable = lappend(parsetree->rtable, new_rte);
2600 new_rt_index = list_length(parsetree->rtable);
2603 * INSERTs never inherit. For UPDATE/DELETE, we use the view query's
2604 * inheritance flag for the base relation.
2606 if (parsetree->commandType == CMD_INSERT)
2607 new_rte->inh = false;
2610 * Make a copy of the view's targetlist, adjusting its Vars to reference
2611 * the new target RTE, ie make their varnos be new_rt_index instead of
2612 * base_rt_index. There can be no Vars for other rels in the tlist, so
2613 * this is sufficient to pull up the tlist expressions for use in the
2614 * outer query. The tlist will provide the replacement expressions used
2615 * by ReplaceVarsFromTargetList below.
2617 view_targetlist = copyObject(viewquery->targetList);
2619 ChangeVarNodes((Node *) view_targetlist,
2625 * Mark the new target RTE for the permissions checks that we want to
2626 * enforce against the view owner, as distinct from the query caller. At
2627 * the relation level, require the same INSERT/UPDATE/DELETE permissions
2628 * that the query caller needs against the view. We drop the ACL_SELECT
2629 * bit that is presumably in new_rte->requiredPerms initially.
2631 * Note: the original view RTE remains in the query's rangetable list.
2632 * Although it will be unused in the query plan, we need it there so that
2633 * the executor still performs appropriate permissions checks for the
2634 * query caller's use of the view.
2636 new_rte->checkAsUser = view->rd_rel->relowner;
2637 new_rte->requiredPerms = view_rte->requiredPerms;
2640 * Now for the per-column permissions bits.
2642 * Initially, new_rte contains selectedCols permission check bits for all
2643 * base-rel columns referenced by the view, but since the view is a SELECT
2644 * query its modifiedCols is empty. We set modifiedCols to include all
2645 * the columns the outer query is trying to modify, adjusting the column
2646 * numbers as needed. But we leave selectedCols as-is, so the view owner
2647 * must have read permission for all columns used in the view definition,
2648 * even if some of them are not read by the outer query. We could try to
2649 * limit selectedCols to only columns used in the transformed query, but
2650 * that does not correspond to what happens in ordinary SELECT usage of a
2651 * view: all referenced columns must have read permission, even if
2652 * optimization finds that some of them can be discarded during query
2653 * transformation. The flattening we're doing here is an optional
2654 * optimization, too. (If you are unpersuaded and want to change this,
2655 * note that applying adjust_view_column_set to view_rte->selectedCols is
2656 * clearly *not* the right answer, since that neglects base-rel columns
2657 * used in the view's WHERE quals.)
2659 * This step needs the modified view targetlist, so we have to do things
2662 Assert(bms_is_empty(new_rte->modifiedCols));
2663 new_rte->modifiedCols = adjust_view_column_set(view_rte->modifiedCols,
2667 * For UPDATE/DELETE, rewriteTargetListUD will have added a wholerow junk
2668 * TLE for the view to the end of the targetlist, which we no longer need.
2669 * Remove it to avoid unnecessary work when we process the targetlist.
2670 * Note that when we recurse through rewriteQuery a new junk TLE will be
2671 * added to allow the executor to find the proper row in the new target
2672 * relation. (So, if we failed to do this, we might have multiple junk
2673 * TLEs with the same name, which would be disastrous.)
2675 if (parsetree->commandType != CMD_INSERT)
2677 TargetEntry *tle = (TargetEntry *) llast(parsetree->targetList);
2679 Assert(tle->resjunk);
2680 Assert(IsA(tle->expr, Var) &&
2681 ((Var *) tle->expr)->varno == parsetree->resultRelation &&
2682 ((Var *) tle->expr)->varattno == 0);
2683 parsetree->targetList = list_delete_ptr(parsetree->targetList, tle);
2687 * Now update all Vars in the outer query that reference the view to
2688 * reference the appropriate column of the base relation instead.
2690 parsetree = (Query *)
2691 ReplaceVarsFromTargetList((Node *) parsetree,
2692 parsetree->resultRelation,
2696 REPLACEVARS_REPORT_ERROR,
2698 &parsetree->hasSubLinks);
2701 * Update all other RTI references in the query that point to the view
2702 * (for example, parsetree->resultRelation itself) to point to the new
2703 * base relation instead. Vars will not be affected since none of them
2704 * reference parsetree->resultRelation any longer.
2706 ChangeVarNodes((Node *) parsetree,
2707 parsetree->resultRelation,
2710 Assert(parsetree->resultRelation == new_rt_index);
2713 * For INSERT/UPDATE we must also update resnos in the targetlist to refer
2714 * to columns of the base relation, since those indicate the target
2715 * columns to be affected.
2717 * Note that this destroys the resno ordering of the targetlist, but that
2718 * will be fixed when we recurse through rewriteQuery, which will invoke
2719 * rewriteTargetListIU again on the updated targetlist.
2721 if (parsetree->commandType != CMD_DELETE)
2723 foreach(lc, parsetree->targetList)
2725 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2726 TargetEntry *view_tle;
2731 view_tle = get_tle_by_resno(view_targetlist, tle->resno);
2732 if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
2733 tle->resno = ((Var *) view_tle->expr)->varattno;
2735 elog(ERROR, "attribute number %d not found in view targetlist",
2741 * For UPDATE/DELETE, pull up any WHERE quals from the view. We know that
2742 * any Vars in the quals must reference the one base relation, so we need
2743 * only adjust their varnos to reference the new target (just the same as
2744 * we did with the view targetlist).
2746 * For INSERT, the view's quals can be ignored in the main query.
2748 if (parsetree->commandType != CMD_INSERT &&
2749 viewquery->jointree->quals != NULL)
2751 Node *viewqual = (Node *) copyObject(viewquery->jointree->quals);
2753 ChangeVarNodes(viewqual, base_rt_index, new_rt_index, 0);
2754 AddQual(parsetree, (Node *) viewqual);
2758 * For INSERT/UPDATE, if the view has the WITH CHECK OPTION, or any parent
2759 * view specified WITH CASCADED CHECK OPTION, add the quals from the view
2760 * to the query's withCheckOptions list.
2762 if (parsetree->commandType != CMD_DELETE)
2764 bool has_wco = RelationHasCheckOption(view);
2765 bool cascaded = RelationHasCascadedCheckOption(view);
2768 * If the parent view has a cascaded check option, treat this view as
2769 * if it also had a cascaded check option.
2771 * New WithCheckOptions are added to the start of the list, so if there
2772 * is a cascaded check option, it will be the first item in the list.
2774 if (parsetree->withCheckOptions != NIL)
2776 WithCheckOption *parent_wco =
2777 (WithCheckOption *) linitial(parsetree->withCheckOptions);
2779 if (parent_wco->cascaded)
2787 * Add the new WithCheckOption to the start of the list, so that
2788 * checks on inner views are run before checks on outer views, as
2789 * required by the SQL standard.
2791 * If the new check is CASCADED, we need to add it even if this view
2792 * has no quals, since there may be quals on child views. A LOCAL
2793 * check can be omitted if this view has no quals.
2795 if (has_wco && (cascaded || viewquery->jointree->quals != NULL))
2797 WithCheckOption *wco;
2799 wco = makeNode(WithCheckOption);
2800 wco->viewname = pstrdup(RelationGetRelationName(view));
2802 wco->cascaded = cascaded;
2804 parsetree->withCheckOptions = lcons(wco,
2805 parsetree->withCheckOptions);
2807 if (viewquery->jointree->quals != NULL)
2809 wco->qual = (Node *) copyObject(viewquery->jointree->quals);
2810 ChangeVarNodes(wco->qual, base_rt_index, new_rt_index, 0);
2813 * Make sure that the query is marked correctly if the added
2814 * qual has sublinks. We can skip this check if the query is
2815 * already marked, or if the command is an UPDATE, in which
2816 * case the same qual will have already been added to the
2817 * query's WHERE clause, and AddQual will have already done
2820 if (!parsetree->hasSubLinks &&
2821 parsetree->commandType != CMD_UPDATE)
2822 parsetree->hasSubLinks = checkExprHasSubLink(wco->qual);
2833 * rewrites the query and apply the rules again on the queries rewritten
2835 * rewrite_events is a list of open query-rewrite actions, so we can detect
2836 * infinite recursion.
2839 RewriteQuery(Query *parsetree, List *rewrite_events)
2841 CmdType event = parsetree->commandType;
2842 bool instead = false;
2843 bool returning = false;
2844 Query *qual_product = NULL;
2845 List *rewritten = NIL;
2849 * First, recursively process any insert/update/delete statements in WITH
2850 * clauses. (We have to do this first because the WITH clauses may get
2851 * copied into rule actions below.)
2853 foreach(lc1, parsetree->cteList)
2855 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc1);
2856 Query *ctequery = (Query *) cte->ctequery;
2859 Assert(IsA(ctequery, Query));
2861 if (ctequery->commandType == CMD_SELECT)
2864 newstuff = RewriteQuery(ctequery, rewrite_events);
2867 * Currently we can only handle unconditional, single-statement DO
2868 * INSTEAD rules correctly; we have to get exactly one Query out of
2869 * the rewrite operation to stuff back into the CTE node.
2871 if (list_length(newstuff) == 1)
2873 /* Push the single Query back into the CTE node */
2874 ctequery = (Query *) linitial(newstuff);
2875 Assert(IsA(ctequery, Query));
2876 /* WITH queries should never be canSetTag */
2877 Assert(!ctequery->canSetTag);
2878 cte->ctequery = (Node *) ctequery;
2880 else if (newstuff == NIL)
2883 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2884 errmsg("DO INSTEAD NOTHING rules are not supported for data-modifying statements in WITH")));
2890 /* examine queries to determine which error message to issue */
2891 foreach(lc2, newstuff)
2893 Query *q = (Query *) lfirst(lc2);
2895 if (q->querySource == QSRC_QUAL_INSTEAD_RULE)
2897 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2898 errmsg("conditional DO INSTEAD rules are not supported for data-modifying statements in WITH")));
2899 if (q->querySource == QSRC_NON_INSTEAD_RULE)
2901 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2902 errmsg("DO ALSO rules are not supported for data-modifying statements in WITH")));
2906 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2907 errmsg("multi-statement DO INSTEAD rules are not supported for data-modifying statements in WITH")));
2912 * If the statement is an insert, update, or delete, adjust its targetlist
2913 * as needed, and then fire INSERT/UPDATE/DELETE rules on it.
2915 * SELECT rules are handled later when we have all the queries that should
2916 * get executed. Also, utilities aren't rewritten at all (do we still
2919 if (event != CMD_SELECT && event != CMD_UTILITY)
2921 int result_relation;
2922 RangeTblEntry *rt_entry;
2923 Relation rt_entry_relation;
2925 List *product_queries;
2927 result_relation = parsetree->resultRelation;
2928 Assert(result_relation != 0);
2929 rt_entry = rt_fetch(result_relation, parsetree->rtable);
2930 Assert(rt_entry->rtekind == RTE_RELATION);
2933 * We can use NoLock here since either the parser or
2934 * AcquireRewriteLocks should have locked the rel already.
2936 rt_entry_relation = heap_open(rt_entry->relid, NoLock);
2939 * Rewrite the targetlist as needed for the command type.
2941 if (event == CMD_INSERT)
2943 RangeTblEntry *values_rte = NULL;
2946 * If it's an INSERT ... VALUES (...), (...), ... there will be a
2947 * single RTE for the VALUES targetlists.
2949 if (list_length(parsetree->jointree->fromlist) == 1)
2951 RangeTblRef *rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
2953 if (IsA(rtr, RangeTblRef))
2955 RangeTblEntry *rte = rt_fetch(rtr->rtindex,
2958 if (rte->rtekind == RTE_VALUES)
2967 /* Process the main targetlist ... */
2968 rewriteTargetListIU(parsetree, rt_entry_relation, &attrnos);
2969 /* ... and the VALUES expression lists */
2970 rewriteValuesRTE(values_rte, rt_entry_relation, attrnos);
2974 /* Process just the main targetlist */
2975 rewriteTargetListIU(parsetree, rt_entry_relation, NULL);
2978 else if (event == CMD_UPDATE)
2980 rewriteTargetListIU(parsetree, rt_entry_relation, NULL);
2981 rewriteTargetListUD(parsetree, rt_entry, rt_entry_relation);
2983 else if (event == CMD_DELETE)
2985 rewriteTargetListUD(parsetree, rt_entry, rt_entry_relation);
2988 elog(ERROR, "unrecognized commandType: %d", (int) event);
2991 * Collect and apply the appropriate rules.
2993 locks = matchLocks(event, rt_entry_relation->rd_rules,
2994 result_relation, parsetree);
2996 product_queries = fireRules(parsetree,
3005 * If there were no INSTEAD rules, and the target relation is a view
3006 * without any INSTEAD OF triggers, see if the view can be
3007 * automatically updated. If so, we perform the necessary query
3008 * transformation here and add the resulting query to the
3009 * product_queries list, so that it gets recursively rewritten if
3012 if (!instead && qual_product == NULL &&
3013 rt_entry_relation->rd_rel->relkind == RELKIND_VIEW &&
3014 !view_has_instead_trigger(rt_entry_relation, event))
3017 * This throws an error if the view can't be automatically
3018 * updated, but that's OK since the query would fail at runtime
3021 parsetree = rewriteTargetView(parsetree, rt_entry_relation);
3024 * At this point product_queries contains any DO ALSO rule
3025 * actions. Add the rewritten query before or after those. This
3026 * must match the handling the original query would have gotten
3027 * below, if we allowed it to be included again.
3029 if (parsetree->commandType == CMD_INSERT)
3030 product_queries = lcons(parsetree, product_queries);
3032 product_queries = lappend(product_queries, parsetree);
3035 * Set the "instead" flag, as if there had been an unqualified
3036 * INSTEAD, to prevent the original query from being included a
3037 * second time below. The transformation will have rewritten any
3038 * RETURNING list, so we can also set "returning" to forestall
3039 * throwing an error below.
3046 * If we got any product queries, recursively rewrite them --- but
3047 * first check for recursion!
3049 if (product_queries != NIL)
3054 foreach(n, rewrite_events)
3056 rev = (rewrite_event *) lfirst(n);
3057 if (rev->relation == RelationGetRelid(rt_entry_relation) &&
3058 rev->event == event)
3060 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3061 errmsg("infinite recursion detected in rules for relation \"%s\"",
3062 RelationGetRelationName(rt_entry_relation))));
3065 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
3066 rev->relation = RelationGetRelid(rt_entry_relation);
3068 rewrite_events = lcons(rev, rewrite_events);
3070 foreach(n, product_queries)
3072 Query *pt = (Query *) lfirst(n);
3075 newstuff = RewriteQuery(pt, rewrite_events);
3076 rewritten = list_concat(rewritten, newstuff);
3079 rewrite_events = list_delete_first(rewrite_events);
3083 * If there is an INSTEAD, and the original query has a RETURNING, we
3084 * have to have found a RETURNING in the rule(s), else fail. (Because
3085 * DefineQueryRewrite only allows RETURNING in unconditional INSTEAD
3086 * rules, there's no need to worry whether the substituted RETURNING
3087 * will actually be executed --- it must be.)
3089 if ((instead || qual_product != NULL) &&
3090 parsetree->returningList &&
3097 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3098 errmsg("cannot perform INSERT RETURNING on relation \"%s\"",
3099 RelationGetRelationName(rt_entry_relation)),
3100 errhint("You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.")));
3104 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3105 errmsg("cannot perform UPDATE RETURNING on relation \"%s\"",
3106 RelationGetRelationName(rt_entry_relation)),
3107 errhint("You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.")));
3111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3112 errmsg("cannot perform DELETE RETURNING on relation \"%s\"",
3113 RelationGetRelationName(rt_entry_relation)),
3114 errhint("You need an unconditional ON DELETE DO INSTEAD rule with a RETURNING clause.")));
3117 elog(ERROR, "unrecognized commandType: %d",
3123 heap_close(rt_entry_relation, NoLock);
3127 * For INSERTs, the original query is done first; for UPDATE/DELETE, it is
3128 * done last. This is needed because update and delete rule actions might
3129 * not do anything if they are invoked after the update or delete is
3130 * performed. The command counter increment between the query executions
3131 * makes the deleted (and maybe the updated) tuples disappear so the scans
3132 * for them in the rule actions cannot find them.
3134 * If we found any unqualified INSTEAD, the original query is not done at
3135 * all, in any form. Otherwise, we add the modified form if qualified
3136 * INSTEADs were found, else the unmodified form.
3140 if (parsetree->commandType == CMD_INSERT)
3142 if (qual_product != NULL)
3143 rewritten = lcons(qual_product, rewritten);
3145 rewritten = lcons(parsetree, rewritten);
3149 if (qual_product != NULL)
3150 rewritten = lappend(rewritten, qual_product);
3152 rewritten = lappend(rewritten, parsetree);
3157 * If the original query has a CTE list, and we generated more than one
3158 * non-utility result query, we have to fail because we'll have copied the
3159 * CTE list into each result query. That would break the expectation of
3160 * single evaluation of CTEs. This could possibly be fixed by
3161 * restructuring so that a CTE list can be shared across multiple Query
3162 * and PlannableStatement nodes.
3164 if (parsetree->cteList != NIL)
3168 foreach(lc1, rewritten)
3170 Query *q = (Query *) lfirst(lc1);
3172 if (q->commandType != CMD_UTILITY)
3177 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3178 errmsg("WITH cannot be used in a query that is rewritten by rules into multiple queries")));
3187 * Primary entry point to the query rewriter.
3188 * Rewrite one query via query rewrite system, possibly returning 0
3191 * NOTE: the parsetree must either have come straight from the parser,
3192 * or have been scanned by AcquireRewriteLocks to acquire suitable locks.
3195 QueryRewrite(Query *parsetree)
3197 uint32 input_query_id = parsetree->queryId;
3201 CmdType origCmdType;
3202 bool foundOriginalQuery;
3206 * This function is only applied to top-level original queries
3208 Assert(parsetree->querySource == QSRC_ORIGINAL);
3209 Assert(parsetree->canSetTag);
3214 * Apply all non-SELECT rules possibly getting 0 or many queries
3216 querylist = RewriteQuery(parsetree, NIL);
3221 * Apply all the RIR rules on each query
3223 * This is also a handy place to mark each query with the original queryId
3226 foreach(l, querylist)
3228 Query *query = (Query *) lfirst(l);
3230 query = fireRIRrules(query, NIL, false);
3232 query->queryId = input_query_id;
3234 results = lappend(results, query);
3240 * Determine which, if any, of the resulting queries is supposed to set
3241 * the command-result tag; and update the canSetTag fields accordingly.
3243 * If the original query is still in the list, it sets the command tag.
3244 * Otherwise, the last INSTEAD query of the same kind as the original is
3245 * allowed to set the tag. (Note these rules can leave us with no query
3246 * setting the tag. The tcop code has to cope with this by setting up a
3247 * default tag based on the original un-rewritten query.)
3249 * The Asserts verify that at most one query in the result list is marked
3250 * canSetTag. If we aren't checking asserts, we can fall out of the loop
3251 * as soon as we find the original query.
3253 origCmdType = parsetree->commandType;
3254 foundOriginalQuery = false;
3259 Query *query = (Query *) lfirst(l);
3261 if (query->querySource == QSRC_ORIGINAL)
3263 Assert(query->canSetTag);
3264 Assert(!foundOriginalQuery);
3265 foundOriginalQuery = true;
3266 #ifndef USE_ASSERT_CHECKING
3272 Assert(!query->canSetTag);
3273 if (query->commandType == origCmdType &&
3274 (query->querySource == QSRC_INSTEAD_RULE ||
3275 query->querySource == QSRC_QUAL_INSTEAD_RULE))
3276 lastInstead = query;
3280 if (!foundOriginalQuery && lastInstead != NULL)
3281 lastInstead->canSetTag = true;