1 /*-------------------------------------------------------------------------
4 * Primary module of query rewriter.
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/rewrite/rewriteHandler.c
13 * Some of the terms used in this file are of historic nature: "retrieve"
14 * was the PostQUEL keyword for what today is SELECT. "RIR" stands for
15 * "Retrieve-Instead-Retrieve", that is an ON SELECT DO INSTEAD SELECT rule
16 * (which has to be unconditional and where only one rule can exist on each
19 *-------------------------------------------------------------------------
23 #include "access/sysattr.h"
24 #include "catalog/dependency.h"
25 #include "catalog/pg_type.h"
26 #include "commands/trigger.h"
27 #include "foreign/fdwapi.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "parser/analyze.h"
31 #include "parser/parse_coerce.h"
32 #include "parser/parsetree.h"
33 #include "rewrite/rewriteDefine.h"
34 #include "rewrite/rewriteHandler.h"
35 #include "rewrite/rewriteManip.h"
36 #include "rewrite/rowsecurity.h"
37 #include "utils/builtins.h"
38 #include "utils/lsyscache.h"
39 #include "utils/rel.h"
42 /* We use a list of these to detect recursion in RewriteQuery */
43 typedef struct rewrite_event
45 Oid relation; /* OID of relation having rules */
46 CmdType event; /* type of rule being fired */
49 typedef struct acquireLocksOnSubLinks_context
51 bool for_execute; /* AcquireRewriteLocks' forExecute param */
52 } acquireLocksOnSubLinks_context;
54 static bool acquireLocksOnSubLinks(Node *node,
55 acquireLocksOnSubLinks_context *context);
56 static Query *rewriteRuleAction(Query *parsetree,
61 bool *returning_flag);
62 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
63 static List *rewriteTargetListIU(List *targetList,
65 OverridingKind override,
66 Relation target_relation,
69 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
70 TargetEntry *prior_tle,
71 const char *attrName);
72 static Node *get_assignment_input(Node *node);
73 static void rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation,
75 static void rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
76 Relation target_relation);
77 static void markQueryForLocking(Query *qry, Node *jtnode,
78 LockClauseStrength strength, LockWaitPolicy waitPolicy,
80 static List *matchLocks(CmdType event, RuleLock *rulelocks,
81 int varno, Query *parsetree, bool *hasUpdate);
82 static Query *fireRIRrules(Query *parsetree, List *activeRIRs,
83 bool forUpdatePushedDown);
84 static bool view_has_instead_trigger(Relation view, CmdType event);
85 static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist);
89 * AcquireRewriteLocks -
90 * Acquire suitable locks on all the relations mentioned in the Query.
91 * These locks will ensure that the relation schemas don't change under us
92 * while we are rewriting and planning the query.
94 * forExecute indicates that the query is about to be executed.
95 * If so, we'll acquire RowExclusiveLock on the query's resultRelation,
96 * RowShareLock on any relation accessed FOR [KEY] UPDATE/SHARE, and
97 * AccessShareLock on all other relations mentioned.
99 * If forExecute is false, AccessShareLock is acquired on all relations.
100 * This case is suitable for ruleutils.c, for example, where we only need
101 * schema stability and we don't intend to actually modify any relations.
103 * forUpdatePushedDown indicates that a pushed-down FOR [KEY] UPDATE/SHARE
104 * applies to the current subquery, requiring all rels to be opened with at
105 * least RowShareLock. This should always be false at the top of the
106 * recursion. This flag is ignored if forExecute is false.
108 * A secondary purpose of this routine is to fix up JOIN RTE references to
109 * dropped columns (see details below). Because the RTEs are modified in
110 * place, it is generally appropriate for the caller of this routine to have
111 * first done a copyObject() to make a writable copy of the querytree in the
112 * current memory context.
114 * This processing can, and for efficiency's sake should, be skipped when the
115 * querytree has just been built by the parser: parse analysis already got
116 * all the same locks we'd get here, and the parser will have omitted dropped
117 * columns from JOINs to begin with. But we must do this whenever we are
118 * dealing with a querytree produced earlier than the current command.
120 * About JOINs and dropped columns: although the parser never includes an
121 * already-dropped column in a JOIN RTE's alias var list, it is possible for
122 * such a list in a stored rule to include references to dropped columns.
123 * (If the column is not explicitly referenced anywhere else in the query,
124 * the dependency mechanism won't consider it used by the rule and so won't
125 * prevent the column drop.) To support get_rte_attribute_is_dropped(), we
126 * replace join alias vars that reference dropped columns with null pointers.
128 * (In PostgreSQL 8.0, we did not do this processing but instead had
129 * get_rte_attribute_is_dropped() recurse to detect dropped columns in joins.
130 * That approach had horrible performance unfortunately; in particular
131 * construction of a nested join was O(N^2) in the nesting depth.)
134 AcquireRewriteLocks(Query *parsetree,
136 bool forUpdatePushedDown)
140 acquireLocksOnSubLinks_context context;
142 context.for_execute = forExecute;
145 * First, process RTEs of the current query level.
148 foreach(l, parsetree->rtable)
150 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
155 RangeTblEntry *curinputrte;
159 switch (rte->rtekind)
164 * Grab the appropriate lock type for the relation, and do not
165 * release it until end of transaction. This protects the
166 * rewriter and planner against schema changes mid-query.
168 * Assuming forExecute is true, this logic must match what the
169 * executor will do, else we risk lock-upgrade deadlocks.
172 lockmode = AccessShareLock;
173 else if (rt_index == parsetree->resultRelation)
174 lockmode = RowExclusiveLock;
175 else if (forUpdatePushedDown ||
176 get_parse_rowmark(parsetree, rt_index) != NULL)
177 lockmode = RowShareLock;
179 lockmode = AccessShareLock;
181 rel = heap_open(rte->relid, lockmode);
184 * While we have the relation open, update the RTE's relkind,
185 * just in case it changed since this rule was made.
187 rte->relkind = rel->rd_rel->relkind;
189 heap_close(rel, NoLock);
195 * Scan the join's alias var list to see if any columns have
196 * been dropped, and if so replace those Vars with null
199 * Since a join has only two inputs, we can expect to see
200 * multiple references to the same input RTE; optimize away
206 foreach(ll, rte->joinaliasvars)
208 Var *aliasitem = (Var *) lfirst(ll);
209 Var *aliasvar = aliasitem;
211 /* Look through any implicit coercion */
212 aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
215 * If the list item isn't a simple Var, then it must
216 * represent a merged column, ie a USING column, and so it
217 * couldn't possibly be dropped, since it's referenced in
218 * the join clause. (Conceivably it could also be a null
219 * pointer already? But that's OK too.)
221 if (aliasvar && IsA(aliasvar, Var))
224 * The elements of an alias list have to refer to
225 * earlier RTEs of the same rtable, because that's the
226 * order the planner builds things in. So we already
227 * processed the referenced RTE, and so it's safe to
228 * use get_rte_attribute_is_dropped on it. (This might
229 * not hold after rewriting or planning, but it's OK
232 Assert(aliasvar->varlevelsup == 0);
233 if (aliasvar->varno != curinputvarno)
235 curinputvarno = aliasvar->varno;
236 if (curinputvarno >= rt_index)
237 elog(ERROR, "unexpected varno %d in JOIN RTE %d",
238 curinputvarno, rt_index);
239 curinputrte = rt_fetch(curinputvarno,
242 if (get_rte_attribute_is_dropped(curinputrte,
245 /* Replace the join alias item with a NULL */
249 newaliasvars = lappend(newaliasvars, aliasitem);
251 rte->joinaliasvars = newaliasvars;
257 * The subquery RTE itself is all right, but we have to
258 * recurse to process the represented subquery.
260 AcquireRewriteLocks(rte->subquery,
262 (forUpdatePushedDown ||
263 get_parse_rowmark(parsetree, rt_index) != NULL));
267 /* ignore other types of RTEs */
272 /* Recurse into subqueries in WITH */
273 foreach(l, parsetree->cteList)
275 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
277 AcquireRewriteLocks((Query *) cte->ctequery, forExecute, false);
281 * Recurse into sublink subqueries, too. But we already did the ones in
282 * the rtable and cteList.
284 if (parsetree->hasSubLinks)
285 query_tree_walker(parsetree, acquireLocksOnSubLinks, &context,
286 QTW_IGNORE_RC_SUBQUERIES);
290 * Walker to find sublink subqueries for AcquireRewriteLocks
293 acquireLocksOnSubLinks(Node *node, acquireLocksOnSubLinks_context *context)
297 if (IsA(node, SubLink))
299 SubLink *sub = (SubLink *) node;
301 /* Do what we came for */
302 AcquireRewriteLocks((Query *) sub->subselect,
303 context->for_execute,
305 /* Fall through to process lefthand args of SubLink */
309 * Do NOT recurse into Query nodes, because AcquireRewriteLocks already
310 * processed subselects of subselects for us.
312 return expression_tree_walker(node, acquireLocksOnSubLinks, context);
317 * rewriteRuleAction -
318 * Rewrite the rule action with appropriate qualifiers (taken from
319 * the triggering query).
322 * parsetree - original query
323 * rule_action - one action (query) of a rule
324 * rule_qual - WHERE condition of rule, or NULL if unconditional
325 * rt_index - RT index of result relation in original query
326 * event - type of rule event
328 * *returning_flag - set TRUE if we rewrite RETURNING clause in rule_action
329 * (must be initialized to FALSE)
331 * rewritten form of rule_action
334 rewriteRuleAction(Query *parsetree,
339 bool *returning_flag)
345 Query **sub_action_ptr;
346 acquireLocksOnSubLinks_context context;
348 context.for_execute = true;
351 * Make modifiable copies of rule action and qual (what we're passed are
352 * the stored versions in the relcache; don't touch 'em!).
354 rule_action = copyObject(rule_action);
355 rule_qual = copyObject(rule_qual);
358 * Acquire necessary locks and fix any deleted JOIN RTE entries.
360 AcquireRewriteLocks(rule_action, true, false);
361 (void) acquireLocksOnSubLinks(rule_qual, &context);
363 current_varno = rt_index;
364 rt_length = list_length(parsetree->rtable);
365 new_varno = PRS2_NEW_VARNO + rt_length;
368 * Adjust rule action and qual to offset its varnos, so that we can merge
369 * its rtable with the main parsetree's rtable.
371 * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
372 * will be in the SELECT part, and we have to modify that rather than the
373 * top-level INSERT (kluge!).
375 sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
377 OffsetVarNodes((Node *) sub_action, rt_length, 0);
378 OffsetVarNodes(rule_qual, rt_length, 0);
379 /* but references to OLD should point at original rt_index */
380 ChangeVarNodes((Node *) sub_action,
381 PRS2_OLD_VARNO + rt_length, rt_index, 0);
382 ChangeVarNodes(rule_qual,
383 PRS2_OLD_VARNO + rt_length, rt_index, 0);
386 * Generate expanded rtable consisting of main parsetree's rtable plus
387 * rule action's rtable; this becomes the complete rtable for the rule
388 * action. Some of the entries may be unused after we finish rewriting,
389 * but we leave them all in place for two reasons:
391 * We'd have a much harder job to adjust the query's varnos if we
392 * selectively removed RT entries.
394 * If the rule is INSTEAD, then the original query won't be executed at
395 * all, and so its rtable must be preserved so that the executor will do
396 * the correct permissions checks on it.
398 * RT entries that are not referenced in the completed jointree will be
399 * ignored by the planner, so they do not affect query semantics. But any
400 * permissions checks specified in them will be applied during executor
401 * startup (see ExecCheckRTEPerms()). This allows us to check that the
402 * caller has, say, insert-permission on a view, when the view is not
403 * semantically referenced at all in the resulting query.
405 * When a rule is not INSTEAD, the permissions checks done on its copied
406 * RT entries will be redundant with those done during execution of the
407 * original query, but we don't bother to treat that case differently.
409 * NOTE: because planner will destructively alter rtable, we must ensure
410 * that rule action's rtable is separate and shares no substructure with
411 * the main rtable. Hence do a deep copy here.
413 sub_action->rtable = list_concat(copyObject(parsetree->rtable),
417 * There could have been some SubLinks in parsetree's rtable, in which
418 * case we'd better mark the sub_action correctly.
420 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
424 foreach(lc, parsetree->rtable)
426 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
428 switch (rte->rtekind)
431 sub_action->hasSubLinks =
432 checkExprHasSubLink((Node *) rte->tablesample);
435 sub_action->hasSubLinks =
436 checkExprHasSubLink((Node *) rte->functions);
439 sub_action->hasSubLinks =
440 checkExprHasSubLink((Node *) rte->tablefunc);
443 sub_action->hasSubLinks =
444 checkExprHasSubLink((Node *) rte->values_lists);
447 /* other RTE types don't contain bare expressions */
450 if (sub_action->hasSubLinks)
451 break; /* no need to keep scanning rtable */
456 * Also, we might have absorbed some RTEs with RLS conditions into the
457 * sub_action. If so, mark it as hasRowSecurity, whether or not those
458 * RTEs will be referenced after we finish rewriting. (Note: currently
459 * this is a no-op because RLS conditions aren't added till later, but it
460 * seems like good future-proofing to do this anyway.)
462 sub_action->hasRowSecurity |= parsetree->hasRowSecurity;
465 * Each rule action's jointree should be the main parsetree's jointree
466 * plus that rule's jointree, but usually *without* the original rtindex
467 * that we're replacing (if present, which it won't be for INSERT). Note
468 * that if the rule action refers to OLD, its jointree will add a
469 * reference to rt_index. If the rule action doesn't refer to OLD, but
470 * either the rule_qual or the user query quals do, then we need to keep
471 * the original rtindex in the jointree to provide data for the quals. We
472 * don't want the original rtindex to be joined twice, however, so avoid
473 * keeping it if the rule action mentions it.
475 * As above, the action's jointree must not share substructure with the
478 if (sub_action->commandType != CMD_UTILITY)
483 Assert(sub_action->jointree != NULL);
484 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
486 (rangeTableEntry_used(rule_qual, rt_index, 0) ||
487 rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
488 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
489 if (newjointree != NIL)
492 * If sub_action is a setop, manipulating its jointree will do no
493 * good at all, because the jointree is dummy. (Perhaps someday
494 * we could push the joining and quals down to the member
495 * statements of the setop?)
497 if (sub_action->setOperations != NULL)
499 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
500 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
502 sub_action->jointree->fromlist =
503 list_concat(newjointree, sub_action->jointree->fromlist);
506 * There could have been some SubLinks in newjointree, in which
507 * case we'd better mark the sub_action correctly.
509 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
510 sub_action->hasSubLinks =
511 checkExprHasSubLink((Node *) newjointree);
516 * If the original query has any CTEs, copy them into the rule action. But
517 * we don't need them for a utility action.
519 if (parsetree->cteList != NIL && sub_action->commandType != CMD_UTILITY)
524 * Annoying implementation restriction: because CTEs are identified by
525 * name within a cteList, we can't merge a CTE from the original query
526 * if it has the same name as any CTE in the rule action.
528 * This could possibly be fixed by using some sort of internally
529 * generated ID, instead of names, to link CTE RTEs to their CTEs.
531 foreach(lc, parsetree->cteList)
533 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
536 foreach(lc2, sub_action->cteList)
538 CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(lc2);
540 if (strcmp(cte->ctename, cte2->ctename) == 0)
542 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
543 errmsg("WITH query name \"%s\" appears in both a rule action and the query being rewritten",
548 /* OK, it's safe to combine the CTE lists */
549 sub_action->cteList = list_concat(sub_action->cteList,
550 copyObject(parsetree->cteList));
554 * Event Qualification forces copying of parsetree and splitting into two
555 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
558 AddQual(sub_action, rule_qual);
560 AddQual(sub_action, parsetree->jointree->quals);
563 * Rewrite new.attribute with right hand side of target-list entry for
564 * appropriate field name in insert/update.
566 * KLUGE ALERT: since ReplaceVarsFromTargetList returns a mutated copy, we
567 * can't just apply it to sub_action; we have to remember to update the
568 * sublink inside rule_action, too.
570 if ((event == CMD_INSERT || event == CMD_UPDATE) &&
571 sub_action->commandType != CMD_UTILITY)
573 sub_action = (Query *)
574 ReplaceVarsFromTargetList((Node *) sub_action,
577 rt_fetch(new_varno, sub_action->rtable),
578 parsetree->targetList,
579 (event == CMD_UPDATE) ?
580 REPLACEVARS_CHANGE_VARNO :
581 REPLACEVARS_SUBSTITUTE_NULL,
585 *sub_action_ptr = sub_action;
587 rule_action = sub_action;
591 * If rule_action has a RETURNING clause, then either throw it away if the
592 * triggering query has no RETURNING clause, or rewrite it to emit what
593 * the triggering query's RETURNING clause asks for. Throw an error if
594 * more than one rule has a RETURNING clause.
596 if (!parsetree->returningList)
597 rule_action->returningList = NIL;
598 else if (rule_action->returningList)
602 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
603 errmsg("cannot have RETURNING lists in multiple rules")));
604 *returning_flag = true;
605 rule_action->returningList = (List *)
606 ReplaceVarsFromTargetList((Node *) parsetree->returningList,
607 parsetree->resultRelation,
609 rt_fetch(parsetree->resultRelation,
611 rule_action->returningList,
612 REPLACEVARS_REPORT_ERROR,
614 &rule_action->hasSubLinks);
617 * There could have been some SubLinks in parsetree's returningList,
618 * in which case we'd better mark the rule_action correctly.
620 if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
621 rule_action->hasSubLinks =
622 checkExprHasSubLink((Node *) rule_action->returningList);
629 * Copy the query's jointree list, and optionally attempt to remove any
630 * occurrence of the given rt_index as a top-level join item (we do not look
631 * for it within join items; this is OK because we are only expecting to find
632 * it as an UPDATE or DELETE target relation, which will be at the top level
633 * of the join). Returns modified jointree list --- this is a separate copy
634 * sharing no nodes with the original.
637 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
639 List *newjointree = copyObject(parsetree->jointree->fromlist);
644 foreach(l, newjointree)
646 RangeTblRef *rtr = lfirst(l);
648 if (IsA(rtr, RangeTblRef) &&
649 rtr->rtindex == rt_index)
651 newjointree = list_delete_ptr(newjointree, rtr);
654 * foreach is safe because we exit loop after list_delete...
665 * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
667 * This has the following responsibilities:
669 * 1. For an INSERT, add tlist entries to compute default values for any
670 * attributes that have defaults and are not assigned to in the given tlist.
671 * (We do not insert anything for default-less attributes, however. The
672 * planner will later insert NULLs for them, but there's no reason to slow
673 * down rewriter processing with extra tlist nodes.) Also, for both INSERT
674 * and UPDATE, replace explicit DEFAULT specifications with column default
677 * 2. For an UPDATE on a trigger-updatable view, add tlist entries for any
678 * unassigned-to attributes, assigning them their old values. These will
679 * later get expanded to the output values of the view. (This is equivalent
680 * to what the planner's expand_targetlist() will do for UPDATE on a regular
681 * table, but it's more convenient to do it here while we still have easy
682 * access to the view's original RT index.) This is only necessary for
683 * trigger-updatable views, for which the view remains the result relation of
684 * the query. For auto-updatable views we must not do this, since it might
685 * add assignments to non-updatable view columns. For rule-updatable views it
686 * is unnecessary extra work, since the query will be rewritten with a
687 * different result relation which will be processed when we recurse via
690 * 3. Merge multiple entries for the same target attribute, or declare error
691 * if we can't. Multiple entries are only allowed for INSERT/UPDATE of
692 * portions of an array or record field, for example
693 * UPDATE table SET foo[2] = 42, foo[4] = 43;
694 * We can merge such operations into a single assignment op. Essentially,
695 * the expression we want to produce in this case is like
696 * foo = array_set_element(array_set_element(foo, 2, 42), 4, 43)
698 * 4. Sort the tlist into standard order: non-junk fields in order by resno,
699 * then junk fields (these in no particular order).
701 * We must do items 1,2,3 before firing rewrite rules, else rewritten
702 * references to NEW.foo will produce wrong or incomplete results. Item 4
703 * is not needed for rewriting, but will be needed by the planner, and we
704 * can do it essentially for free while handling the other items.
706 * If attrno_list isn't NULL, we return an additional output besides the
707 * rewritten targetlist: an integer list of the assigned-to attnums, in
708 * order of the original tlist's non-junk entries. This is needed for
709 * processing VALUES RTEs.
712 rewriteTargetListIU(List *targetList,
714 OverridingKind override,
715 Relation target_relation,
719 TargetEntry **new_tles;
720 List *new_tlist = NIL;
721 List *junk_tlist = NIL;
722 Form_pg_attribute att_tup;
728 if (attrno_list) /* initialize optional result list */
732 * We process the normal (non-junk) attributes by scanning the input tlist
733 * once and transferring TLEs into an array, then scanning the array to
734 * build an output tlist. This avoids O(N^2) behavior for large numbers
737 * Junk attributes are tossed into a separate list during the same tlist
738 * scan, then appended to the reconstructed tlist.
740 numattrs = RelationGetNumberOfAttributes(target_relation);
741 new_tles = (TargetEntry **) palloc0(numattrs * sizeof(TargetEntry *));
742 next_junk_attrno = numattrs + 1;
744 foreach(temp, targetList)
746 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
748 if (!old_tle->resjunk)
750 /* Normal attr: stash it into new_tles[] */
751 attrno = old_tle->resno;
752 if (attrno < 1 || attrno > numattrs)
753 elog(ERROR, "bogus resno %d in targetlist", attrno);
754 att_tup = target_relation->rd_att->attrs[attrno - 1];
756 /* put attrno into attrno_list even if it's dropped */
758 *attrno_list = lappend_int(*attrno_list, attrno);
760 /* We can (and must) ignore deleted attributes */
761 if (att_tup->attisdropped)
764 /* Merge with any prior assignment to same attribute */
765 new_tles[attrno - 1] =
766 process_matched_tle(old_tle,
767 new_tles[attrno - 1],
768 NameStr(att_tup->attname));
773 * Copy all resjunk tlist entries to junk_tlist, and assign them
774 * resnos above the last real resno.
776 * Typical junk entries include ORDER BY or GROUP BY expressions
777 * (are these actually possible in an INSERT or UPDATE?), system
778 * attribute references, etc.
781 /* Get the resno right, but don't copy unnecessarily */
782 if (old_tle->resno != next_junk_attrno)
784 old_tle = flatCopyTargetEntry(old_tle);
785 old_tle->resno = next_junk_attrno;
787 junk_tlist = lappend(junk_tlist, old_tle);
792 for (attrno = 1; attrno <= numattrs; attrno++)
794 TargetEntry *new_tle = new_tles[attrno - 1];
797 att_tup = target_relation->rd_att->attrs[attrno - 1];
799 /* We can (and must) ignore deleted attributes */
800 if (att_tup->attisdropped)
804 * Handle the two cases where we need to insert a default expression:
805 * it's an INSERT and there's no tlist entry for the column, or the
806 * tlist entry is a DEFAULT placeholder node.
808 apply_default = ((new_tle == NULL && commandType == CMD_INSERT) ||
809 (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)));
811 if (commandType == CMD_INSERT)
813 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS && !apply_default)
815 if (override != OVERRIDING_SYSTEM_VALUE)
817 (errcode(ERRCODE_GENERATED_ALWAYS),
818 errmsg("cannot insert into column \"%s\"", NameStr(att_tup->attname)),
819 errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
820 NameStr(att_tup->attname)),
821 errhint("Use OVERRIDING SYSTEM VALUE to override.")));
824 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_BY_DEFAULT && override == OVERRIDING_USER_VALUE)
825 apply_default = true;
828 if (commandType == CMD_UPDATE)
830 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS && !apply_default)
832 (errcode(ERRCODE_GENERATED_ALWAYS),
833 errmsg("column \"%s\" can only be updated to DEFAULT", NameStr(att_tup->attname)),
834 errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
835 NameStr(att_tup->attname))));
842 if (att_tup->attidentity)
844 NextValueExpr *nve = makeNode(NextValueExpr);
846 nve->seqid = getOwnedSequence(RelationGetRelid(target_relation), attrno);
847 nve->typeId = att_tup->atttypid;
849 new_expr = (Node *) nve;
852 new_expr = build_column_default(target_relation, attrno);
855 * If there is no default (ie, default is effectively NULL), we
856 * can omit the tlist entry in the INSERT case, since the planner
857 * can insert a NULL for itself, and there's no point in spending
858 * any more rewriter cycles on the entry. But in the UPDATE case
859 * we've got to explicitly set the column to NULL.
863 if (commandType == CMD_INSERT)
867 new_expr = (Node *) makeConst(att_tup->atttypid,
869 att_tup->attcollation,
874 /* this is to catch a NOT NULL domain constraint */
875 new_expr = coerce_to_domain(new_expr,
878 COERCE_IMPLICIT_CAST,
886 new_tle = makeTargetEntry((Expr *) new_expr,
888 pstrdup(NameStr(att_tup->attname)),
893 * For an UPDATE on a trigger-updatable view, provide a dummy entry
894 * whenever there is no explicit assignment.
896 if (new_tle == NULL && commandType == CMD_UPDATE &&
897 target_relation->rd_rel->relkind == RELKIND_VIEW &&
898 view_has_instead_trigger(target_relation, CMD_UPDATE))
902 new_expr = (Node *) makeVar(result_rti,
906 att_tup->attcollation,
909 new_tle = makeTargetEntry((Expr *) new_expr,
911 pstrdup(NameStr(att_tup->attname)),
916 new_tlist = lappend(new_tlist, new_tle);
921 return list_concat(new_tlist, junk_tlist);
926 * Convert a matched TLE from the original tlist into a correct new TLE.
928 * This routine detects and handles multiple assignments to the same target
929 * attribute. (The attribute name is needed only for error messages.)
932 process_matched_tle(TargetEntry *src_tle,
933 TargetEntry *prior_tle,
934 const char *attrName)
944 if (prior_tle == NULL)
947 * Normal case where this is the first assignment to the attribute.
953 * Multiple assignments to same attribute. Allow only if all are
954 * FieldStore or ArrayRef assignment operations. This is a bit
955 * tricky because what we may actually be looking at is a nest of
956 * such nodes; consider
957 * UPDATE tab SET col.fld1.subfld1 = x, col.fld2.subfld2 = y
958 * The two expressions produced by the parser will look like
959 * FieldStore(col, fld1, FieldStore(placeholder, subfld1, x))
960 * FieldStore(col, fld2, FieldStore(placeholder, subfld2, y))
961 * However, we can ignore the substructure and just consider the top
962 * FieldStore or ArrayRef from each assignment, because it works to
964 * FieldStore(FieldStore(col, fld1,
965 * FieldStore(placeholder, subfld1, x)),
966 * fld2, FieldStore(placeholder, subfld2, y))
967 * Note the leftmost expression goes on the inside so that the
968 * assignments appear to occur left-to-right.
970 * For FieldStore, instead of nesting we can generate a single
971 * FieldStore with multiple target fields. We must nest when
972 * ArrayRefs are involved though.
975 src_expr = (Node *) src_tle->expr;
976 prior_expr = (Node *) prior_tle->expr;
977 src_input = get_assignment_input(src_expr);
978 prior_input = get_assignment_input(prior_expr);
979 if (src_input == NULL ||
980 prior_input == NULL ||
981 exprType(src_expr) != exprType(prior_expr))
983 (errcode(ERRCODE_SYNTAX_ERROR),
984 errmsg("multiple assignments to same column \"%s\"",
988 * Prior TLE could be a nest of assignments if we do this more than once.
990 priorbottom = prior_input;
993 Node *newbottom = get_assignment_input(priorbottom);
995 if (newbottom == NULL)
996 break; /* found the original Var reference */
997 priorbottom = newbottom;
999 if (!equal(priorbottom, src_input))
1001 (errcode(ERRCODE_SYNTAX_ERROR),
1002 errmsg("multiple assignments to same column \"%s\"",
1006 * Looks OK to nest 'em.
1008 if (IsA(src_expr, FieldStore))
1010 FieldStore *fstore = makeNode(FieldStore);
1012 if (IsA(prior_expr, FieldStore))
1014 /* combine the two */
1015 memcpy(fstore, prior_expr, sizeof(FieldStore));
1017 list_concat(list_copy(((FieldStore *) prior_expr)->newvals),
1018 list_copy(((FieldStore *) src_expr)->newvals));
1020 list_concat(list_copy(((FieldStore *) prior_expr)->fieldnums),
1021 list_copy(((FieldStore *) src_expr)->fieldnums));
1025 /* general case, just nest 'em */
1026 memcpy(fstore, src_expr, sizeof(FieldStore));
1027 fstore->arg = (Expr *) prior_expr;
1029 newexpr = (Node *) fstore;
1031 else if (IsA(src_expr, ArrayRef))
1033 ArrayRef *aref = makeNode(ArrayRef);
1035 memcpy(aref, src_expr, sizeof(ArrayRef));
1036 aref->refexpr = (Expr *) prior_expr;
1037 newexpr = (Node *) aref;
1041 elog(ERROR, "cannot happen");
1045 result = flatCopyTargetEntry(src_tle);
1046 result->expr = (Expr *) newexpr;
1051 * If node is an assignment node, return its input; else return NULL
1054 get_assignment_input(Node *node)
1058 if (IsA(node, FieldStore))
1060 FieldStore *fstore = (FieldStore *) node;
1062 return (Node *) fstore->arg;
1064 else if (IsA(node, ArrayRef))
1066 ArrayRef *aref = (ArrayRef *) node;
1068 if (aref->refassgnexpr == NULL)
1070 return (Node *) aref->refexpr;
1076 * Make an expression tree for the default value for a column.
1078 * If there is no default, return a NULL instead.
1081 build_column_default(Relation rel, int attrno)
1083 TupleDesc rd_att = rel->rd_att;
1084 Form_pg_attribute att_tup = rd_att->attrs[attrno - 1];
1085 Oid atttype = att_tup->atttypid;
1086 int32 atttypmod = att_tup->atttypmod;
1091 * Scan to see if relation has a default for this column.
1093 if (rd_att->constr && rd_att->constr->num_defval > 0)
1095 AttrDefault *defval = rd_att->constr->defval;
1096 int ndef = rd_att->constr->num_defval;
1100 if (attrno == defval[ndef].adnum)
1103 * Found it, convert string representation to node tree.
1105 expr = stringToNode(defval[ndef].adbin);
1114 * No per-column default, so look for a default for the type itself.
1116 expr = get_typdefault(atttype);
1120 return NULL; /* No default anywhere */
1123 * Make sure the value is coerced to the target column type; this will
1124 * generally be true already, but there seem to be some corner cases
1125 * involving domain defaults where it might not be true. This should match
1126 * the parser's processing of non-defaulted expressions --- see
1127 * transformAssignedExpr().
1129 exprtype = exprType(expr);
1131 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1134 COERCION_ASSIGNMENT,
1135 COERCE_IMPLICIT_CAST,
1139 (errcode(ERRCODE_DATATYPE_MISMATCH),
1140 errmsg("column \"%s\" is of type %s"
1141 " but default expression is of type %s",
1142 NameStr(att_tup->attname),
1143 format_type_be(atttype),
1144 format_type_be(exprtype)),
1145 errhint("You will need to rewrite or cast the expression.")));
1151 /* Does VALUES RTE contain any SetToDefault items? */
1153 searchForDefault(RangeTblEntry *rte)
1157 foreach(lc, rte->values_lists)
1159 List *sublist = (List *) lfirst(lc);
1162 foreach(lc2, sublist)
1164 Node *col = (Node *) lfirst(lc2);
1166 if (IsA(col, SetToDefault))
1174 * When processing INSERT ... VALUES with a VALUES RTE (ie, multiple VALUES
1175 * lists), we have to replace any DEFAULT items in the VALUES lists with
1176 * the appropriate default expressions. The other aspects of targetlist
1177 * rewriting need be applied only to the query's targetlist proper.
1179 * Note that we currently can't support subscripted or field assignment
1180 * in the multi-VALUES case. The targetlist will contain simple Vars
1181 * referencing the VALUES RTE, and therefore process_matched_tle() will
1182 * reject any such attempt with "multiple assignments to same column".
1185 rewriteValuesRTE(RangeTblEntry *rte, Relation target_relation, List *attrnos)
1191 * Rebuilding all the lists is a pretty expensive proposition in a big
1192 * VALUES list, and it's a waste of time if there aren't any DEFAULT
1193 * placeholders. So first scan to see if there are any.
1195 if (!searchForDefault(rte))
1196 return; /* nothing to do */
1198 /* Check list lengths (we can assume all the VALUES sublists are alike) */
1199 Assert(list_length(attrnos) == list_length(linitial(rte->values_lists)));
1202 foreach(lc, rte->values_lists)
1204 List *sublist = (List *) lfirst(lc);
1205 List *newList = NIL;
1209 forboth(lc2, sublist, lc3, attrnos)
1211 Node *col = (Node *) lfirst(lc2);
1212 int attrno = lfirst_int(lc3);
1214 if (IsA(col, SetToDefault))
1216 Form_pg_attribute att_tup;
1219 att_tup = target_relation->rd_att->attrs[attrno - 1];
1221 if (!att_tup->attisdropped)
1222 new_expr = build_column_default(target_relation, attrno);
1224 new_expr = NULL; /* force a NULL if dropped */
1227 * If there is no default (ie, default is effectively NULL),
1228 * we've got to explicitly set the column to NULL.
1232 new_expr = (Node *) makeConst(att_tup->atttypid,
1234 att_tup->attcollation,
1239 /* this is to catch a NOT NULL domain constraint */
1240 new_expr = coerce_to_domain(new_expr,
1243 COERCE_IMPLICIT_CAST,
1248 newList = lappend(newList, new_expr);
1251 newList = lappend(newList, col);
1253 newValues = lappend(newValues, newList);
1255 rte->values_lists = newValues;
1260 * rewriteTargetListUD - rewrite UPDATE/DELETE targetlist as needed
1262 * This function adds a "junk" TLE that is needed to allow the executor to
1263 * find the original row for the update or delete. When the target relation
1264 * is a regular table, the junk TLE emits the ctid attribute of the original
1265 * row. When the target relation is a view, there is no ctid, so we instead
1266 * emit a whole-row Var that will contain the "old" values of the view row.
1267 * If it's a foreign table, we let the FDW decide what to add.
1269 * For UPDATE queries, this is applied after rewriteTargetListIU. The
1270 * ordering isn't actually critical at the moment.
1273 rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
1274 Relation target_relation)
1277 const char *attrname;
1280 if (target_relation->rd_rel->relkind == RELKIND_RELATION ||
1281 target_relation->rd_rel->relkind == RELKIND_MATVIEW ||
1282 target_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1285 * Emit CTID so that executor can find the row to update or delete.
1287 var = makeVar(parsetree->resultRelation,
1288 SelfItemPointerAttributeNumber,
1296 else if (target_relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1299 * Let the foreign table's FDW add whatever junk TLEs it wants.
1301 FdwRoutine *fdwroutine;
1303 fdwroutine = GetFdwRoutineForRelation(target_relation, false);
1305 if (fdwroutine->AddForeignUpdateTargets != NULL)
1306 fdwroutine->AddForeignUpdateTargets(parsetree, target_rte,
1310 * If we have a row-level trigger corresponding to the operation, emit
1311 * a whole-row Var so that executor will have the "old" row to pass to
1312 * the trigger. Alas, this misses system columns.
1314 if (target_relation->trigdesc &&
1315 ((parsetree->commandType == CMD_UPDATE &&
1316 (target_relation->trigdesc->trig_update_after_row ||
1317 target_relation->trigdesc->trig_update_before_row)) ||
1318 (parsetree->commandType == CMD_DELETE &&
1319 (target_relation->trigdesc->trig_delete_after_row ||
1320 target_relation->trigdesc->trig_delete_before_row))))
1322 var = makeWholeRowVar(target_rte,
1323 parsetree->resultRelation,
1327 attrname = "wholerow";
1333 * Emit whole-row Var so that executor will have the "old" view row to
1334 * pass to the INSTEAD OF trigger.
1336 var = makeWholeRowVar(target_rte,
1337 parsetree->resultRelation,
1341 attrname = "wholerow";
1346 tle = makeTargetEntry((Expr *) var,
1347 list_length(parsetree->targetList) + 1,
1351 parsetree->targetList = lappend(parsetree->targetList, tle);
1358 * match the list of locks and returns the matching rules
1361 matchLocks(CmdType event,
1362 RuleLock *rulelocks,
1367 List *matching_locks = NIL;
1371 if (rulelocks == NULL)
1374 if (parsetree->commandType != CMD_SELECT)
1376 if (parsetree->resultRelation != varno)
1380 nlocks = rulelocks->numLocks;
1382 for (i = 0; i < nlocks; i++)
1384 RewriteRule *oneLock = rulelocks->rules[i];
1386 if (oneLock->event == CMD_UPDATE)
1390 * Suppress ON INSERT/UPDATE/DELETE rules that are disabled or
1391 * configured to not fire during the current sessions replication
1392 * role. ON SELECT rules will always be applied in order to keep views
1393 * working even in LOCAL or REPLICA role.
1395 if (oneLock->event != CMD_SELECT)
1397 if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
1399 if (oneLock->enabled == RULE_FIRES_ON_ORIGIN ||
1400 oneLock->enabled == RULE_DISABLED)
1403 else /* ORIGIN or LOCAL ROLE */
1405 if (oneLock->enabled == RULE_FIRES_ON_REPLICA ||
1406 oneLock->enabled == RULE_DISABLED)
1411 if (oneLock->event == event)
1413 if (parsetree->commandType != CMD_SELECT ||
1414 rangeTableEntry_used((Node *) parsetree, varno, 0))
1415 matching_locks = lappend(matching_locks, oneLock);
1419 return matching_locks;
1424 * ApplyRetrieveRule - expand an ON SELECT rule
1427 ApplyRetrieveRule(Query *parsetree,
1432 bool forUpdatePushedDown)
1439 if (list_length(rule->actions) != 1)
1440 elog(ERROR, "expected just one rule action");
1441 if (rule->qual != NULL)
1442 elog(ERROR, "cannot handle qualified ON SELECT rule");
1444 if (rt_index == parsetree->resultRelation)
1447 * We have a view as the result relation of the query, and it wasn't
1448 * rewritten by any rule. This case is supported if there is an
1449 * INSTEAD OF trigger that will trap attempts to insert/update/delete
1450 * view rows. The executor will check that; for the moment just plow
1451 * ahead. We have two cases:
1453 * For INSERT, we needn't do anything. The unmodified RTE will serve
1454 * fine as the result relation.
1456 * For UPDATE/DELETE, we need to expand the view so as to have source
1457 * data for the operation. But we also need an unmodified RTE to
1458 * serve as the target. So, copy the RTE and add the copy to the
1459 * rangetable. Note that the copy does not get added to the jointree.
1460 * Also note that there's a hack in fireRIRrules to avoid calling this
1461 * function again when it arrives at the copied RTE.
1463 if (parsetree->commandType == CMD_INSERT)
1465 else if (parsetree->commandType == CMD_UPDATE ||
1466 parsetree->commandType == CMD_DELETE)
1468 RangeTblEntry *newrte;
1470 rte = rt_fetch(rt_index, parsetree->rtable);
1471 newrte = copyObject(rte);
1472 parsetree->rtable = lappend(parsetree->rtable, newrte);
1473 parsetree->resultRelation = list_length(parsetree->rtable);
1476 * There's no need to do permissions checks twice, so wipe out the
1477 * permissions info for the original RTE (we prefer to keep the
1478 * bits set on the result RTE).
1480 rte->requiredPerms = 0;
1481 rte->checkAsUser = InvalidOid;
1482 rte->selectedCols = NULL;
1483 rte->insertedCols = NULL;
1484 rte->updatedCols = NULL;
1487 * For the most part, Vars referencing the view should remain as
1488 * they are, meaning that they implicitly represent OLD values.
1489 * But in the RETURNING list if any, we want such Vars to
1490 * represent NEW values, so change them to reference the new RTE.
1492 * Since ChangeVarNodes scribbles on the tree in-place, copy the
1493 * RETURNING list first for safety.
1495 parsetree->returningList = copyObject(parsetree->returningList);
1496 ChangeVarNodes((Node *) parsetree->returningList, rt_index,
1497 parsetree->resultRelation, 0);
1499 /* Now, continue with expanding the original view RTE */
1502 elog(ERROR, "unrecognized commandType: %d",
1503 (int) parsetree->commandType);
1507 * If FOR [KEY] UPDATE/SHARE of view, be sure we get right initial lock on
1508 * the relations it references.
1510 rc = get_parse_rowmark(parsetree, rt_index);
1511 forUpdatePushedDown |= (rc != NULL);
1514 * Make a modifiable copy of the view query, and acquire needed locks on
1515 * the relations it mentions.
1517 rule_action = copyObject(linitial(rule->actions));
1519 AcquireRewriteLocks(rule_action, true, forUpdatePushedDown);
1522 * Recursively expand any view references inside the view.
1524 rule_action = fireRIRrules(rule_action, activeRIRs, forUpdatePushedDown);
1527 * Now, plug the view query in as a subselect, replacing the relation's
1530 rte = rt_fetch(rt_index, parsetree->rtable);
1532 rte->rtekind = RTE_SUBQUERY;
1533 rte->relid = InvalidOid;
1534 rte->security_barrier = RelationIsSecurityView(relation);
1535 rte->subquery = rule_action;
1536 rte->inh = false; /* must not be set for a subquery */
1539 * We move the view's permission check data down to its rangetable. The
1540 * checks will actually be done against the OLD entry therein.
1542 subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
1543 Assert(subrte->relid == relation->rd_id);
1544 subrte->requiredPerms = rte->requiredPerms;
1545 subrte->checkAsUser = rte->checkAsUser;
1546 subrte->selectedCols = rte->selectedCols;
1547 subrte->insertedCols = rte->insertedCols;
1548 subrte->updatedCols = rte->updatedCols;
1550 rte->requiredPerms = 0; /* no permission check on subquery itself */
1551 rte->checkAsUser = InvalidOid;
1552 rte->selectedCols = NULL;
1553 rte->insertedCols = NULL;
1554 rte->updatedCols = NULL;
1557 * If FOR [KEY] UPDATE/SHARE of view, mark all the contained tables as
1558 * implicit FOR [KEY] UPDATE/SHARE, the same as the parser would have done
1559 * if the view's subquery had been written out explicitly.
1561 * Note: we don't consider forUpdatePushedDown here; such marks will be
1562 * made by recursing from the upper level in markQueryForLocking.
1565 markQueryForLocking(rule_action, (Node *) rule_action->jointree,
1566 rc->strength, rc->waitPolicy, true);
1572 * Recursively mark all relations used by a view as FOR [KEY] UPDATE/SHARE.
1574 * This may generate an invalid query, eg if some sub-query uses an
1575 * aggregate. We leave it to the planner to detect that.
1577 * NB: this must agree with the parser's transformLockingClause() routine.
1578 * However, unlike the parser we have to be careful not to mark a view's
1579 * OLD and NEW rels for updating. The best way to handle that seems to be
1580 * to scan the jointree to determine which rels are used.
1583 markQueryForLocking(Query *qry, Node *jtnode,
1584 LockClauseStrength strength, LockWaitPolicy waitPolicy,
1589 if (IsA(jtnode, RangeTblRef))
1591 int rti = ((RangeTblRef *) jtnode)->rtindex;
1592 RangeTblEntry *rte = rt_fetch(rti, qry->rtable);
1594 if (rte->rtekind == RTE_RELATION)
1596 applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
1597 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1599 else if (rte->rtekind == RTE_SUBQUERY)
1601 applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
1602 /* FOR UPDATE/SHARE of subquery is propagated to subquery's rels */
1603 markQueryForLocking(rte->subquery, (Node *) rte->subquery->jointree,
1604 strength, waitPolicy, true);
1606 /* other RTE types are unaffected by FOR UPDATE */
1608 else if (IsA(jtnode, FromExpr))
1610 FromExpr *f = (FromExpr *) jtnode;
1613 foreach(l, f->fromlist)
1614 markQueryForLocking(qry, lfirst(l), strength, waitPolicy, pushedDown);
1616 else if (IsA(jtnode, JoinExpr))
1618 JoinExpr *j = (JoinExpr *) jtnode;
1620 markQueryForLocking(qry, j->larg, strength, waitPolicy, pushedDown);
1621 markQueryForLocking(qry, j->rarg, strength, waitPolicy, pushedDown);
1624 elog(ERROR, "unrecognized node type: %d",
1625 (int) nodeTag(jtnode));
1630 * fireRIRonSubLink -
1631 * Apply fireRIRrules() to each SubLink (subselect in expression) found
1632 * in the given tree.
1634 * NOTE: although this has the form of a walker, we cheat and modify the
1635 * SubLink nodes in-place. It is caller's responsibility to ensure that
1636 * no unwanted side-effects occur!
1638 * This is unlike most of the other routines that recurse into subselects,
1639 * because we must take control at the SubLink node in order to replace
1640 * the SubLink's subselect link with the possibly-rewritten subquery.
1643 fireRIRonSubLink(Node *node, List *activeRIRs)
1647 if (IsA(node, SubLink))
1649 SubLink *sub = (SubLink *) node;
1651 /* Do what we came for */
1652 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
1654 /* Fall through to process lefthand args of SubLink */
1658 * Do NOT recurse into Query nodes, because fireRIRrules already processed
1659 * subselects of subselects for us.
1661 return expression_tree_walker(node, fireRIRonSubLink,
1662 (void *) activeRIRs);
1668 * Apply all RIR rules on each rangetable entry in a query
1671 fireRIRrules(Query *parsetree, List *activeRIRs, bool forUpdatePushedDown)
1673 int origResultRelation = parsetree->resultRelation;
1678 * don't try to convert this into a foreach loop, because rtable list can
1679 * get changed each time through...
1682 while (rt_index < list_length(parsetree->rtable))
1693 rte = rt_fetch(rt_index, parsetree->rtable);
1696 * A subquery RTE can't have associated rules, so there's nothing to
1697 * do to this level of the query, but we must recurse into the
1698 * subquery to expand any rule references in it.
1700 if (rte->rtekind == RTE_SUBQUERY)
1702 rte->subquery = fireRIRrules(rte->subquery, activeRIRs,
1703 (forUpdatePushedDown ||
1704 get_parse_rowmark(parsetree, rt_index) != NULL));
1709 * Joins and other non-relation RTEs can be ignored completely.
1711 if (rte->rtekind != RTE_RELATION)
1715 * Always ignore RIR rules for materialized views referenced in
1716 * queries. (This does not prevent refreshing MVs, since they aren't
1717 * referenced in their own query definitions.)
1719 * Note: in the future we might want to allow MVs to be conditionally
1720 * expanded as if they were regular views, if they are not scannable.
1721 * In that case this test would need to be postponed till after we've
1722 * opened the rel, so that we could check its state.
1724 if (rte->relkind == RELKIND_MATVIEW)
1728 * If the table is not referenced in the query, then we ignore it.
1729 * This prevents infinite expansion loop due to new rtable entries
1730 * inserted by expansion of a rule. A table is referenced if it is
1731 * part of the join set (a source table), or is referenced by any Var
1732 * nodes, or is the result table.
1734 if (rt_index != parsetree->resultRelation &&
1735 !rangeTableEntry_used((Node *) parsetree, rt_index, 0))
1739 * Also, if this is a new result relation introduced by
1740 * ApplyRetrieveRule, we don't want to do anything more with it.
1742 if (rt_index == parsetree->resultRelation &&
1743 rt_index != origResultRelation)
1747 * We can use NoLock here since either the parser or
1748 * AcquireRewriteLocks should have locked the rel already.
1750 rel = heap_open(rte->relid, NoLock);
1753 * Collect the RIR rules that we must apply
1755 rules = rel->rd_rules;
1759 for (i = 0; i < rules->numLocks; i++)
1761 rule = rules->rules[i];
1762 if (rule->event != CMD_SELECT)
1765 locks = lappend(locks, rule);
1769 * If we found any, apply them --- but first check for recursion!
1775 if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
1777 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1778 errmsg("infinite recursion detected in rules for relation \"%s\"",
1779 RelationGetRelationName(rel))));
1780 activeRIRs = lcons_oid(RelationGetRelid(rel), activeRIRs);
1786 parsetree = ApplyRetrieveRule(parsetree,
1791 forUpdatePushedDown);
1794 activeRIRs = list_delete_first(activeRIRs);
1798 heap_close(rel, NoLock);
1801 /* Recurse into subqueries in WITH */
1802 foreach(lc, parsetree->cteList)
1804 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1806 cte->ctequery = (Node *)
1807 fireRIRrules((Query *) cte->ctequery, activeRIRs, false);
1811 * Recurse into sublink subqueries, too. But we already did the ones in
1812 * the rtable and cteList.
1814 if (parsetree->hasSubLinks)
1815 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
1816 QTW_IGNORE_RC_SUBQUERIES);
1819 * Apply any row level security policies. We do this last because it
1820 * requires special recursion detection if the new quals have sublink
1821 * subqueries, and if we did it in the loop above query_tree_walker would
1822 * then recurse into those quals a second time.
1825 foreach(lc, parsetree->rtable)
1827 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
1829 List *securityQuals;
1830 List *withCheckOptions;
1831 bool hasRowSecurity;
1836 /* Only normal relations can have RLS policies */
1837 if (rte->rtekind != RTE_RELATION ||
1838 (rte->relkind != RELKIND_RELATION &&
1839 rte->relkind != RELKIND_PARTITIONED_TABLE))
1842 rel = heap_open(rte->relid, NoLock);
1845 * Fetch any new security quals that must be applied to this RTE.
1847 get_row_security_policies(parsetree, rte, rt_index,
1848 &securityQuals, &withCheckOptions,
1849 &hasRowSecurity, &hasSubLinks);
1851 if (securityQuals != NIL || withCheckOptions != NIL)
1855 acquireLocksOnSubLinks_context context;
1858 * Recursively process the new quals, checking for infinite
1861 if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
1863 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1864 errmsg("infinite recursion detected in policy for relation \"%s\"",
1865 RelationGetRelationName(rel))));
1867 activeRIRs = lcons_oid(RelationGetRelid(rel), activeRIRs);
1870 * get_row_security_policies just passed back securityQuals
1871 * and/or withCheckOptions, and there were SubLinks, make sure
1872 * we lock any relations which are referenced.
1874 * These locks would normally be acquired by the parser, but
1875 * securityQuals and withCheckOptions are added post-parsing.
1877 context.for_execute = true;
1878 (void) acquireLocksOnSubLinks((Node *) securityQuals, &context);
1879 (void) acquireLocksOnSubLinks((Node *) withCheckOptions,
1883 * Now that we have the locks on anything added by
1884 * get_row_security_policies, fire any RIR rules for them.
1886 expression_tree_walker((Node *) securityQuals,
1887 fireRIRonSubLink, (void *) activeRIRs);
1889 expression_tree_walker((Node *) withCheckOptions,
1890 fireRIRonSubLink, (void *) activeRIRs);
1892 activeRIRs = list_delete_first(activeRIRs);
1896 * Add the new security barrier quals to the start of the RTE's
1897 * list so that they get applied before any existing barrier quals
1898 * (which would have come from a security-barrier view, and should
1899 * get lower priority than RLS conditions on the table itself).
1901 rte->securityQuals = list_concat(securityQuals,
1902 rte->securityQuals);
1904 parsetree->withCheckOptions = list_concat(withCheckOptions,
1905 parsetree->withCheckOptions);
1909 * Make sure the query is marked correctly if row level security
1910 * applies, or if the new quals had sublinks.
1913 parsetree->hasRowSecurity = true;
1915 parsetree->hasSubLinks = true;
1917 heap_close(rel, NoLock);
1925 * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
1926 * qualification. This is used to generate suitable "else clauses" for
1927 * conditional INSTEAD rules. (Unfortunately we must use "x IS NOT TRUE",
1928 * not just "NOT x" which the planner is much smarter about, else we will
1929 * do the wrong thing when the qual evaluates to NULL.)
1931 * The rule_qual may contain references to OLD or NEW. OLD references are
1932 * replaced by references to the specified rt_index (the relation that the
1933 * rule applies to). NEW references are only possible for INSERT and UPDATE
1934 * queries on the relation itself, and so they should be replaced by copies
1935 * of the related entries in the query's own targetlist.
1938 CopyAndAddInvertedQual(Query *parsetree,
1943 /* Don't scribble on the passed qual (it's in the relcache!) */
1944 Node *new_qual = copyObject(rule_qual);
1945 acquireLocksOnSubLinks_context context;
1947 context.for_execute = true;
1950 * In case there are subqueries in the qual, acquire necessary locks and
1951 * fix any deleted JOIN RTE entries. (This is somewhat redundant with
1952 * rewriteRuleAction, but not entirely ... consider restructuring so that
1953 * we only need to process the qual this way once.)
1955 (void) acquireLocksOnSubLinks(new_qual, &context);
1957 /* Fix references to OLD */
1958 ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
1959 /* Fix references to NEW */
1960 if (event == CMD_INSERT || event == CMD_UPDATE)
1961 new_qual = ReplaceVarsFromTargetList(new_qual,
1966 parsetree->targetList,
1967 (event == CMD_UPDATE) ?
1968 REPLACEVARS_CHANGE_VARNO :
1969 REPLACEVARS_SUBSTITUTE_NULL,
1971 &parsetree->hasSubLinks);
1972 /* And attach the fixed qual */
1973 AddInvertedQual(parsetree, new_qual);
1981 * Iterate through rule locks applying rules.
1984 * parsetree - original query
1985 * rt_index - RT index of result relation in original query
1986 * event - type of rule event
1987 * locks - list of rules to fire
1989 * *instead_flag - set TRUE if any unqualified INSTEAD rule is found
1990 * (must be initialized to FALSE)
1991 * *returning_flag - set TRUE if we rewrite RETURNING clause in any rule
1992 * (must be initialized to FALSE)
1993 * *qual_product - filled with modified original query if any qualified
1994 * INSTEAD rule is found (must be initialized to NULL)
1996 * list of rule actions adjusted for use with this query
1998 * Qualified INSTEAD rules generate their action with the qualification
1999 * condition added. They also generate a modified version of the original
2000 * query with the negated qualification added, so that it will run only for
2001 * rows that the qualified action doesn't act on. (If there are multiple
2002 * qualified INSTEAD rules, we AND all the negated quals onto a single
2003 * modified original query.) We won't execute the original, unmodified
2004 * query if we find either qualified or unqualified INSTEAD rules. If
2005 * we find both, the modified original query is discarded too.
2008 fireRules(Query *parsetree,
2013 bool *returning_flag,
2014 Query **qual_product)
2016 List *results = NIL;
2021 RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
2022 Node *event_qual = rule_lock->qual;
2023 List *actions = rule_lock->actions;
2027 /* Determine correct QuerySource value for actions */
2028 if (rule_lock->isInstead)
2030 if (event_qual != NULL)
2031 qsrc = QSRC_QUAL_INSTEAD_RULE;
2034 qsrc = QSRC_INSTEAD_RULE;
2035 *instead_flag = true; /* report unqualified INSTEAD */
2039 qsrc = QSRC_NON_INSTEAD_RULE;
2041 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
2044 * If there are INSTEAD rules with qualifications, the original
2045 * query is still performed. But all the negated rule
2046 * qualifications of the INSTEAD rules are added so it does its
2047 * actions only in cases where the rule quals of all INSTEAD rules
2048 * are false. Think of it as the default action in a case. We save
2049 * this in *qual_product so RewriteQuery() can add it to the query
2050 * list after we mangled it up enough.
2052 * If we have already found an unqualified INSTEAD rule, then
2053 * *qual_product won't be used, so don't bother building it.
2057 if (*qual_product == NULL)
2058 *qual_product = copyObject(parsetree);
2059 *qual_product = CopyAndAddInvertedQual(*qual_product,
2066 /* Now process the rule's actions and add them to the result list */
2069 Query *rule_action = lfirst(r);
2071 if (rule_action->commandType == CMD_NOTHING)
2074 rule_action = rewriteRuleAction(parsetree, rule_action,
2075 event_qual, rt_index, event,
2078 rule_action->querySource = qsrc;
2079 rule_action->canSetTag = false; /* might change later */
2081 results = lappend(results, rule_action);
2090 * get_view_query - get the Query from a view's _RETURN rule.
2092 * Caller should have verified that the relation is a view, and therefore
2093 * we should find an ON SELECT action.
2095 * Note that the pointer returned is into the relcache and therefore must
2096 * be treated as read-only to the caller and not modified or scribbled on.
2099 get_view_query(Relation view)
2103 Assert(view->rd_rel->relkind == RELKIND_VIEW);
2105 for (i = 0; i < view->rd_rules->numLocks; i++)
2107 RewriteRule *rule = view->rd_rules->rules[i];
2109 if (rule->event == CMD_SELECT)
2111 /* A _RETURN rule should have only one action */
2112 if (list_length(rule->actions) != 1)
2113 elog(ERROR, "invalid _RETURN rule action specification");
2115 return (Query *) linitial(rule->actions);
2119 elog(ERROR, "failed to find _RETURN rule for view");
2120 return NULL; /* keep compiler quiet */
2125 * view_has_instead_trigger - does view have an INSTEAD OF trigger for event?
2127 * If it does, we don't want to treat it as auto-updatable. This test can't
2128 * be folded into view_query_is_auto_updatable because it's not an error
2132 view_has_instead_trigger(Relation view, CmdType event)
2134 TriggerDesc *trigDesc = view->trigdesc;
2139 if (trigDesc && trigDesc->trig_insert_instead_row)
2143 if (trigDesc && trigDesc->trig_update_instead_row)
2147 if (trigDesc && trigDesc->trig_delete_instead_row)
2151 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2159 * view_col_is_auto_updatable - test whether the specified column of a view
2160 * is auto-updatable. Returns NULL (if the column can be updated) or a message
2161 * string giving the reason that it cannot be.
2163 * Note that the checks performed here are local to this view. We do not check
2164 * whether the referenced column of the underlying base relation is updatable.
2167 view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
2169 Var *var = (Var *) tle->expr;
2172 * For now, the only updatable columns we support are those that are Vars
2173 * referring to user columns of the underlying base relation.
2175 * The view targetlist may contain resjunk columns (e.g., a view defined
2176 * like "SELECT * FROM t ORDER BY a+b" is auto-updatable) but such columns
2177 * are not auto-updatable, and in fact should never appear in the outer
2178 * query's targetlist.
2181 return gettext_noop("Junk view columns are not updatable.");
2183 if (!IsA(var, Var) ||
2184 var->varno != rtr->rtindex ||
2185 var->varlevelsup != 0)
2186 return gettext_noop("View columns that are not columns of their base relation are not updatable.");
2188 if (var->varattno < 0)
2189 return gettext_noop("View columns that refer to system columns are not updatable.");
2191 if (var->varattno == 0)
2192 return gettext_noop("View columns that return whole-row references are not updatable.");
2194 return NULL; /* the view column is updatable */
2199 * view_query_is_auto_updatable - test whether the specified view definition
2200 * represents an auto-updatable view. Returns NULL (if the view can be updated)
2201 * or a message string giving the reason that it cannot be.
2203 * If check_cols is true, the view is required to have at least one updatable
2204 * column (necessary for INSERT/UPDATE). Otherwise the view's columns are not
2205 * checked for updatability. See also view_cols_are_auto_updatable.
2207 * Note that the checks performed here are only based on the view definition.
2208 * We do not check whether any base relations referred to by the view are
2212 view_query_is_auto_updatable(Query *viewquery, bool check_cols)
2215 RangeTblEntry *base_rte;
2218 * Check if the view is simply updatable. According to SQL-92 this means:
2219 * - No DISTINCT clause.
2220 * - Each TLE is a column reference, and each column appears at most once.
2221 * - FROM contains exactly one base relation.
2222 * - No GROUP BY or HAVING clauses.
2223 * - No set operations (UNION, INTERSECT or EXCEPT).
2224 * - No sub-queries in the WHERE clause that reference the target table.
2226 * We ignore that last restriction since it would be complex to enforce
2227 * and there isn't any actual benefit to disallowing sub-queries. (The
2228 * semantic issues that the standard is presumably concerned about don't
2229 * arise in Postgres, since any such sub-query will not see any updates
2230 * executed by the outer query anyway, thanks to MVCC snapshotting.)
2232 * We also relax the second restriction by supporting part of SQL:1999
2233 * feature T111, which allows for a mix of updatable and non-updatable
2234 * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2235 * a non-updatable column.
2237 * In addition we impose these constraints, involving features that are
2238 * not part of SQL-92:
2239 * - No CTEs (WITH clauses).
2240 * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2241 * - No system columns (including whole-row references) in the tlist.
2242 * - No window functions in the tlist.
2243 * - No set-returning functions in the tlist.
2245 * Note that we do these checks without recursively expanding the view.
2246 * If the base relation is a view, we'll recursively deal with it later.
2249 if (viewquery->distinctClause != NIL)
2250 return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2252 if (viewquery->groupClause != NIL || viewquery->groupingSets)
2253 return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2255 if (viewquery->havingQual != NULL)
2256 return gettext_noop("Views containing HAVING are not automatically updatable.");
2258 if (viewquery->setOperations != NULL)
2259 return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2261 if (viewquery->cteList != NIL)
2262 return gettext_noop("Views containing WITH are not automatically updatable.");
2264 if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2265 return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2268 * We must not allow window functions or set returning functions in the
2269 * targetlist. Otherwise we might end up inserting them into the quals of
2270 * the main query. We must also check for aggregates in the targetlist in
2271 * case they appear without a GROUP BY.
2273 * These restrictions ensure that each row of the view corresponds to a
2274 * unique row in the underlying base relation.
2276 if (viewquery->hasAggs)
2277 return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2279 if (viewquery->hasWindowFuncs)
2280 return gettext_noop("Views that return window functions are not automatically updatable.");
2282 if (viewquery->hasTargetSRFs)
2283 return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2286 * The view query should select from a single base relation, which must be
2287 * a table or another view.
2289 if (list_length(viewquery->jointree->fromlist) != 1)
2290 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2292 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2293 if (!IsA(rtr, RangeTblRef))
2294 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2296 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2297 if (base_rte->rtekind != RTE_RELATION ||
2298 (base_rte->relkind != RELKIND_RELATION &&
2299 base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2300 base_rte->relkind != RELKIND_VIEW &&
2301 base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2302 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2304 if (base_rte->tablesample)
2305 return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2308 * Check that the view has at least one updatable column. This is required
2309 * for INSERT/UPDATE but not for DELETE.
2317 foreach(cell, viewquery->targetList)
2319 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2321 if (view_col_is_auto_updatable(rtr, tle) == NULL)
2329 return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2332 return NULL; /* the view is updatable */
2337 * view_cols_are_auto_updatable - test whether all of the required columns of
2338 * an auto-updatable view are actually updatable. Returns NULL (if all the
2339 * required columns can be updated) or a message string giving the reason that
2342 * This should be used for INSERT/UPDATE to ensure that we don't attempt to
2343 * assign to any non-updatable columns.
2345 * Additionally it may be used to retrieve the set of updatable columns in the
2346 * view, or if one or more of the required columns is not updatable, the name
2347 * of the first offending non-updatable column.
2349 * The caller must have already verified that this is an auto-updatable view
2350 * using view_query_is_auto_updatable.
2352 * Note that the checks performed here are only based on the view definition.
2353 * We do not check whether the referenced columns of the base relation are
2357 view_cols_are_auto_updatable(Query *viewquery,
2358 Bitmapset *required_cols,
2359 Bitmapset **updatable_cols,
2360 char **non_updatable_col)
2367 * The caller should have verified that this view is auto-updatable and so
2368 * there should be a single base relation.
2370 Assert(list_length(viewquery->jointree->fromlist) == 1);
2371 rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
2373 /* Initialize the optional return values */
2374 if (updatable_cols != NULL)
2375 *updatable_cols = NULL;
2376 if (non_updatable_col != NULL)
2377 *non_updatable_col = NULL;
2379 /* Test each view column for updatability */
2380 col = -FirstLowInvalidHeapAttributeNumber;
2381 foreach(cell, viewquery->targetList)
2383 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2384 const char *col_update_detail;
2387 col_update_detail = view_col_is_auto_updatable(rtr, tle);
2389 if (col_update_detail == NULL)
2391 /* The column is updatable */
2392 if (updatable_cols != NULL)
2393 *updatable_cols = bms_add_member(*updatable_cols, col);
2395 else if (bms_is_member(col, required_cols))
2397 /* The required column is not updatable */
2398 if (non_updatable_col != NULL)
2399 *non_updatable_col = tle->resname;
2400 return col_update_detail;
2404 return NULL; /* all the required view columns are updatable */
2409 * relation_is_updatable - determine which update events the specified
2410 * relation supports.
2412 * Note that views may contain a mix of updatable and non-updatable columns.
2413 * For a view to support INSERT/UPDATE it must have at least one updatable
2414 * column, but there is no such restriction for DELETE. If include_cols is
2415 * non-NULL, then only the specified columns are considered when testing for
2418 * This is used for the information_schema views, which have separate concepts
2419 * of "updatable" and "trigger updatable". A relation is "updatable" if it
2420 * can be updated without the need for triggers (either because it has a
2421 * suitable RULE, or because it is simple enough to be automatically updated).
2422 * A relation is "trigger updatable" if it has a suitable INSTEAD OF trigger.
2423 * The SQL standard regards this as not necessarily updatable, presumably
2424 * because there is no way of knowing what the trigger will actually do.
2425 * The information_schema views therefore call this function with
2426 * include_triggers = false. However, other callers might only care whether
2427 * data-modifying SQL will work, so they can pass include_triggers = true
2428 * to have trigger updatability included in the result.
2430 * The return value is a bitmask of rule event numbers indicating which of
2431 * the INSERT, UPDATE and DELETE operations are supported. (We do it this way
2432 * so that we can test for UPDATE plus DELETE support in a single call.)
2435 relation_is_updatable(Oid reloid,
2436 bool include_triggers,
2437 Bitmapset *include_cols)
2441 RuleLock *rulelocks;
2443 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2445 rel = try_relation_open(reloid, AccessShareLock);
2448 * If the relation doesn't exist, return zero rather than throwing an
2449 * error. This is helpful since scanning an information_schema view under
2450 * MVCC rules can result in referencing rels that have actually been
2456 /* If the relation is a table, it is always updatable */
2457 if (rel->rd_rel->relkind == RELKIND_RELATION ||
2458 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2460 relation_close(rel, AccessShareLock);
2464 /* Look for unconditional DO INSTEAD rules, and note supported events */
2465 rulelocks = rel->rd_rules;
2466 if (rulelocks != NULL)
2470 for (i = 0; i < rulelocks->numLocks; i++)
2472 if (rulelocks->rules[i]->isInstead &&
2473 rulelocks->rules[i]->qual == NULL)
2475 events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2479 /* If we have rules for all events, we're done */
2480 if (events == ALL_EVENTS)
2482 relation_close(rel, AccessShareLock);
2487 /* Similarly look for INSTEAD OF triggers, if they are to be included */
2488 if (include_triggers)
2490 TriggerDesc *trigDesc = rel->trigdesc;
2494 if (trigDesc->trig_insert_instead_row)
2495 events |= (1 << CMD_INSERT);
2496 if (trigDesc->trig_update_instead_row)
2497 events |= (1 << CMD_UPDATE);
2498 if (trigDesc->trig_delete_instead_row)
2499 events |= (1 << CMD_DELETE);
2501 /* If we have triggers for all events, we're done */
2502 if (events == ALL_EVENTS)
2504 relation_close(rel, AccessShareLock);
2510 /* If this is a foreign table, check which update events it supports */
2511 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2513 FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2515 if (fdwroutine->IsForeignRelUpdatable != NULL)
2516 events |= fdwroutine->IsForeignRelUpdatable(rel);
2519 /* Assume presence of executor functions is sufficient */
2520 if (fdwroutine->ExecForeignInsert != NULL)
2521 events |= (1 << CMD_INSERT);
2522 if (fdwroutine->ExecForeignUpdate != NULL)
2523 events |= (1 << CMD_UPDATE);
2524 if (fdwroutine->ExecForeignDelete != NULL)
2525 events |= (1 << CMD_DELETE);
2528 relation_close(rel, AccessShareLock);
2532 /* Check if this is an automatically updatable view */
2533 if (rel->rd_rel->relkind == RELKIND_VIEW)
2535 Query *viewquery = get_view_query(rel);
2537 if (view_query_is_auto_updatable(viewquery, false) == NULL)
2539 Bitmapset *updatable_cols;
2542 RangeTblEntry *base_rte;
2546 * Determine which of the view's columns are updatable. If there
2547 * are none within the set of columns we are looking at, then the
2548 * view doesn't support INSERT/UPDATE, but it may still support
2551 view_cols_are_auto_updatable(viewquery, NULL,
2552 &updatable_cols, NULL);
2554 if (include_cols != NULL)
2555 updatable_cols = bms_int_members(updatable_cols, include_cols);
2557 if (bms_is_empty(updatable_cols))
2558 auto_events = (1 << CMD_DELETE); /* May support DELETE */
2560 auto_events = ALL_EVENTS; /* May support all events */
2563 * The base relation must also support these update commands.
2564 * Tables are always updatable, but for any other kind of base
2565 * relation we must do a recursive check limited to the columns
2566 * referenced by the locally updatable columns in this view.
2568 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2569 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2570 Assert(base_rte->rtekind == RTE_RELATION);
2572 if (base_rte->relkind != RELKIND_RELATION &&
2573 base_rte->relkind != RELKIND_PARTITIONED_TABLE)
2575 baseoid = base_rte->relid;
2576 include_cols = adjust_view_column_set(updatable_cols,
2577 viewquery->targetList);
2578 auto_events &= relation_is_updatable(baseoid,
2582 events |= auto_events;
2586 /* If we reach here, the relation may support some update commands */
2587 relation_close(rel, AccessShareLock);
2593 * adjust_view_column_set - map a set of column numbers according to targetlist
2595 * This is used with simply-updatable views to map column-permissions sets for
2596 * the view columns onto the matching columns in the underlying base relation.
2597 * The targetlist is expected to be a list of plain Vars of the underlying
2598 * relation (as per the checks above in view_query_is_auto_updatable).
2601 adjust_view_column_set(Bitmapset *cols, List *targetlist)
2603 Bitmapset *result = NULL;
2607 while ((col = bms_next_member(cols, col)) >= 0)
2609 /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
2610 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
2612 if (attno == InvalidAttrNumber)
2615 * There's a whole-row reference to the view. For permissions
2616 * purposes, treat it as a reference to each column available from
2617 * the view. (We should *not* convert this to a whole-row
2618 * reference to the base relation, since the view may not touch
2619 * all columns of the base relation.)
2623 foreach(lc, targetlist)
2625 TargetEntry *tle = lfirst_node(TargetEntry, lc);
2630 var = castNode(Var, tle->expr);
2631 result = bms_add_member(result,
2632 var->varattno - FirstLowInvalidHeapAttributeNumber);
2638 * Views do not have system columns, so we do not expect to see
2639 * any other system attnos here. If we do find one, the error
2642 TargetEntry *tle = get_tle_by_resno(targetlist, attno);
2644 if (tle != NULL && !tle->resjunk && IsA(tle->expr, Var))
2646 Var *var = (Var *) tle->expr;
2648 result = bms_add_member(result,
2649 var->varattno - FirstLowInvalidHeapAttributeNumber);
2652 elog(ERROR, "attribute number %d not found in view targetlist",
2662 * rewriteTargetView -
2663 * Attempt to rewrite a query where the target relation is a view, so that
2664 * the view's base relation becomes the target relation.
2666 * Note that the base relation here may itself be a view, which may or may not
2667 * have INSTEAD OF triggers or rules to handle the update. That is handled by
2668 * the recursion in RewriteQuery.
2671 rewriteTargetView(Query *parsetree, Relation view)
2674 const char *auto_update_detail;
2678 RangeTblEntry *base_rte;
2679 RangeTblEntry *view_rte;
2680 RangeTblEntry *new_rte;
2682 List *view_targetlist;
2686 * Get the Query from the view's ON SELECT rule. We're going to munge the
2687 * Query to change the view's base relation into the target relation,
2688 * along with various other changes along the way, so we need to make a
2689 * copy of it (get_view_query() returns a pointer into the relcache, so we
2690 * have to treat it as read-only).
2692 viewquery = copyObject(get_view_query(view));
2694 /* The view must be updatable, else fail */
2695 auto_update_detail =
2696 view_query_is_auto_updatable(viewquery,
2697 parsetree->commandType != CMD_DELETE);
2699 if (auto_update_detail)
2701 /* messages here should match execMain.c's CheckValidResultRel */
2702 switch (parsetree->commandType)
2706 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2707 errmsg("cannot insert into view \"%s\"",
2708 RelationGetRelationName(view)),
2709 errdetail_internal("%s", _(auto_update_detail)),
2710 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
2714 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2715 errmsg("cannot update view \"%s\"",
2716 RelationGetRelationName(view)),
2717 errdetail_internal("%s", _(auto_update_detail)),
2718 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
2722 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2723 errmsg("cannot delete from view \"%s\"",
2724 RelationGetRelationName(view)),
2725 errdetail_internal("%s", _(auto_update_detail)),
2726 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
2729 elog(ERROR, "unrecognized CmdType: %d",
2730 (int) parsetree->commandType);
2736 * For INSERT/UPDATE the modified columns must all be updatable. Note that
2737 * we get the modified columns from the query's targetlist, not from the
2738 * result RTE's insertedCols and/or updatedCols set, since
2739 * rewriteTargetListIU may have added additional targetlist entries for
2740 * view defaults, and these must also be updatable.
2742 if (parsetree->commandType != CMD_DELETE)
2744 Bitmapset *modified_cols = NULL;
2745 char *non_updatable_col;
2747 foreach(lc, parsetree->targetList)
2749 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2752 modified_cols = bms_add_member(modified_cols,
2753 tle->resno - FirstLowInvalidHeapAttributeNumber);
2756 if (parsetree->onConflict)
2758 foreach(lc, parsetree->onConflict->onConflictSet)
2760 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2763 modified_cols = bms_add_member(modified_cols,
2764 tle->resno - FirstLowInvalidHeapAttributeNumber);
2768 auto_update_detail = view_cols_are_auto_updatable(viewquery,
2771 &non_updatable_col);
2772 if (auto_update_detail)
2775 * This is a different error, caused by an attempt to update a
2776 * non-updatable column in an otherwise updatable view.
2778 switch (parsetree->commandType)
2782 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2783 errmsg("cannot insert into column \"%s\" of view \"%s\"",
2785 RelationGetRelationName(view)),
2786 errdetail_internal("%s", _(auto_update_detail))));
2790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2791 errmsg("cannot update column \"%s\" of view \"%s\"",
2793 RelationGetRelationName(view)),
2794 errdetail_internal("%s", _(auto_update_detail))));
2797 elog(ERROR, "unrecognized CmdType: %d",
2798 (int) parsetree->commandType);
2804 /* Locate RTE describing the view in the outer query */
2805 view_rte = rt_fetch(parsetree->resultRelation, parsetree->rtable);
2808 * If we get here, view_query_is_auto_updatable() has verified that the
2809 * view contains a single base relation.
2811 Assert(list_length(viewquery->jointree->fromlist) == 1);
2812 rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
2814 base_rt_index = rtr->rtindex;
2815 base_rte = rt_fetch(base_rt_index, viewquery->rtable);
2816 Assert(base_rte->rtekind == RTE_RELATION);
2819 * Up to now, the base relation hasn't been touched at all in our query.
2820 * We need to acquire lock on it before we try to do anything with it.
2821 * (The subsequent recursive call of RewriteQuery will suppose that we
2822 * already have the right lock!) Since it will become the query target
2823 * relation, RowExclusiveLock is always the right thing.
2825 base_rel = heap_open(base_rte->relid, RowExclusiveLock);
2828 * While we have the relation open, update the RTE's relkind, just in case
2829 * it changed since this view was made (cf. AcquireRewriteLocks).
2831 base_rte->relkind = base_rel->rd_rel->relkind;
2833 heap_close(base_rel, NoLock);
2836 * If the view query contains any sublink subqueries then we need to also
2837 * acquire locks on any relations they refer to. We know that there won't
2838 * be any subqueries in the range table or CTEs, so we can skip those, as
2839 * in AcquireRewriteLocks.
2841 if (viewquery->hasSubLinks)
2843 acquireLocksOnSubLinks_context context;
2845 context.for_execute = true;
2846 query_tree_walker(viewquery, acquireLocksOnSubLinks, &context,
2847 QTW_IGNORE_RC_SUBQUERIES);
2851 * Create a new target RTE describing the base relation, and add it to the
2852 * outer query's rangetable. (What's happening in the next few steps is
2853 * very much like what the planner would do to "pull up" the view into the
2854 * outer query. Perhaps someday we should refactor things enough so that
2855 * we can share code with the planner.)
2857 new_rte = (RangeTblEntry *) base_rte;
2858 parsetree->rtable = lappend(parsetree->rtable, new_rte);
2859 new_rt_index = list_length(parsetree->rtable);
2862 * INSERTs never inherit. For UPDATE/DELETE, we use the view query's
2863 * inheritance flag for the base relation.
2865 if (parsetree->commandType == CMD_INSERT)
2866 new_rte->inh = false;
2869 * Adjust the view's targetlist Vars to reference the new target RTE, ie
2870 * make their varnos be new_rt_index instead of base_rt_index. There can
2871 * be no Vars for other rels in the tlist, so this is sufficient to pull
2872 * up the tlist expressions for use in the outer query. The tlist will
2873 * provide the replacement expressions used by ReplaceVarsFromTargetList
2876 view_targetlist = viewquery->targetList;
2878 ChangeVarNodes((Node *) view_targetlist,
2884 * Mark the new target RTE for the permissions checks that we want to
2885 * enforce against the view owner, as distinct from the query caller. At
2886 * the relation level, require the same INSERT/UPDATE/DELETE permissions
2887 * that the query caller needs against the view. We drop the ACL_SELECT
2888 * bit that is presumably in new_rte->requiredPerms initially.
2890 * Note: the original view RTE remains in the query's rangetable list.
2891 * Although it will be unused in the query plan, we need it there so that
2892 * the executor still performs appropriate permissions checks for the
2893 * query caller's use of the view.
2895 new_rte->checkAsUser = view->rd_rel->relowner;
2896 new_rte->requiredPerms = view_rte->requiredPerms;
2899 * Now for the per-column permissions bits.
2901 * Initially, new_rte contains selectedCols permission check bits for all
2902 * base-rel columns referenced by the view, but since the view is a SELECT
2903 * query its insertedCols/updatedCols is empty. We set insertedCols and
2904 * updatedCols to include all the columns the outer query is trying to
2905 * modify, adjusting the column numbers as needed. But we leave
2906 * selectedCols as-is, so the view owner must have read permission for all
2907 * columns used in the view definition, even if some of them are not read
2908 * by the outer query. We could try to limit selectedCols to only columns
2909 * used in the transformed query, but that does not correspond to what
2910 * happens in ordinary SELECT usage of a view: all referenced columns must
2911 * have read permission, even if optimization finds that some of them can
2912 * be discarded during query transformation. The flattening we're doing
2913 * here is an optional optimization, too. (If you are unpersuaded and
2914 * want to change this, note that applying adjust_view_column_set to
2915 * view_rte->selectedCols is clearly *not* the right answer, since that
2916 * neglects base-rel columns used in the view's WHERE quals.)
2918 * This step needs the modified view targetlist, so we have to do things
2921 Assert(bms_is_empty(new_rte->insertedCols) &&
2922 bms_is_empty(new_rte->updatedCols));
2924 new_rte->insertedCols = adjust_view_column_set(view_rte->insertedCols,
2927 new_rte->updatedCols = adjust_view_column_set(view_rte->updatedCols,
2931 * Move any security barrier quals from the view RTE onto the new target
2932 * RTE. Any such quals should now apply to the new target RTE and will
2933 * not reference the original view RTE in the rewritten query.
2935 new_rte->securityQuals = view_rte->securityQuals;
2936 view_rte->securityQuals = NIL;
2939 * For UPDATE/DELETE, rewriteTargetListUD will have added a wholerow junk
2940 * TLE for the view to the end of the targetlist, which we no longer need.
2941 * Remove it to avoid unnecessary work when we process the targetlist.
2942 * Note that when we recurse through rewriteQuery a new junk TLE will be
2943 * added to allow the executor to find the proper row in the new target
2944 * relation. (So, if we failed to do this, we might have multiple junk
2945 * TLEs with the same name, which would be disastrous.)
2947 if (parsetree->commandType != CMD_INSERT)
2949 TargetEntry *tle = (TargetEntry *) llast(parsetree->targetList);
2951 Assert(tle->resjunk);
2952 Assert(IsA(tle->expr, Var) &&
2953 ((Var *) tle->expr)->varno == parsetree->resultRelation &&
2954 ((Var *) tle->expr)->varattno == 0);
2955 parsetree->targetList = list_delete_ptr(parsetree->targetList, tle);
2959 * Now update all Vars in the outer query that reference the view to
2960 * reference the appropriate column of the base relation instead.
2962 parsetree = (Query *)
2963 ReplaceVarsFromTargetList((Node *) parsetree,
2964 parsetree->resultRelation,
2968 REPLACEVARS_REPORT_ERROR,
2970 &parsetree->hasSubLinks);
2973 * Update all other RTI references in the query that point to the view
2974 * (for example, parsetree->resultRelation itself) to point to the new
2975 * base relation instead. Vars will not be affected since none of them
2976 * reference parsetree->resultRelation any longer.
2978 ChangeVarNodes((Node *) parsetree,
2979 parsetree->resultRelation,
2982 Assert(parsetree->resultRelation == new_rt_index);
2985 * For INSERT/UPDATE we must also update resnos in the targetlist to refer
2986 * to columns of the base relation, since those indicate the target
2987 * columns to be affected.
2989 * Note that this destroys the resno ordering of the targetlist, but that
2990 * will be fixed when we recurse through rewriteQuery, which will invoke
2991 * rewriteTargetListIU again on the updated targetlist.
2993 if (parsetree->commandType != CMD_DELETE)
2995 foreach(lc, parsetree->targetList)
2997 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2998 TargetEntry *view_tle;
3003 view_tle = get_tle_by_resno(view_targetlist, tle->resno);
3004 if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
3005 tle->resno = ((Var *) view_tle->expr)->varattno;
3007 elog(ERROR, "attribute number %d not found in view targetlist",
3013 * For UPDATE/DELETE, pull up any WHERE quals from the view. We know that
3014 * any Vars in the quals must reference the one base relation, so we need
3015 * only adjust their varnos to reference the new target (just the same as
3016 * we did with the view targetlist).
3018 * If it's a security-barrier view, its WHERE quals must be applied before
3019 * quals from the outer query, so we attach them to the RTE as security
3020 * barrier quals rather than adding them to the main WHERE clause.
3022 * For INSERT, the view's quals can be ignored in the main query.
3024 if (parsetree->commandType != CMD_INSERT &&
3025 viewquery->jointree->quals != NULL)
3027 Node *viewqual = (Node *) viewquery->jointree->quals;
3030 * Even though we copied viewquery already at the top of this
3031 * function, we must duplicate the viewqual again here, because we may
3032 * need to use the quals again below for a WithCheckOption clause.
3034 viewqual = copyObject(viewqual);
3036 ChangeVarNodes(viewqual, base_rt_index, new_rt_index, 0);
3038 if (RelationIsSecurityView(view))
3041 * The view's quals go in front of existing barrier quals: those
3042 * would have come from an outer level of security-barrier view,
3043 * and so must get evaluated later.
3045 * Note: the parsetree has been mutated, so the new_rte pointer is
3046 * stale and needs to be re-computed.
3048 new_rte = rt_fetch(new_rt_index, parsetree->rtable);
3049 new_rte->securityQuals = lcons(viewqual, new_rte->securityQuals);
3052 * Do not set parsetree->hasRowSecurity, because these aren't RLS
3053 * conditions (they aren't affected by enabling/disabling RLS).
3057 * Make sure that the query is marked correctly if the added qual
3060 if (!parsetree->hasSubLinks)
3061 parsetree->hasSubLinks = checkExprHasSubLink(viewqual);
3064 AddQual(parsetree, (Node *) viewqual);
3068 * For INSERT/UPDATE, if the view has the WITH CHECK OPTION, or any parent
3069 * view specified WITH CASCADED CHECK OPTION, add the quals from the view
3070 * to the query's withCheckOptions list.
3072 if (parsetree->commandType != CMD_DELETE)
3074 bool has_wco = RelationHasCheckOption(view);
3075 bool cascaded = RelationHasCascadedCheckOption(view);
3078 * If the parent view has a cascaded check option, treat this view as
3079 * if it also had a cascaded check option.
3081 * New WithCheckOptions are added to the start of the list, so if
3082 * there is a cascaded check option, it will be the first item in the
3085 if (parsetree->withCheckOptions != NIL)
3087 WithCheckOption *parent_wco =
3088 (WithCheckOption *) linitial(parsetree->withCheckOptions);
3090 if (parent_wco->cascaded)
3098 * Add the new WithCheckOption to the start of the list, so that
3099 * checks on inner views are run before checks on outer views, as
3100 * required by the SQL standard.
3102 * If the new check is CASCADED, we need to add it even if this view
3103 * has no quals, since there may be quals on child views. A LOCAL
3104 * check can be omitted if this view has no quals.
3106 if (has_wco && (cascaded || viewquery->jointree->quals != NULL))
3108 WithCheckOption *wco;
3110 wco = makeNode(WithCheckOption);
3111 wco->kind = WCO_VIEW_CHECK;
3112 wco->relname = pstrdup(RelationGetRelationName(view));
3113 wco->polname = NULL;
3115 wco->cascaded = cascaded;
3117 parsetree->withCheckOptions = lcons(wco,
3118 parsetree->withCheckOptions);
3120 if (viewquery->jointree->quals != NULL)
3122 wco->qual = (Node *) viewquery->jointree->quals;
3123 ChangeVarNodes(wco->qual, base_rt_index, new_rt_index, 0);
3126 * Make sure that the query is marked correctly if the added
3127 * qual has sublinks. We can skip this check if the query is
3128 * already marked, or if the command is an UPDATE, in which
3129 * case the same qual will have already been added, and this
3130 * check will already have been done.
3132 if (!parsetree->hasSubLinks &&
3133 parsetree->commandType != CMD_UPDATE)
3134 parsetree->hasSubLinks = checkExprHasSubLink(wco->qual);
3145 * rewrites the query and apply the rules again on the queries rewritten
3147 * rewrite_events is a list of open query-rewrite actions, so we can detect
3148 * infinite recursion.
3151 RewriteQuery(Query *parsetree, List *rewrite_events)
3153 CmdType event = parsetree->commandType;
3154 bool instead = false;
3155 bool returning = false;
3156 bool updatableview = false;
3157 Query *qual_product = NULL;
3158 List *rewritten = NIL;
3162 * First, recursively process any insert/update/delete statements in WITH
3163 * clauses. (We have to do this first because the WITH clauses may get
3164 * copied into rule actions below.)
3166 foreach(lc1, parsetree->cteList)
3168 CommonTableExpr *cte = lfirst_node(CommonTableExpr, lc1);
3169 Query *ctequery = castNode(Query, cte->ctequery);
3172 if (ctequery->commandType == CMD_SELECT)
3175 newstuff = RewriteQuery(ctequery, rewrite_events);
3178 * Currently we can only handle unconditional, single-statement DO
3179 * INSTEAD rules correctly; we have to get exactly one Query out of
3180 * the rewrite operation to stuff back into the CTE node.
3182 if (list_length(newstuff) == 1)
3184 /* Push the single Query back into the CTE node */
3185 ctequery = linitial_node(Query, newstuff);
3186 /* WITH queries should never be canSetTag */
3187 Assert(!ctequery->canSetTag);
3188 cte->ctequery = (Node *) ctequery;
3190 else if (newstuff == NIL)
3193 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3194 errmsg("DO INSTEAD NOTHING rules are not supported for data-modifying statements in WITH")));
3200 /* examine queries to determine which error message to issue */
3201 foreach(lc2, newstuff)
3203 Query *q = (Query *) lfirst(lc2);
3205 if (q->querySource == QSRC_QUAL_INSTEAD_RULE)
3207 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3208 errmsg("conditional DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3209 if (q->querySource == QSRC_NON_INSTEAD_RULE)
3211 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3212 errmsg("DO ALSO rules are not supported for data-modifying statements in WITH")));
3216 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3217 errmsg("multi-statement DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3222 * If the statement is an insert, update, or delete, adjust its targetlist
3223 * as needed, and then fire INSERT/UPDATE/DELETE rules on it.
3225 * SELECT rules are handled later when we have all the queries that should
3226 * get executed. Also, utilities aren't rewritten at all (do we still
3229 if (event != CMD_SELECT && event != CMD_UTILITY)
3231 int result_relation;
3232 RangeTblEntry *rt_entry;
3233 Relation rt_entry_relation;
3235 List *product_queries;
3236 bool hasUpdate = false;
3238 result_relation = parsetree->resultRelation;
3239 Assert(result_relation != 0);
3240 rt_entry = rt_fetch(result_relation, parsetree->rtable);
3241 Assert(rt_entry->rtekind == RTE_RELATION);
3244 * We can use NoLock here since either the parser or
3245 * AcquireRewriteLocks should have locked the rel already.
3247 rt_entry_relation = heap_open(rt_entry->relid, NoLock);
3250 * Rewrite the targetlist as needed for the command type.
3252 if (event == CMD_INSERT)
3254 RangeTblEntry *values_rte = NULL;
3257 * If it's an INSERT ... VALUES (...), (...), ... there will be a
3258 * single RTE for the VALUES targetlists.
3260 if (list_length(parsetree->jointree->fromlist) == 1)
3262 RangeTblRef *rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
3264 if (IsA(rtr, RangeTblRef))
3266 RangeTblEntry *rte = rt_fetch(rtr->rtindex,
3269 if (rte->rtekind == RTE_VALUES)
3278 /* Process the main targetlist ... */
3279 parsetree->targetList = rewriteTargetListIU(parsetree->targetList,
3280 parsetree->commandType,
3281 parsetree->override,
3283 parsetree->resultRelation,
3285 /* ... and the VALUES expression lists */
3286 rewriteValuesRTE(values_rte, rt_entry_relation, attrnos);
3290 /* Process just the main targetlist */
3291 parsetree->targetList =
3292 rewriteTargetListIU(parsetree->targetList,
3293 parsetree->commandType,
3294 parsetree->override,
3296 parsetree->resultRelation, NULL);
3299 if (parsetree->onConflict &&
3300 parsetree->onConflict->action == ONCONFLICT_UPDATE)
3302 parsetree->onConflict->onConflictSet =
3303 rewriteTargetListIU(parsetree->onConflict->onConflictSet,
3305 parsetree->override,
3307 parsetree->resultRelation,
3311 else if (event == CMD_UPDATE)
3313 parsetree->targetList =
3314 rewriteTargetListIU(parsetree->targetList,
3315 parsetree->commandType,
3316 parsetree->override,
3318 parsetree->resultRelation, NULL);
3319 rewriteTargetListUD(parsetree, rt_entry, rt_entry_relation);
3321 else if (event == CMD_DELETE)
3323 rewriteTargetListUD(parsetree, rt_entry, rt_entry_relation);
3326 elog(ERROR, "unrecognized commandType: %d", (int) event);
3329 * Collect and apply the appropriate rules.
3331 locks = matchLocks(event, rt_entry_relation->rd_rules,
3332 result_relation, parsetree, &hasUpdate);
3334 product_queries = fireRules(parsetree,
3343 * If there were no INSTEAD rules, and the target relation is a view
3344 * without any INSTEAD OF triggers, see if the view can be
3345 * automatically updated. If so, we perform the necessary query
3346 * transformation here and add the resulting query to the
3347 * product_queries list, so that it gets recursively rewritten if
3350 if (!instead && qual_product == NULL &&
3351 rt_entry_relation->rd_rel->relkind == RELKIND_VIEW &&
3352 !view_has_instead_trigger(rt_entry_relation, event))
3355 * This throws an error if the view can't be automatically
3356 * updated, but that's OK since the query would fail at runtime
3359 parsetree = rewriteTargetView(parsetree, rt_entry_relation);
3362 * At this point product_queries contains any DO ALSO rule
3363 * actions. Add the rewritten query before or after those. This
3364 * must match the handling the original query would have gotten
3365 * below, if we allowed it to be included again.
3367 if (parsetree->commandType == CMD_INSERT)
3368 product_queries = lcons(parsetree, product_queries);
3370 product_queries = lappend(product_queries, parsetree);
3373 * Set the "instead" flag, as if there had been an unqualified
3374 * INSTEAD, to prevent the original query from being included a
3375 * second time below. The transformation will have rewritten any
3376 * RETURNING list, so we can also set "returning" to forestall
3377 * throwing an error below.
3381 updatableview = true;
3385 * If we got any product queries, recursively rewrite them --- but
3386 * first check for recursion!
3388 if (product_queries != NIL)
3393 foreach(n, rewrite_events)
3395 rev = (rewrite_event *) lfirst(n);
3396 if (rev->relation == RelationGetRelid(rt_entry_relation) &&
3397 rev->event == event)
3399 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3400 errmsg("infinite recursion detected in rules for relation \"%s\"",
3401 RelationGetRelationName(rt_entry_relation))));
3404 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
3405 rev->relation = RelationGetRelid(rt_entry_relation);
3407 rewrite_events = lcons(rev, rewrite_events);
3409 foreach(n, product_queries)
3411 Query *pt = (Query *) lfirst(n);
3414 newstuff = RewriteQuery(pt, rewrite_events);
3415 rewritten = list_concat(rewritten, newstuff);
3418 rewrite_events = list_delete_first(rewrite_events);
3422 * If there is an INSTEAD, and the original query has a RETURNING, we
3423 * have to have found a RETURNING in the rule(s), else fail. (Because
3424 * DefineQueryRewrite only allows RETURNING in unconditional INSTEAD
3425 * rules, there's no need to worry whether the substituted RETURNING
3426 * will actually be executed --- it must be.)
3428 if ((instead || qual_product != NULL) &&
3429 parsetree->returningList &&
3436 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3437 errmsg("cannot perform INSERT RETURNING on relation \"%s\"",
3438 RelationGetRelationName(rt_entry_relation)),
3439 errhint("You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.")));
3443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3444 errmsg("cannot perform UPDATE RETURNING on relation \"%s\"",
3445 RelationGetRelationName(rt_entry_relation)),
3446 errhint("You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.")));
3450 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3451 errmsg("cannot perform DELETE RETURNING on relation \"%s\"",
3452 RelationGetRelationName(rt_entry_relation)),
3453 errhint("You need an unconditional ON DELETE DO INSTEAD rule with a RETURNING clause.")));
3456 elog(ERROR, "unrecognized commandType: %d",
3463 * Updatable views are supported by ON CONFLICT, so don't prevent that
3464 * case from proceeding
3466 if (parsetree->onConflict &&
3467 (product_queries != NIL || hasUpdate) &&
3470 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3471 errmsg("INSERT with ON CONFLICT clause cannot be used with table that has INSERT or UPDATE rules")));
3473 heap_close(rt_entry_relation, NoLock);
3477 * For INSERTs, the original query is done first; for UPDATE/DELETE, it is
3478 * done last. This is needed because update and delete rule actions might
3479 * not do anything if they are invoked after the update or delete is
3480 * performed. The command counter increment between the query executions
3481 * makes the deleted (and maybe the updated) tuples disappear so the scans
3482 * for them in the rule actions cannot find them.
3484 * If we found any unqualified INSTEAD, the original query is not done at
3485 * all, in any form. Otherwise, we add the modified form if qualified
3486 * INSTEADs were found, else the unmodified form.
3490 if (parsetree->commandType == CMD_INSERT)
3492 if (qual_product != NULL)
3493 rewritten = lcons(qual_product, rewritten);
3495 rewritten = lcons(parsetree, rewritten);
3499 if (qual_product != NULL)
3500 rewritten = lappend(rewritten, qual_product);
3502 rewritten = lappend(rewritten, parsetree);
3507 * If the original query has a CTE list, and we generated more than one
3508 * non-utility result query, we have to fail because we'll have copied the
3509 * CTE list into each result query. That would break the expectation of
3510 * single evaluation of CTEs. This could possibly be fixed by
3511 * restructuring so that a CTE list can be shared across multiple Query
3512 * and PlannableStatement nodes.
3514 if (parsetree->cteList != NIL)
3518 foreach(lc1, rewritten)
3520 Query *q = (Query *) lfirst(lc1);
3522 if (q->commandType != CMD_UTILITY)
3527 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3528 errmsg("WITH cannot be used in a query that is rewritten by rules into multiple queries")));
3537 * Primary entry point to the query rewriter.
3538 * Rewrite one query via query rewrite system, possibly returning 0
3541 * NOTE: the parsetree must either have come straight from the parser,
3542 * or have been scanned by AcquireRewriteLocks to acquire suitable locks.
3545 QueryRewrite(Query *parsetree)
3547 uint32 input_query_id = parsetree->queryId;
3551 CmdType origCmdType;
3552 bool foundOriginalQuery;
3556 * This function is only applied to top-level original queries
3558 Assert(parsetree->querySource == QSRC_ORIGINAL);
3559 Assert(parsetree->canSetTag);
3564 * Apply all non-SELECT rules possibly getting 0 or many queries
3566 querylist = RewriteQuery(parsetree, NIL);
3571 * Apply all the RIR rules on each query
3573 * This is also a handy place to mark each query with the original queryId
3576 foreach(l, querylist)
3578 Query *query = (Query *) lfirst(l);
3580 query = fireRIRrules(query, NIL, false);
3582 query->queryId = input_query_id;
3584 results = lappend(results, query);
3590 * Determine which, if any, of the resulting queries is supposed to set
3591 * the command-result tag; and update the canSetTag fields accordingly.
3593 * If the original query is still in the list, it sets the command tag.
3594 * Otherwise, the last INSTEAD query of the same kind as the original is
3595 * allowed to set the tag. (Note these rules can leave us with no query
3596 * setting the tag. The tcop code has to cope with this by setting up a
3597 * default tag based on the original un-rewritten query.)
3599 * The Asserts verify that at most one query in the result list is marked
3600 * canSetTag. If we aren't checking asserts, we can fall out of the loop
3601 * as soon as we find the original query.
3603 origCmdType = parsetree->commandType;
3604 foundOriginalQuery = false;
3609 Query *query = (Query *) lfirst(l);
3611 if (query->querySource == QSRC_ORIGINAL)
3613 Assert(query->canSetTag);
3614 Assert(!foundOriginalQuery);
3615 foundOriginalQuery = true;
3616 #ifndef USE_ASSERT_CHECKING
3622 Assert(!query->canSetTag);
3623 if (query->commandType == origCmdType &&
3624 (query->querySource == QSRC_INSTEAD_RULE ||
3625 query->querySource == QSRC_QUAL_INSTEAD_RULE))
3626 lastInstead = query;
3630 if (!foundOriginalQuery && lastInstead != NULL)
3631 lastInstead->canSetTag = true;