1 /*-------------------------------------------------------------------------
2 *
3 * rewriteHandler.c
4 * Primary module of query rewriter.
5 *
6 * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 * IDENTIFICATION
10 * src/backend/rewrite/rewriteHandler.c
11 *
12 * NOTES
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
17 * relation).
18 *
19 *-------------------------------------------------------------------------
20 */
21 #include "postgres.h"
22
23 #include "access/relation.h"
24 #include "access/sysattr.h"
25 #include "access/table.h"
26 #include "catalog/dependency.h"
27 #include "catalog/pg_type.h"
28 #include "commands/trigger.h"
29 #include "foreign/fdwapi.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "nodes/nodeFuncs.h"
33 #include "optimizer/optimizer.h"
34 #include "parser/analyze.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_relation.h"
37 #include "parser/parsetree.h"
38 #include "rewrite/rewriteDefine.h"
39 #include "rewrite/rewriteHandler.h"
40 #include "rewrite/rewriteManip.h"
41 #include "rewrite/rowsecurity.h"
42 #include "utils/builtins.h"
43 #include "utils/lsyscache.h"
44 #include "utils/rel.h"
45
46
47 /* We use a list of these to detect recursion in RewriteQuery */
48 typedef struct rewrite_event
49 {
50 Oid relation; /* OID of relation having rules */
51 CmdType event; /* type of rule being fired */
52 } rewrite_event;
53
54 typedef struct acquireLocksOnSubLinks_context
55 {
56 bool for_execute; /* AcquireRewriteLocks' forExecute param */
57 } acquireLocksOnSubLinks_context;
58
59 static bool acquireLocksOnSubLinks(Node *node,
60 acquireLocksOnSubLinks_context *context);
61 static Query *rewriteRuleAction(Query *parsetree,
62 Query *rule_action,
63 Node *rule_qual,
64 int rt_index,
65 CmdType event,
66 bool *returning_flag);
67 static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
68 static List *rewriteTargetListIU(List *targetList,
69 CmdType commandType,
70 OverridingKind override,
71 Relation target_relation,
72 int result_rti);
73 static TargetEntry *process_matched_tle(TargetEntry *src_tle,
74 TargetEntry *prior_tle,
75 const char *attrName);
76 static Node *get_assignment_input(Node *node);
77 static bool rewriteValuesRTE(Query *parsetree, RangeTblEntry *rte, int rti,
78 Relation target_relation, bool force_nulls);
79 static void markQueryForLocking(Query *qry, Node *jtnode,
80 LockClauseStrength strength, LockWaitPolicy waitPolicy,
81 bool pushedDown);
82 static List *matchLocks(CmdType event, RuleLock *rulelocks,
83 int varno, Query *parsetree, bool *hasUpdate);
84 static Query *fireRIRrules(Query *parsetree, List *activeRIRs);
85 static bool view_has_instead_trigger(Relation view, CmdType event);
86 static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist);
87
88
89 /*
90 * AcquireRewriteLocks -
91 * Acquire suitable locks on all the relations mentioned in the Query.
92 * These locks will ensure that the relation schemas don't change under us
93 * while we are rewriting, planning, and executing the query.
94 *
95 * Caution: this may modify the querytree, therefore caller should usually
96 * have done a copyObject() to make a writable copy of the querytree in the
97 * current memory context.
98 *
99 * forExecute indicates that the query is about to be executed. If so,
100 * we'll acquire the lock modes specified in the RTE rellockmode fields.
101 * If forExecute is false, AccessShareLock is acquired on all relations.
102 * This case is suitable for ruleutils.c, for example, where we only need
103 * schema stability and we don't intend to actually modify any relations.
104 *
105 * forUpdatePushedDown indicates that a pushed-down FOR [KEY] UPDATE/SHARE
106 * applies to the current subquery, requiring all rels to be opened with at
107 * least RowShareLock. This should always be false at the top of the
108 * recursion. When it is true, we adjust RTE rellockmode fields to reflect
109 * the higher lock level. This flag is ignored if forExecute is false.
110 *
111 * A secondary purpose of this routine is to fix up JOIN RTE references to
112 * dropped columns (see details below). Such RTEs are modified in-place.
113 *
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.
119 *
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.
127 *
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.)
132 */
133 void
AcquireRewriteLocks(Query * parsetree,bool forExecute,bool forUpdatePushedDown)134 AcquireRewriteLocks(Query *parsetree,
135 bool forExecute,
136 bool forUpdatePushedDown)
137 {
138 ListCell *l;
139 int rt_index;
140 acquireLocksOnSubLinks_context context;
141
142 context.for_execute = forExecute;
143
144 /*
145 * First, process RTEs of the current query level.
146 */
147 rt_index = 0;
148 foreach(l, parsetree->rtable)
149 {
150 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
151 Relation rel;
152 LOCKMODE lockmode;
153 List *newaliasvars;
154 Index curinputvarno;
155 RangeTblEntry *curinputrte;
156 ListCell *ll;
157
158 ++rt_index;
159 switch (rte->rtekind)
160 {
161 case RTE_RELATION:
162
163 /*
164 * Grab the appropriate lock type for the relation, and do not
165 * release it until end of transaction. This protects the
166 * rewriter, planner, and executor against schema changes
167 * mid-query.
168 *
169 * If forExecute is false, ignore rellockmode and just use
170 * AccessShareLock.
171 */
172 if (!forExecute)
173 lockmode = AccessShareLock;
174 else if (forUpdatePushedDown)
175 {
176 /* Upgrade RTE's lock mode to reflect pushed-down lock */
177 if (rte->rellockmode == AccessShareLock)
178 rte->rellockmode = RowShareLock;
179 lockmode = rte->rellockmode;
180 }
181 else
182 lockmode = rte->rellockmode;
183
184 rel = table_open(rte->relid, lockmode);
185
186 /*
187 * While we have the relation open, update the RTE's relkind,
188 * just in case it changed since this rule was made.
189 */
190 rte->relkind = rel->rd_rel->relkind;
191
192 table_close(rel, NoLock);
193 break;
194
195 case RTE_JOIN:
196
197 /*
198 * Scan the join's alias var list to see if any columns have
199 * been dropped, and if so replace those Vars with null
200 * pointers.
201 *
202 * Since a join has only two inputs, we can expect to see
203 * multiple references to the same input RTE; optimize away
204 * multiple fetches.
205 */
206 newaliasvars = NIL;
207 curinputvarno = 0;
208 curinputrte = NULL;
209 foreach(ll, rte->joinaliasvars)
210 {
211 Var *aliasitem = (Var *) lfirst(ll);
212 Var *aliasvar = aliasitem;
213
214 /* Look through any implicit coercion */
215 aliasvar = (Var *) strip_implicit_coercions((Node *) aliasvar);
216
217 /*
218 * If the list item isn't a simple Var, then it must
219 * represent a merged column, ie a USING column, and so it
220 * couldn't possibly be dropped, since it's referenced in
221 * the join clause. (Conceivably it could also be a null
222 * pointer already? But that's OK too.)
223 */
224 if (aliasvar && IsA(aliasvar, Var))
225 {
226 /*
227 * The elements of an alias list have to refer to
228 * earlier RTEs of the same rtable, because that's the
229 * order the planner builds things in. So we already
230 * processed the referenced RTE, and so it's safe to
231 * use get_rte_attribute_is_dropped on it. (This might
232 * not hold after rewriting or planning, but it's OK
233 * to assume here.)
234 */
235 Assert(aliasvar->varlevelsup == 0);
236 if (aliasvar->varno != curinputvarno)
237 {
238 curinputvarno = aliasvar->varno;
239 if (curinputvarno >= rt_index)
240 elog(ERROR, "unexpected varno %d in JOIN RTE %d",
241 curinputvarno, rt_index);
242 curinputrte = rt_fetch(curinputvarno,
243 parsetree->rtable);
244 }
245 if (get_rte_attribute_is_dropped(curinputrte,
246 aliasvar->varattno))
247 {
248 /* Replace the join alias item with a NULL */
249 aliasitem = NULL;
250 }
251 }
252 newaliasvars = lappend(newaliasvars, aliasitem);
253 }
254 rte->joinaliasvars = newaliasvars;
255 break;
256
257 case RTE_SUBQUERY:
258
259 /*
260 * The subquery RTE itself is all right, but we have to
261 * recurse to process the represented subquery.
262 */
263 AcquireRewriteLocks(rte->subquery,
264 forExecute,
265 (forUpdatePushedDown ||
266 get_parse_rowmark(parsetree, rt_index) != NULL));
267 break;
268
269 default:
270 /* ignore other types of RTEs */
271 break;
272 }
273 }
274
275 /* Recurse into subqueries in WITH */
276 foreach(l, parsetree->cteList)
277 {
278 CommonTableExpr *cte = (CommonTableExpr *) lfirst(l);
279
280 AcquireRewriteLocks((Query *) cte->ctequery, forExecute, false);
281 }
282
283 /*
284 * Recurse into sublink subqueries, too. But we already did the ones in
285 * the rtable and cteList.
286 */
287 if (parsetree->hasSubLinks)
288 query_tree_walker(parsetree, acquireLocksOnSubLinks, &context,
289 QTW_IGNORE_RC_SUBQUERIES);
290 }
291
292 /*
293 * Walker to find sublink subqueries for AcquireRewriteLocks
294 */
295 static bool
acquireLocksOnSubLinks(Node * node,acquireLocksOnSubLinks_context * context)296 acquireLocksOnSubLinks(Node *node, acquireLocksOnSubLinks_context *context)
297 {
298 if (node == NULL)
299 return false;
300 if (IsA(node, SubLink))
301 {
302 SubLink *sub = (SubLink *) node;
303
304 /* Do what we came for */
305 AcquireRewriteLocks((Query *) sub->subselect,
306 context->for_execute,
307 false);
308 /* Fall through to process lefthand args of SubLink */
309 }
310
311 /*
312 * Do NOT recurse into Query nodes, because AcquireRewriteLocks already
313 * processed subselects of subselects for us.
314 */
315 return expression_tree_walker(node, acquireLocksOnSubLinks, context);
316 }
317
318
319 /*
320 * rewriteRuleAction -
321 * Rewrite the rule action with appropriate qualifiers (taken from
322 * the triggering query).
323 *
324 * Input arguments:
325 * parsetree - original query
326 * rule_action - one action (query) of a rule
327 * rule_qual - WHERE condition of rule, or NULL if unconditional
328 * rt_index - RT index of result relation in original query
329 * event - type of rule event
330 * Output arguments:
331 * *returning_flag - set true if we rewrite RETURNING clause in rule_action
332 * (must be initialized to false)
333 * Return value:
334 * rewritten form of rule_action
335 */
336 static Query *
rewriteRuleAction(Query * parsetree,Query * rule_action,Node * rule_qual,int rt_index,CmdType event,bool * returning_flag)337 rewriteRuleAction(Query *parsetree,
338 Query *rule_action,
339 Node *rule_qual,
340 int rt_index,
341 CmdType event,
342 bool *returning_flag)
343 {
344 int current_varno,
345 new_varno;
346 int rt_length;
347 Query *sub_action;
348 Query **sub_action_ptr;
349 acquireLocksOnSubLinks_context context;
350
351 context.for_execute = true;
352
353 /*
354 * Make modifiable copies of rule action and qual (what we're passed are
355 * the stored versions in the relcache; don't touch 'em!).
356 */
357 rule_action = copyObject(rule_action);
358 rule_qual = copyObject(rule_qual);
359
360 /*
361 * Acquire necessary locks and fix any deleted JOIN RTE entries.
362 */
363 AcquireRewriteLocks(rule_action, true, false);
364 (void) acquireLocksOnSubLinks(rule_qual, &context);
365
366 current_varno = rt_index;
367 rt_length = list_length(parsetree->rtable);
368 new_varno = PRS2_NEW_VARNO + rt_length;
369
370 /*
371 * Adjust rule action and qual to offset its varnos, so that we can merge
372 * its rtable with the main parsetree's rtable.
373 *
374 * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
375 * will be in the SELECT part, and we have to modify that rather than the
376 * top-level INSERT (kluge!).
377 */
378 sub_action = getInsertSelectQuery(rule_action, &sub_action_ptr);
379
380 OffsetVarNodes((Node *) sub_action, rt_length, 0);
381 OffsetVarNodes(rule_qual, rt_length, 0);
382 /* but references to OLD should point at original rt_index */
383 ChangeVarNodes((Node *) sub_action,
384 PRS2_OLD_VARNO + rt_length, rt_index, 0);
385 ChangeVarNodes(rule_qual,
386 PRS2_OLD_VARNO + rt_length, rt_index, 0);
387
388 /*
389 * Generate expanded rtable consisting of main parsetree's rtable plus
390 * rule action's rtable; this becomes the complete rtable for the rule
391 * action. Some of the entries may be unused after we finish rewriting,
392 * but we leave them all in place for two reasons:
393 *
394 * We'd have a much harder job to adjust the query's varnos if we
395 * selectively removed RT entries.
396 *
397 * If the rule is INSTEAD, then the original query won't be executed at
398 * all, and so its rtable must be preserved so that the executor will do
399 * the correct permissions checks on it.
400 *
401 * RT entries that are not referenced in the completed jointree will be
402 * ignored by the planner, so they do not affect query semantics. But any
403 * permissions checks specified in them will be applied during executor
404 * startup (see ExecCheckRTEPerms()). This allows us to check that the
405 * caller has, say, insert-permission on a view, when the view is not
406 * semantically referenced at all in the resulting query.
407 *
408 * When a rule is not INSTEAD, the permissions checks done on its copied
409 * RT entries will be redundant with those done during execution of the
410 * original query, but we don't bother to treat that case differently.
411 *
412 * NOTE: because planner will destructively alter rtable, we must ensure
413 * that rule action's rtable is separate and shares no substructure with
414 * the main rtable. Hence do a deep copy here.
415 */
416 sub_action->rtable = list_concat(copyObject(parsetree->rtable),
417 sub_action->rtable);
418
419 /*
420 * There could have been some SubLinks in parsetree's rtable, in which
421 * case we'd better mark the sub_action correctly.
422 */
423 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
424 {
425 ListCell *lc;
426
427 foreach(lc, parsetree->rtable)
428 {
429 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
430
431 switch (rte->rtekind)
432 {
433 case RTE_RELATION:
434 sub_action->hasSubLinks =
435 checkExprHasSubLink((Node *) rte->tablesample);
436 break;
437 case RTE_FUNCTION:
438 sub_action->hasSubLinks =
439 checkExprHasSubLink((Node *) rte->functions);
440 break;
441 case RTE_TABLEFUNC:
442 sub_action->hasSubLinks =
443 checkExprHasSubLink((Node *) rte->tablefunc);
444 break;
445 case RTE_VALUES:
446 sub_action->hasSubLinks =
447 checkExprHasSubLink((Node *) rte->values_lists);
448 break;
449 default:
450 /* other RTE types don't contain bare expressions */
451 break;
452 }
453 if (sub_action->hasSubLinks)
454 break; /* no need to keep scanning rtable */
455 }
456 }
457
458 /*
459 * Also, we might have absorbed some RTEs with RLS conditions into the
460 * sub_action. If so, mark it as hasRowSecurity, whether or not those
461 * RTEs will be referenced after we finish rewriting. (Note: currently
462 * this is a no-op because RLS conditions aren't added till later, but it
463 * seems like good future-proofing to do this anyway.)
464 */
465 sub_action->hasRowSecurity |= parsetree->hasRowSecurity;
466
467 /*
468 * Each rule action's jointree should be the main parsetree's jointree
469 * plus that rule's jointree, but usually *without* the original rtindex
470 * that we're replacing (if present, which it won't be for INSERT). Note
471 * that if the rule action refers to OLD, its jointree will add a
472 * reference to rt_index. If the rule action doesn't refer to OLD, but
473 * either the rule_qual or the user query quals do, then we need to keep
474 * the original rtindex in the jointree to provide data for the quals. We
475 * don't want the original rtindex to be joined twice, however, so avoid
476 * keeping it if the rule action mentions it.
477 *
478 * As above, the action's jointree must not share substructure with the
479 * main parsetree's.
480 */
481 if (sub_action->commandType != CMD_UTILITY)
482 {
483 bool keeporig;
484 List *newjointree;
485
486 Assert(sub_action->jointree != NULL);
487 keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
488 rt_index, 0)) &&
489 (rangeTableEntry_used(rule_qual, rt_index, 0) ||
490 rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
491 newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
492 if (newjointree != NIL)
493 {
494 /*
495 * If sub_action is a setop, manipulating its jointree will do no
496 * good at all, because the jointree is dummy. (Perhaps someday
497 * we could push the joining and quals down to the member
498 * statements of the setop?)
499 */
500 if (sub_action->setOperations != NULL)
501 ereport(ERROR,
502 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
503 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
504
505 sub_action->jointree->fromlist =
506 list_concat(newjointree, sub_action->jointree->fromlist);
507
508 /*
509 * There could have been some SubLinks in newjointree, in which
510 * case we'd better mark the sub_action correctly.
511 */
512 if (parsetree->hasSubLinks && !sub_action->hasSubLinks)
513 sub_action->hasSubLinks =
514 checkExprHasSubLink((Node *) newjointree);
515 }
516 }
517
518 /*
519 * If the original query has any CTEs, copy them into the rule action. But
520 * we don't need them for a utility action.
521 */
522 if (parsetree->cteList != NIL && sub_action->commandType != CMD_UTILITY)
523 {
524 ListCell *lc;
525
526 /*
527 * Annoying implementation restriction: because CTEs are identified by
528 * name within a cteList, we can't merge a CTE from the original query
529 * if it has the same name as any CTE in the rule action.
530 *
531 * This could possibly be fixed by using some sort of internally
532 * generated ID, instead of names, to link CTE RTEs to their CTEs.
533 * However, decompiling the results would be quite confusing; note the
534 * merge of hasRecursive flags below, which could change the apparent
535 * semantics of such redundantly-named CTEs.
536 */
537 foreach(lc, parsetree->cteList)
538 {
539 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
540 ListCell *lc2;
541
542 foreach(lc2, sub_action->cteList)
543 {
544 CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(lc2);
545
546 if (strcmp(cte->ctename, cte2->ctename) == 0)
547 ereport(ERROR,
548 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
549 errmsg("WITH query name \"%s\" appears in both a rule action and the query being rewritten",
550 cte->ctename)));
551 }
552 }
553
554 /* OK, it's safe to combine the CTE lists */
555 sub_action->cteList = list_concat(sub_action->cteList,
556 copyObject(parsetree->cteList));
557 /* ... and don't forget about the associated flags */
558 sub_action->hasRecursive |= parsetree->hasRecursive;
559 sub_action->hasModifyingCTE |= parsetree->hasModifyingCTE;
560
561 /*
562 * If rule_action is different from sub_action (i.e., the rule action
563 * is an INSERT...SELECT), then we might have just added some
564 * data-modifying CTEs that are not at the top query level. This is
565 * disallowed by the parser and we mustn't generate such trees here
566 * either, so throw an error.
567 *
568 * Conceivably such cases could be supported by attaching the original
569 * query's CTEs to rule_action not sub_action. But to do that, we'd
570 * have to increment ctelevelsup in RTEs and SubLinks copied from the
571 * original query. For now, it doesn't seem worth the trouble.
572 */
573 if (sub_action->hasModifyingCTE && rule_action != sub_action)
574 ereport(ERROR,
575 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
576 errmsg("INSERT...SELECT rule actions are not supported for queries having data-modifying statements in WITH")));
577 }
578
579 /*
580 * Event Qualification forces copying of parsetree and splitting into two
581 * queries one w/rule_qual, one w/NOT rule_qual. Also add user query qual
582 * onto rule action
583 */
584 AddQual(sub_action, rule_qual);
585
586 AddQual(sub_action, parsetree->jointree->quals);
587
588 /*
589 * Rewrite new.attribute with right hand side of target-list entry for
590 * appropriate field name in insert/update.
591 *
592 * KLUGE ALERT: since ReplaceVarsFromTargetList returns a mutated copy, we
593 * can't just apply it to sub_action; we have to remember to update the
594 * sublink inside rule_action, too.
595 */
596 if ((event == CMD_INSERT || event == CMD_UPDATE) &&
597 sub_action->commandType != CMD_UTILITY)
598 {
599 sub_action = (Query *)
600 ReplaceVarsFromTargetList((Node *) sub_action,
601 new_varno,
602 0,
603 rt_fetch(new_varno, sub_action->rtable),
604 parsetree->targetList,
605 (event == CMD_UPDATE) ?
606 REPLACEVARS_CHANGE_VARNO :
607 REPLACEVARS_SUBSTITUTE_NULL,
608 current_varno,
609 NULL);
610 if (sub_action_ptr)
611 *sub_action_ptr = sub_action;
612 else
613 rule_action = sub_action;
614 }
615
616 /*
617 * If rule_action has a RETURNING clause, then either throw it away if the
618 * triggering query has no RETURNING clause, or rewrite it to emit what
619 * the triggering query's RETURNING clause asks for. Throw an error if
620 * more than one rule has a RETURNING clause.
621 */
622 if (!parsetree->returningList)
623 rule_action->returningList = NIL;
624 else if (rule_action->returningList)
625 {
626 if (*returning_flag)
627 ereport(ERROR,
628 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
629 errmsg("cannot have RETURNING lists in multiple rules")));
630 *returning_flag = true;
631 rule_action->returningList = (List *)
632 ReplaceVarsFromTargetList((Node *) parsetree->returningList,
633 parsetree->resultRelation,
634 0,
635 rt_fetch(parsetree->resultRelation,
636 parsetree->rtable),
637 rule_action->returningList,
638 REPLACEVARS_REPORT_ERROR,
639 0,
640 &rule_action->hasSubLinks);
641
642 /*
643 * There could have been some SubLinks in parsetree's returningList,
644 * in which case we'd better mark the rule_action correctly.
645 */
646 if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
647 rule_action->hasSubLinks =
648 checkExprHasSubLink((Node *) rule_action->returningList);
649 }
650
651 return rule_action;
652 }
653
654 /*
655 * Copy the query's jointree list, and optionally attempt to remove any
656 * occurrence of the given rt_index as a top-level join item (we do not look
657 * for it within join items; this is OK because we are only expecting to find
658 * it as an UPDATE or DELETE target relation, which will be at the top level
659 * of the join). Returns modified jointree list --- this is a separate copy
660 * sharing no nodes with the original.
661 */
662 static List *
adjustJoinTreeList(Query * parsetree,bool removert,int rt_index)663 adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
664 {
665 List *newjointree = copyObject(parsetree->jointree->fromlist);
666 ListCell *l;
667
668 if (removert)
669 {
670 foreach(l, newjointree)
671 {
672 RangeTblRef *rtr = lfirst(l);
673
674 if (IsA(rtr, RangeTblRef) &&
675 rtr->rtindex == rt_index)
676 {
677 newjointree = list_delete_ptr(newjointree, rtr);
678
679 /*
680 * foreach is safe because we exit loop after list_delete...
681 */
682 break;
683 }
684 }
685 }
686 return newjointree;
687 }
688
689
690 /*
691 * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
692 *
693 * This has the following responsibilities:
694 *
695 * 1. For an INSERT, add tlist entries to compute default values for any
696 * attributes that have defaults and are not assigned to in the given tlist.
697 * (We do not insert anything for default-less attributes, however. The
698 * planner will later insert NULLs for them, but there's no reason to slow
699 * down rewriter processing with extra tlist nodes.) Also, for both INSERT
700 * and UPDATE, replace explicit DEFAULT specifications with column default
701 * expressions.
702 *
703 * 2. For an UPDATE on a trigger-updatable view, add tlist entries for any
704 * unassigned-to attributes, assigning them their old values. These will
705 * later get expanded to the output values of the view. (This is equivalent
706 * to what the planner's expand_targetlist() will do for UPDATE on a regular
707 * table, but it's more convenient to do it here while we still have easy
708 * access to the view's original RT index.) This is only necessary for
709 * trigger-updatable views, for which the view remains the result relation of
710 * the query. For auto-updatable views we must not do this, since it might
711 * add assignments to non-updatable view columns. For rule-updatable views it
712 * is unnecessary extra work, since the query will be rewritten with a
713 * different result relation which will be processed when we recurse via
714 * RewriteQuery.
715 *
716 * 3. Merge multiple entries for the same target attribute, or declare error
717 * if we can't. Multiple entries are only allowed for INSERT/UPDATE of
718 * portions of an array or record field, for example
719 * UPDATE table SET foo[2] = 42, foo[4] = 43;
720 * We can merge such operations into a single assignment op. Essentially,
721 * the expression we want to produce in this case is like
722 * foo = array_set_element(array_set_element(foo, 2, 42), 4, 43)
723 *
724 * 4. Sort the tlist into standard order: non-junk fields in order by resno,
725 * then junk fields (these in no particular order).
726 *
727 * We must do items 1,2,3 before firing rewrite rules, else rewritten
728 * references to NEW.foo will produce wrong or incomplete results. Item 4
729 * is not needed for rewriting, but will be needed by the planner, and we
730 * can do it essentially for free while handling the other items.
731 *
732 * Note that for an inheritable UPDATE, this processing is only done once,
733 * using the parent relation as reference. It must not do anything that
734 * will not be correct when transposed to the child relation(s). (Step 4
735 * is incorrect by this light, since child relations might have different
736 * column ordering, but the planner will fix things by re-sorting the tlist
737 * for each child.)
738 */
739 static List *
rewriteTargetListIU(List * targetList,CmdType commandType,OverridingKind override,Relation target_relation,int result_rti)740 rewriteTargetListIU(List *targetList,
741 CmdType commandType,
742 OverridingKind override,
743 Relation target_relation,
744 int result_rti)
745 {
746 TargetEntry **new_tles;
747 List *new_tlist = NIL;
748 List *junk_tlist = NIL;
749 Form_pg_attribute att_tup;
750 int attrno,
751 next_junk_attrno,
752 numattrs;
753 ListCell *temp;
754
755 /*
756 * We process the normal (non-junk) attributes by scanning the input tlist
757 * once and transferring TLEs into an array, then scanning the array to
758 * build an output tlist. This avoids O(N^2) behavior for large numbers
759 * of attributes.
760 *
761 * Junk attributes are tossed into a separate list during the same tlist
762 * scan, then appended to the reconstructed tlist.
763 */
764 numattrs = RelationGetNumberOfAttributes(target_relation);
765 new_tles = (TargetEntry **) palloc0(numattrs * sizeof(TargetEntry *));
766 next_junk_attrno = numattrs + 1;
767
768 foreach(temp, targetList)
769 {
770 TargetEntry *old_tle = (TargetEntry *) lfirst(temp);
771
772 if (!old_tle->resjunk)
773 {
774 /* Normal attr: stash it into new_tles[] */
775 attrno = old_tle->resno;
776 if (attrno < 1 || attrno > numattrs)
777 elog(ERROR, "bogus resno %d in targetlist", attrno);
778 att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
779
780 /* We can (and must) ignore deleted attributes */
781 if (att_tup->attisdropped)
782 continue;
783
784 /* Merge with any prior assignment to same attribute */
785 new_tles[attrno - 1] =
786 process_matched_tle(old_tle,
787 new_tles[attrno - 1],
788 NameStr(att_tup->attname));
789 }
790 else
791 {
792 /*
793 * Copy all resjunk tlist entries to junk_tlist, and assign them
794 * resnos above the last real resno.
795 *
796 * Typical junk entries include ORDER BY or GROUP BY expressions
797 * (are these actually possible in an INSERT or UPDATE?), system
798 * attribute references, etc.
799 */
800
801 /* Get the resno right, but don't copy unnecessarily */
802 if (old_tle->resno != next_junk_attrno)
803 {
804 old_tle = flatCopyTargetEntry(old_tle);
805 old_tle->resno = next_junk_attrno;
806 }
807 junk_tlist = lappend(junk_tlist, old_tle);
808 next_junk_attrno++;
809 }
810 }
811
812 for (attrno = 1; attrno <= numattrs; attrno++)
813 {
814 TargetEntry *new_tle = new_tles[attrno - 1];
815 bool apply_default;
816
817 att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
818
819 /* We can (and must) ignore deleted attributes */
820 if (att_tup->attisdropped)
821 continue;
822
823 /*
824 * Handle the two cases where we need to insert a default expression:
825 * it's an INSERT and there's no tlist entry for the column, or the
826 * tlist entry is a DEFAULT placeholder node.
827 */
828 apply_default = ((new_tle == NULL && commandType == CMD_INSERT) ||
829 (new_tle && new_tle->expr && IsA(new_tle->expr, SetToDefault)));
830
831 if (commandType == CMD_INSERT)
832 {
833 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS && !apply_default)
834 {
835 if (override == OVERRIDING_USER_VALUE)
836 apply_default = true;
837 else if (override != OVERRIDING_SYSTEM_VALUE)
838 ereport(ERROR,
839 (errcode(ERRCODE_GENERATED_ALWAYS),
840 errmsg("cannot insert into column \"%s\"", NameStr(att_tup->attname)),
841 errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
842 NameStr(att_tup->attname)),
843 errhint("Use OVERRIDING SYSTEM VALUE to override.")));
844 }
845
846 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_BY_DEFAULT && override == OVERRIDING_USER_VALUE)
847 apply_default = true;
848
849 if (att_tup->attgenerated && !apply_default)
850 ereport(ERROR,
851 (errcode(ERRCODE_SYNTAX_ERROR),
852 errmsg("cannot insert into column \"%s\"", NameStr(att_tup->attname)),
853 errdetail("Column \"%s\" is a generated column.",
854 NameStr(att_tup->attname))));
855 }
856
857 if (commandType == CMD_UPDATE)
858 {
859 if (att_tup->attidentity == ATTRIBUTE_IDENTITY_ALWAYS && new_tle && !apply_default)
860 ereport(ERROR,
861 (errcode(ERRCODE_GENERATED_ALWAYS),
862 errmsg("column \"%s\" can only be updated to DEFAULT", NameStr(att_tup->attname)),
863 errdetail("Column \"%s\" is an identity column defined as GENERATED ALWAYS.",
864 NameStr(att_tup->attname))));
865
866 if (att_tup->attgenerated && new_tle && !apply_default)
867 ereport(ERROR,
868 (errcode(ERRCODE_SYNTAX_ERROR),
869 errmsg("column \"%s\" can only be updated to DEFAULT", NameStr(att_tup->attname)),
870 errdetail("Column \"%s\" is a generated column.",
871 NameStr(att_tup->attname))));
872 }
873
874 if (att_tup->attgenerated)
875 {
876 /*
877 * stored generated column will be fixed in executor
878 */
879 new_tle = NULL;
880 }
881 else if (apply_default)
882 {
883 Node *new_expr;
884
885 new_expr = build_column_default(target_relation, attrno);
886
887 /*
888 * If there is no default (ie, default is effectively NULL), we
889 * can omit the tlist entry in the INSERT case, since the planner
890 * can insert a NULL for itself, and there's no point in spending
891 * any more rewriter cycles on the entry. But in the UPDATE case
892 * we've got to explicitly set the column to NULL.
893 */
894 if (!new_expr)
895 {
896 if (commandType == CMD_INSERT)
897 new_tle = NULL;
898 else
899 {
900 new_expr = (Node *) makeConst(att_tup->atttypid,
901 -1,
902 att_tup->attcollation,
903 att_tup->attlen,
904 (Datum) 0,
905 true, /* isnull */
906 att_tup->attbyval);
907 /* this is to catch a NOT NULL domain constraint */
908 new_expr = coerce_to_domain(new_expr,
909 InvalidOid, -1,
910 att_tup->atttypid,
911 COERCION_IMPLICIT,
912 COERCE_IMPLICIT_CAST,
913 -1,
914 false);
915 }
916 }
917
918 if (new_expr)
919 new_tle = makeTargetEntry((Expr *) new_expr,
920 attrno,
921 pstrdup(NameStr(att_tup->attname)),
922 false);
923 }
924
925 /*
926 * For an UPDATE on a trigger-updatable view, provide a dummy entry
927 * whenever there is no explicit assignment.
928 */
929 if (new_tle == NULL && commandType == CMD_UPDATE &&
930 target_relation->rd_rel->relkind == RELKIND_VIEW &&
931 view_has_instead_trigger(target_relation, CMD_UPDATE))
932 {
933 Node *new_expr;
934
935 new_expr = (Node *) makeVar(result_rti,
936 attrno,
937 att_tup->atttypid,
938 att_tup->atttypmod,
939 att_tup->attcollation,
940 0);
941
942 new_tle = makeTargetEntry((Expr *) new_expr,
943 attrno,
944 pstrdup(NameStr(att_tup->attname)),
945 false);
946 }
947
948 if (new_tle)
949 new_tlist = lappend(new_tlist, new_tle);
950 }
951
952 pfree(new_tles);
953
954 return list_concat(new_tlist, junk_tlist);
955 }
956
957
958 /*
959 * Convert a matched TLE from the original tlist into a correct new TLE.
960 *
961 * This routine detects and handles multiple assignments to the same target
962 * attribute. (The attribute name is needed only for error messages.)
963 */
964 static TargetEntry *
process_matched_tle(TargetEntry * src_tle,TargetEntry * prior_tle,const char * attrName)965 process_matched_tle(TargetEntry *src_tle,
966 TargetEntry *prior_tle,
967 const char *attrName)
968 {
969 TargetEntry *result;
970 CoerceToDomain *coerce_expr = NULL;
971 Node *src_expr;
972 Node *prior_expr;
973 Node *src_input;
974 Node *prior_input;
975 Node *priorbottom;
976 Node *newexpr;
977
978 if (prior_tle == NULL)
979 {
980 /*
981 * Normal case where this is the first assignment to the attribute.
982 */
983 return src_tle;
984 }
985
986 /*----------
987 * Multiple assignments to same attribute. Allow only if all are
988 * FieldStore or SubscriptingRef assignment operations. This is a bit
989 * tricky because what we may actually be looking at is a nest of
990 * such nodes; consider
991 * UPDATE tab SET col.fld1.subfld1 = x, col.fld2.subfld2 = y
992 * The two expressions produced by the parser will look like
993 * FieldStore(col, fld1, FieldStore(placeholder, subfld1, x))
994 * FieldStore(col, fld2, FieldStore(placeholder, subfld2, y))
995 * However, we can ignore the substructure and just consider the top
996 * FieldStore or SubscriptingRef from each assignment, because it works to
997 * combine these as
998 * FieldStore(FieldStore(col, fld1,
999 * FieldStore(placeholder, subfld1, x)),
1000 * fld2, FieldStore(placeholder, subfld2, y))
1001 * Note the leftmost expression goes on the inside so that the
1002 * assignments appear to occur left-to-right.
1003 *
1004 * For FieldStore, instead of nesting we can generate a single
1005 * FieldStore with multiple target fields. We must nest when
1006 * SubscriptingRefs are involved though.
1007 *
1008 * As a further complication, the destination column might be a domain,
1009 * resulting in each assignment containing a CoerceToDomain node over a
1010 * FieldStore or SubscriptingRef. These should have matching target
1011 * domains, so we strip them and reconstitute a single CoerceToDomain over
1012 * the combined FieldStore/SubscriptingRef nodes. (Notice that this has the
1013 * result that the domain's checks are applied only after we do all the
1014 * field or element updates, not after each one. This is arguably desirable.)
1015 *----------
1016 */
1017 src_expr = (Node *) src_tle->expr;
1018 prior_expr = (Node *) prior_tle->expr;
1019
1020 if (src_expr && IsA(src_expr, CoerceToDomain) &&
1021 prior_expr && IsA(prior_expr, CoerceToDomain) &&
1022 ((CoerceToDomain *) src_expr)->resulttype ==
1023 ((CoerceToDomain *) prior_expr)->resulttype)
1024 {
1025 /* we assume without checking that resulttypmod/resultcollid match */
1026 coerce_expr = (CoerceToDomain *) src_expr;
1027 src_expr = (Node *) ((CoerceToDomain *) src_expr)->arg;
1028 prior_expr = (Node *) ((CoerceToDomain *) prior_expr)->arg;
1029 }
1030
1031 src_input = get_assignment_input(src_expr);
1032 prior_input = get_assignment_input(prior_expr);
1033 if (src_input == NULL ||
1034 prior_input == NULL ||
1035 exprType(src_expr) != exprType(prior_expr))
1036 ereport(ERROR,
1037 (errcode(ERRCODE_SYNTAX_ERROR),
1038 errmsg("multiple assignments to same column \"%s\"",
1039 attrName)));
1040
1041 /*
1042 * Prior TLE could be a nest of assignments if we do this more than once.
1043 */
1044 priorbottom = prior_input;
1045 for (;;)
1046 {
1047 Node *newbottom = get_assignment_input(priorbottom);
1048
1049 if (newbottom == NULL)
1050 break; /* found the original Var reference */
1051 priorbottom = newbottom;
1052 }
1053 if (!equal(priorbottom, src_input))
1054 ereport(ERROR,
1055 (errcode(ERRCODE_SYNTAX_ERROR),
1056 errmsg("multiple assignments to same column \"%s\"",
1057 attrName)));
1058
1059 /*
1060 * Looks OK to nest 'em.
1061 */
1062 if (IsA(src_expr, FieldStore))
1063 {
1064 FieldStore *fstore = makeNode(FieldStore);
1065
1066 if (IsA(prior_expr, FieldStore))
1067 {
1068 /* combine the two */
1069 memcpy(fstore, prior_expr, sizeof(FieldStore));
1070 fstore->newvals =
1071 list_concat_copy(((FieldStore *) prior_expr)->newvals,
1072 ((FieldStore *) src_expr)->newvals);
1073 fstore->fieldnums =
1074 list_concat_copy(((FieldStore *) prior_expr)->fieldnums,
1075 ((FieldStore *) src_expr)->fieldnums);
1076 }
1077 else
1078 {
1079 /* general case, just nest 'em */
1080 memcpy(fstore, src_expr, sizeof(FieldStore));
1081 fstore->arg = (Expr *) prior_expr;
1082 }
1083 newexpr = (Node *) fstore;
1084 }
1085 else if (IsA(src_expr, SubscriptingRef))
1086 {
1087 SubscriptingRef *sbsref = makeNode(SubscriptingRef);
1088
1089 memcpy(sbsref, src_expr, sizeof(SubscriptingRef));
1090 sbsref->refexpr = (Expr *) prior_expr;
1091 newexpr = (Node *) sbsref;
1092 }
1093 else
1094 {
1095 elog(ERROR, "cannot happen");
1096 newexpr = NULL;
1097 }
1098
1099 if (coerce_expr)
1100 {
1101 /* put back the CoerceToDomain */
1102 CoerceToDomain *newcoerce = makeNode(CoerceToDomain);
1103
1104 memcpy(newcoerce, coerce_expr, sizeof(CoerceToDomain));
1105 newcoerce->arg = (Expr *) newexpr;
1106 newexpr = (Node *) newcoerce;
1107 }
1108
1109 result = flatCopyTargetEntry(src_tle);
1110 result->expr = (Expr *) newexpr;
1111 return result;
1112 }
1113
1114 /*
1115 * If node is an assignment node, return its input; else return NULL
1116 */
1117 static Node *
get_assignment_input(Node * node)1118 get_assignment_input(Node *node)
1119 {
1120 if (node == NULL)
1121 return NULL;
1122 if (IsA(node, FieldStore))
1123 {
1124 FieldStore *fstore = (FieldStore *) node;
1125
1126 return (Node *) fstore->arg;
1127 }
1128 else if (IsA(node, SubscriptingRef))
1129 {
1130 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1131
1132 if (sbsref->refassgnexpr == NULL)
1133 return NULL;
1134
1135 return (Node *) sbsref->refexpr;
1136 }
1137
1138 return NULL;
1139 }
1140
1141 /*
1142 * Make an expression tree for the default value for a column.
1143 *
1144 * If there is no default, return a NULL instead.
1145 */
1146 Node *
build_column_default(Relation rel,int attrno)1147 build_column_default(Relation rel, int attrno)
1148 {
1149 TupleDesc rd_att = rel->rd_att;
1150 Form_pg_attribute att_tup = TupleDescAttr(rd_att, attrno - 1);
1151 Oid atttype = att_tup->atttypid;
1152 int32 atttypmod = att_tup->atttypmod;
1153 Node *expr = NULL;
1154 Oid exprtype;
1155
1156 if (att_tup->attidentity)
1157 {
1158 NextValueExpr *nve = makeNode(NextValueExpr);
1159
1160 nve->seqid = getIdentitySequence(RelationGetRelid(rel), attrno, false);
1161 nve->typeId = att_tup->atttypid;
1162
1163 return (Node *) nve;
1164 }
1165
1166 /*
1167 * Scan to see if relation has a default for this column.
1168 */
1169 if (att_tup->atthasdef && rd_att->constr &&
1170 rd_att->constr->num_defval > 0)
1171 {
1172 AttrDefault *defval = rd_att->constr->defval;
1173 int ndef = rd_att->constr->num_defval;
1174
1175 while (--ndef >= 0)
1176 {
1177 if (attrno == defval[ndef].adnum)
1178 {
1179 /*
1180 * Found it, convert string representation to node tree.
1181 */
1182 expr = stringToNode(defval[ndef].adbin);
1183 break;
1184 }
1185 }
1186 }
1187
1188 /*
1189 * No per-column default, so look for a default for the type itself. But
1190 * not for generated columns.
1191 */
1192 if (expr == NULL && !att_tup->attgenerated)
1193 expr = get_typdefault(atttype);
1194
1195 if (expr == NULL)
1196 return NULL; /* No default anywhere */
1197
1198 /*
1199 * Make sure the value is coerced to the target column type; this will
1200 * generally be true already, but there seem to be some corner cases
1201 * involving domain defaults where it might not be true. This should match
1202 * the parser's processing of non-defaulted expressions --- see
1203 * transformAssignedExpr().
1204 */
1205 exprtype = exprType(expr);
1206
1207 expr = coerce_to_target_type(NULL, /* no UNKNOWN params here */
1208 expr, exprtype,
1209 atttype, atttypmod,
1210 COERCION_ASSIGNMENT,
1211 COERCE_IMPLICIT_CAST,
1212 -1);
1213 if (expr == NULL)
1214 ereport(ERROR,
1215 (errcode(ERRCODE_DATATYPE_MISMATCH),
1216 errmsg("column \"%s\" is of type %s"
1217 " but default expression is of type %s",
1218 NameStr(att_tup->attname),
1219 format_type_be(atttype),
1220 format_type_be(exprtype)),
1221 errhint("You will need to rewrite or cast the expression.")));
1222
1223 return expr;
1224 }
1225
1226
1227 /* Does VALUES RTE contain any SetToDefault items? */
1228 static bool
searchForDefault(RangeTblEntry * rte)1229 searchForDefault(RangeTblEntry *rte)
1230 {
1231 ListCell *lc;
1232
1233 foreach(lc, rte->values_lists)
1234 {
1235 List *sublist = (List *) lfirst(lc);
1236 ListCell *lc2;
1237
1238 foreach(lc2, sublist)
1239 {
1240 Node *col = (Node *) lfirst(lc2);
1241
1242 if (IsA(col, SetToDefault))
1243 return true;
1244 }
1245 }
1246 return false;
1247 }
1248
1249 /*
1250 * When processing INSERT ... VALUES with a VALUES RTE (ie, multiple VALUES
1251 * lists), we have to replace any DEFAULT items in the VALUES lists with
1252 * the appropriate default expressions. The other aspects of targetlist
1253 * rewriting need be applied only to the query's targetlist proper.
1254 *
1255 * For an auto-updatable view, each DEFAULT item in the VALUES list is
1256 * replaced with the default from the view, if it has one. Otherwise it is
1257 * left untouched so that the underlying base relation's default can be
1258 * applied instead (when we later recurse to here after rewriting the query
1259 * to refer to the base relation instead of the view).
1260 *
1261 * For other types of relation, including rule- and trigger-updatable views,
1262 * all DEFAULT items are replaced, and if the target relation doesn't have a
1263 * default, the value is explicitly set to NULL.
1264 *
1265 * Additionally, if force_nulls is true, the target relation's defaults are
1266 * ignored and all DEFAULT items in the VALUES list are explicitly set to
1267 * NULL, regardless of the target relation's type. This is used for the
1268 * product queries generated by DO ALSO rules attached to an auto-updatable
1269 * view, for which we will have already called this function with force_nulls
1270 * false. For these product queries, we must then force any remaining DEFAULT
1271 * items to NULL to provide concrete values for the rule actions.
1272 * Essentially, this is a mix of the 2 cases above --- the original query is
1273 * an insert into an auto-updatable view, and the product queries are inserts
1274 * into a rule-updatable view.
1275 *
1276 * Note that we may have subscripted or field assignment targetlist entries,
1277 * as well as more complex expressions from already-replaced DEFAULT items if
1278 * we have recursed to here for an auto-updatable view. However, it ought to
1279 * be impossible for such entries to have DEFAULTs assigned to them --- we
1280 * should only have to replace DEFAULT items for targetlist entries that
1281 * contain simple Vars referencing the VALUES RTE.
1282 *
1283 * Returns true if all DEFAULT items were replaced, and false if some were
1284 * left untouched.
1285 */
1286 static bool
rewriteValuesRTE(Query * parsetree,RangeTblEntry * rte,int rti,Relation target_relation,bool force_nulls)1287 rewriteValuesRTE(Query *parsetree, RangeTblEntry *rte, int rti,
1288 Relation target_relation, bool force_nulls)
1289 {
1290 List *newValues;
1291 ListCell *lc;
1292 bool isAutoUpdatableView;
1293 bool allReplaced;
1294 int numattrs;
1295 int *attrnos;
1296
1297 /*
1298 * Rebuilding all the lists is a pretty expensive proposition in a big
1299 * VALUES list, and it's a waste of time if there aren't any DEFAULT
1300 * placeholders. So first scan to see if there are any.
1301 *
1302 * We skip this check if force_nulls is true, because we know that there
1303 * are DEFAULT items present in that case.
1304 */
1305 if (!force_nulls && !searchForDefault(rte))
1306 return true; /* nothing to do */
1307
1308 /*
1309 * Scan the targetlist for entries referring to the VALUES RTE, and note
1310 * the target attributes. As noted above, we should only need to do this
1311 * for targetlist entries containing simple Vars --- nothing else in the
1312 * VALUES RTE should contain DEFAULT items, and we complain if such a
1313 * thing does occur.
1314 */
1315 numattrs = list_length(linitial(rte->values_lists));
1316 attrnos = (int *) palloc0(numattrs * sizeof(int));
1317
1318 foreach(lc, parsetree->targetList)
1319 {
1320 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1321
1322 if (IsA(tle->expr, Var))
1323 {
1324 Var *var = (Var *) tle->expr;
1325
1326 if (var->varno == rti)
1327 {
1328 int attrno = var->varattno;
1329
1330 Assert(attrno >= 1 && attrno <= numattrs);
1331 attrnos[attrno - 1] = tle->resno;
1332 }
1333 }
1334 }
1335
1336 /*
1337 * Check if the target relation is an auto-updatable view, in which case
1338 * unresolved defaults will be left untouched rather than being set to
1339 * NULL. If force_nulls is true, we always set DEFAULT items to NULL, so
1340 * skip this check in that case --- it isn't an auto-updatable view.
1341 */
1342 isAutoUpdatableView = false;
1343 if (!force_nulls &&
1344 target_relation->rd_rel->relkind == RELKIND_VIEW &&
1345 !view_has_instead_trigger(target_relation, CMD_INSERT))
1346 {
1347 List *locks;
1348 bool hasUpdate;
1349 bool found;
1350 ListCell *l;
1351
1352 /* Look for an unconditional DO INSTEAD rule */
1353 locks = matchLocks(CMD_INSERT, target_relation->rd_rules,
1354 parsetree->resultRelation, parsetree, &hasUpdate);
1355
1356 found = false;
1357 foreach(l, locks)
1358 {
1359 RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
1360
1361 if (rule_lock->isInstead &&
1362 rule_lock->qual == NULL)
1363 {
1364 found = true;
1365 break;
1366 }
1367 }
1368
1369 /*
1370 * If we didn't find an unconditional DO INSTEAD rule, assume that the
1371 * view is auto-updatable. If it isn't, rewriteTargetView() will
1372 * throw an error.
1373 */
1374 if (!found)
1375 isAutoUpdatableView = true;
1376 }
1377
1378 newValues = NIL;
1379 allReplaced = true;
1380 foreach(lc, rte->values_lists)
1381 {
1382 List *sublist = (List *) lfirst(lc);
1383 List *newList = NIL;
1384 ListCell *lc2;
1385 int i;
1386
1387 Assert(list_length(sublist) == numattrs);
1388
1389 i = 0;
1390 foreach(lc2, sublist)
1391 {
1392 Node *col = (Node *) lfirst(lc2);
1393 int attrno = attrnos[i++];
1394
1395 if (IsA(col, SetToDefault))
1396 {
1397 Form_pg_attribute att_tup;
1398 Node *new_expr;
1399
1400 if (attrno == 0)
1401 elog(ERROR, "cannot set value in column %d to DEFAULT", i);
1402 att_tup = TupleDescAttr(target_relation->rd_att, attrno - 1);
1403
1404 if (!force_nulls && !att_tup->attisdropped)
1405 new_expr = build_column_default(target_relation, attrno);
1406 else
1407 new_expr = NULL; /* force a NULL if dropped */
1408
1409 /*
1410 * If there is no default (ie, default is effectively NULL),
1411 * we've got to explicitly set the column to NULL, unless the
1412 * target relation is an auto-updatable view.
1413 */
1414 if (!new_expr)
1415 {
1416 if (isAutoUpdatableView)
1417 {
1418 /* Leave the value untouched */
1419 newList = lappend(newList, col);
1420 allReplaced = false;
1421 continue;
1422 }
1423
1424 new_expr = (Node *) makeConst(att_tup->atttypid,
1425 -1,
1426 att_tup->attcollation,
1427 att_tup->attlen,
1428 (Datum) 0,
1429 true, /* isnull */
1430 att_tup->attbyval);
1431 /* this is to catch a NOT NULL domain constraint */
1432 new_expr = coerce_to_domain(new_expr,
1433 InvalidOid, -1,
1434 att_tup->atttypid,
1435 COERCION_IMPLICIT,
1436 COERCE_IMPLICIT_CAST,
1437 -1,
1438 false);
1439 }
1440 newList = lappend(newList, new_expr);
1441 }
1442 else
1443 newList = lappend(newList, col);
1444 }
1445 newValues = lappend(newValues, newList);
1446 }
1447 rte->values_lists = newValues;
1448
1449 pfree(attrnos);
1450
1451 return allReplaced;
1452 }
1453
1454
1455 /*
1456 * rewriteTargetListUD - rewrite UPDATE/DELETE targetlist as needed
1457 *
1458 * This function adds a "junk" TLE that is needed to allow the executor to
1459 * find the original row for the update or delete. When the target relation
1460 * is a regular table, the junk TLE emits the ctid attribute of the original
1461 * row. When the target relation is a foreign table, we let the FDW decide
1462 * what to add.
1463 *
1464 * We used to do this during RewriteQuery(), but now that inheritance trees
1465 * can contain a mix of regular and foreign tables, we must postpone it till
1466 * planning, after the inheritance tree has been expanded. In that way we
1467 * can do the right thing for each child table.
1468 */
1469 void
rewriteTargetListUD(Query * parsetree,RangeTblEntry * target_rte,Relation target_relation)1470 rewriteTargetListUD(Query *parsetree, RangeTblEntry *target_rte,
1471 Relation target_relation)
1472 {
1473 Var *var = NULL;
1474 const char *attrname;
1475 TargetEntry *tle;
1476
1477 if (target_relation->rd_rel->relkind == RELKIND_RELATION ||
1478 target_relation->rd_rel->relkind == RELKIND_MATVIEW ||
1479 target_relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1480 {
1481 /*
1482 * Emit CTID so that executor can find the row to update or delete.
1483 */
1484 var = makeVar(parsetree->resultRelation,
1485 SelfItemPointerAttributeNumber,
1486 TIDOID,
1487 -1,
1488 InvalidOid,
1489 0);
1490
1491 attrname = "ctid";
1492 }
1493 else if (target_relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1494 {
1495 /*
1496 * Let the foreign table's FDW add whatever junk TLEs it wants.
1497 */
1498 FdwRoutine *fdwroutine;
1499
1500 fdwroutine = GetFdwRoutineForRelation(target_relation, false);
1501
1502 if (fdwroutine->AddForeignUpdateTargets != NULL)
1503 fdwroutine->AddForeignUpdateTargets(parsetree, target_rte,
1504 target_relation);
1505
1506 /*
1507 * If we have a row-level trigger corresponding to the operation, emit
1508 * a whole-row Var so that executor will have the "old" row to pass to
1509 * the trigger. Alas, this misses system columns.
1510 */
1511 if (target_relation->trigdesc &&
1512 ((parsetree->commandType == CMD_UPDATE &&
1513 (target_relation->trigdesc->trig_update_after_row ||
1514 target_relation->trigdesc->trig_update_before_row)) ||
1515 (parsetree->commandType == CMD_DELETE &&
1516 (target_relation->trigdesc->trig_delete_after_row ||
1517 target_relation->trigdesc->trig_delete_before_row))))
1518 {
1519 var = makeWholeRowVar(target_rte,
1520 parsetree->resultRelation,
1521 0,
1522 false);
1523
1524 attrname = "wholerow";
1525 }
1526 }
1527
1528 if (var != NULL)
1529 {
1530 tle = makeTargetEntry((Expr *) var,
1531 list_length(parsetree->targetList) + 1,
1532 pstrdup(attrname),
1533 true);
1534
1535 parsetree->targetList = lappend(parsetree->targetList, tle);
1536 }
1537 }
1538
1539 /*
1540 * Record in target_rte->extraUpdatedCols the indexes of any generated columns
1541 * that depend on any columns mentioned in target_rte->updatedCols.
1542 */
1543 void
fill_extraUpdatedCols(RangeTblEntry * target_rte,Relation target_relation)1544 fill_extraUpdatedCols(RangeTblEntry *target_rte, Relation target_relation)
1545 {
1546 TupleDesc tupdesc = RelationGetDescr(target_relation);
1547 TupleConstr *constr = tupdesc->constr;
1548
1549 target_rte->extraUpdatedCols = NULL;
1550
1551 if (constr && constr->has_generated_stored)
1552 {
1553 for (int i = 0; i < constr->num_defval; i++)
1554 {
1555 AttrDefault *defval = &constr->defval[i];
1556 Node *expr;
1557 Bitmapset *attrs_used = NULL;
1558
1559 /* skip if not generated column */
1560 if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
1561 continue;
1562
1563 /* identify columns this generated column depends on */
1564 expr = stringToNode(defval->adbin);
1565 pull_varattnos(expr, 1, &attrs_used);
1566
1567 if (bms_overlap(target_rte->updatedCols, attrs_used))
1568 target_rte->extraUpdatedCols =
1569 bms_add_member(target_rte->extraUpdatedCols,
1570 defval->adnum - FirstLowInvalidHeapAttributeNumber);
1571 }
1572 }
1573 }
1574
1575
1576 /*
1577 * matchLocks -
1578 * match the list of locks and returns the matching rules
1579 */
1580 static List *
matchLocks(CmdType event,RuleLock * rulelocks,int varno,Query * parsetree,bool * hasUpdate)1581 matchLocks(CmdType event,
1582 RuleLock *rulelocks,
1583 int varno,
1584 Query *parsetree,
1585 bool *hasUpdate)
1586 {
1587 List *matching_locks = NIL;
1588 int nlocks;
1589 int i;
1590
1591 if (rulelocks == NULL)
1592 return NIL;
1593
1594 if (parsetree->commandType != CMD_SELECT)
1595 {
1596 if (parsetree->resultRelation != varno)
1597 return NIL;
1598 }
1599
1600 nlocks = rulelocks->numLocks;
1601
1602 for (i = 0; i < nlocks; i++)
1603 {
1604 RewriteRule *oneLock = rulelocks->rules[i];
1605
1606 if (oneLock->event == CMD_UPDATE)
1607 *hasUpdate = true;
1608
1609 /*
1610 * Suppress ON INSERT/UPDATE/DELETE rules that are disabled or
1611 * configured to not fire during the current sessions replication
1612 * role. ON SELECT rules will always be applied in order to keep views
1613 * working even in LOCAL or REPLICA role.
1614 */
1615 if (oneLock->event != CMD_SELECT)
1616 {
1617 if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
1618 {
1619 if (oneLock->enabled == RULE_FIRES_ON_ORIGIN ||
1620 oneLock->enabled == RULE_DISABLED)
1621 continue;
1622 }
1623 else /* ORIGIN or LOCAL ROLE */
1624 {
1625 if (oneLock->enabled == RULE_FIRES_ON_REPLICA ||
1626 oneLock->enabled == RULE_DISABLED)
1627 continue;
1628 }
1629 }
1630
1631 if (oneLock->event == event)
1632 {
1633 if (parsetree->commandType != CMD_SELECT ||
1634 rangeTableEntry_used((Node *) parsetree, varno, 0))
1635 matching_locks = lappend(matching_locks, oneLock);
1636 }
1637 }
1638
1639 return matching_locks;
1640 }
1641
1642
1643 /*
1644 * ApplyRetrieveRule - expand an ON SELECT rule
1645 */
1646 static Query *
ApplyRetrieveRule(Query * parsetree,RewriteRule * rule,int rt_index,Relation relation,List * activeRIRs)1647 ApplyRetrieveRule(Query *parsetree,
1648 RewriteRule *rule,
1649 int rt_index,
1650 Relation relation,
1651 List *activeRIRs)
1652 {
1653 Query *rule_action;
1654 RangeTblEntry *rte,
1655 *subrte;
1656 RowMarkClause *rc;
1657
1658 if (list_length(rule->actions) != 1)
1659 elog(ERROR, "expected just one rule action");
1660 if (rule->qual != NULL)
1661 elog(ERROR, "cannot handle qualified ON SELECT rule");
1662
1663 if (rt_index == parsetree->resultRelation)
1664 {
1665 /*
1666 * We have a view as the result relation of the query, and it wasn't
1667 * rewritten by any rule. This case is supported if there is an
1668 * INSTEAD OF trigger that will trap attempts to insert/update/delete
1669 * view rows. The executor will check that; for the moment just plow
1670 * ahead. We have two cases:
1671 *
1672 * For INSERT, we needn't do anything. The unmodified RTE will serve
1673 * fine as the result relation.
1674 *
1675 * For UPDATE/DELETE, we need to expand the view so as to have source
1676 * data for the operation. But we also need an unmodified RTE to
1677 * serve as the target. So, copy the RTE and add the copy to the
1678 * rangetable. Note that the copy does not get added to the jointree.
1679 * Also note that there's a hack in fireRIRrules to avoid calling this
1680 * function again when it arrives at the copied RTE.
1681 */
1682 if (parsetree->commandType == CMD_INSERT)
1683 return parsetree;
1684 else if (parsetree->commandType == CMD_UPDATE ||
1685 parsetree->commandType == CMD_DELETE)
1686 {
1687 RangeTblEntry *newrte;
1688 Var *var;
1689 TargetEntry *tle;
1690
1691 rte = rt_fetch(rt_index, parsetree->rtable);
1692 newrte = copyObject(rte);
1693 parsetree->rtable = lappend(parsetree->rtable, newrte);
1694 parsetree->resultRelation = list_length(parsetree->rtable);
1695
1696 /*
1697 * There's no need to do permissions checks twice, so wipe out the
1698 * permissions info for the original RTE (we prefer to keep the
1699 * bits set on the result RTE).
1700 */
1701 rte->requiredPerms = 0;
1702 rte->checkAsUser = InvalidOid;
1703 rte->selectedCols = NULL;
1704 rte->insertedCols = NULL;
1705 rte->updatedCols = NULL;
1706 rte->extraUpdatedCols = NULL;
1707
1708 /*
1709 * For the most part, Vars referencing the view should remain as
1710 * they are, meaning that they implicitly represent OLD values.
1711 * But in the RETURNING list if any, we want such Vars to
1712 * represent NEW values, so change them to reference the new RTE.
1713 *
1714 * Since ChangeVarNodes scribbles on the tree in-place, copy the
1715 * RETURNING list first for safety.
1716 */
1717 parsetree->returningList = copyObject(parsetree->returningList);
1718 ChangeVarNodes((Node *) parsetree->returningList, rt_index,
1719 parsetree->resultRelation, 0);
1720
1721 /*
1722 * To allow the executor to compute the original view row to pass
1723 * to the INSTEAD OF trigger, we add a resjunk whole-row Var
1724 * referencing the original RTE. This will later get expanded
1725 * into a RowExpr computing all the OLD values of the view row.
1726 */
1727 var = makeWholeRowVar(rte, rt_index, 0, false);
1728 tle = makeTargetEntry((Expr *) var,
1729 list_length(parsetree->targetList) + 1,
1730 pstrdup("wholerow"),
1731 true);
1732
1733 parsetree->targetList = lappend(parsetree->targetList, tle);
1734
1735 /* Now, continue with expanding the original view RTE */
1736 }
1737 else
1738 elog(ERROR, "unrecognized commandType: %d",
1739 (int) parsetree->commandType);
1740 }
1741
1742 /*
1743 * Check if there's a FOR [KEY] UPDATE/SHARE clause applying to this view.
1744 *
1745 * Note: we needn't explicitly consider any such clauses appearing in
1746 * ancestor query levels; their effects have already been pushed down to
1747 * here by markQueryForLocking, and will be reflected in "rc".
1748 */
1749 rc = get_parse_rowmark(parsetree, rt_index);
1750
1751 /*
1752 * Make a modifiable copy of the view query, and acquire needed locks on
1753 * the relations it mentions. Force at least RowShareLock for all such
1754 * rels if there's a FOR [KEY] UPDATE/SHARE clause affecting this view.
1755 */
1756 rule_action = copyObject(linitial(rule->actions));
1757
1758 AcquireRewriteLocks(rule_action, true, (rc != NULL));
1759
1760 /*
1761 * If FOR [KEY] UPDATE/SHARE of view, mark all the contained tables as
1762 * implicit FOR [KEY] UPDATE/SHARE, the same as the parser would have done
1763 * if the view's subquery had been written out explicitly.
1764 */
1765 if (rc != NULL)
1766 markQueryForLocking(rule_action, (Node *) rule_action->jointree,
1767 rc->strength, rc->waitPolicy, true);
1768
1769 /*
1770 * Recursively expand any view references inside the view.
1771 *
1772 * Note: this must happen after markQueryForLocking. That way, any UPDATE
1773 * permission bits needed for sub-views are initially applied to their
1774 * RTE_RELATION RTEs by markQueryForLocking, and then transferred to their
1775 * OLD rangetable entries by the action below (in a recursive call of this
1776 * routine).
1777 */
1778 rule_action = fireRIRrules(rule_action, activeRIRs);
1779
1780 /*
1781 * Now, plug the view query in as a subselect, converting the relation's
1782 * original RTE to a subquery RTE.
1783 */
1784 rte = rt_fetch(rt_index, parsetree->rtable);
1785
1786 rte->rtekind = RTE_SUBQUERY;
1787 rte->subquery = rule_action;
1788 rte->security_barrier = RelationIsSecurityView(relation);
1789 /* Clear fields that should not be set in a subquery RTE */
1790 rte->relid = InvalidOid;
1791 rte->relkind = 0;
1792 rte->rellockmode = 0;
1793 rte->tablesample = NULL;
1794 rte->inh = false; /* must not be set for a subquery */
1795
1796 /*
1797 * We move the view's permission check data down to its rangetable. The
1798 * checks will actually be done against the OLD entry therein.
1799 */
1800 subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
1801 Assert(subrte->relid == relation->rd_id);
1802 subrte->requiredPerms = rte->requiredPerms;
1803 subrte->checkAsUser = rte->checkAsUser;
1804 subrte->selectedCols = rte->selectedCols;
1805 subrte->insertedCols = rte->insertedCols;
1806 subrte->updatedCols = rte->updatedCols;
1807 subrte->extraUpdatedCols = rte->extraUpdatedCols;
1808
1809 rte->requiredPerms = 0; /* no permission check on subquery itself */
1810 rte->checkAsUser = InvalidOid;
1811 rte->selectedCols = NULL;
1812 rte->insertedCols = NULL;
1813 rte->updatedCols = NULL;
1814 rte->extraUpdatedCols = NULL;
1815
1816 return parsetree;
1817 }
1818
1819 /*
1820 * Recursively mark all relations used by a view as FOR [KEY] UPDATE/SHARE.
1821 *
1822 * This may generate an invalid query, eg if some sub-query uses an
1823 * aggregate. We leave it to the planner to detect that.
1824 *
1825 * NB: this must agree with the parser's transformLockingClause() routine.
1826 * However, unlike the parser we have to be careful not to mark a view's
1827 * OLD and NEW rels for updating. The best way to handle that seems to be
1828 * to scan the jointree to determine which rels are used.
1829 */
1830 static void
markQueryForLocking(Query * qry,Node * jtnode,LockClauseStrength strength,LockWaitPolicy waitPolicy,bool pushedDown)1831 markQueryForLocking(Query *qry, Node *jtnode,
1832 LockClauseStrength strength, LockWaitPolicy waitPolicy,
1833 bool pushedDown)
1834 {
1835 if (jtnode == NULL)
1836 return;
1837 if (IsA(jtnode, RangeTblRef))
1838 {
1839 int rti = ((RangeTblRef *) jtnode)->rtindex;
1840 RangeTblEntry *rte = rt_fetch(rti, qry->rtable);
1841
1842 if (rte->rtekind == RTE_RELATION)
1843 {
1844 applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
1845 rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
1846 }
1847 else if (rte->rtekind == RTE_SUBQUERY)
1848 {
1849 applyLockingClause(qry, rti, strength, waitPolicy, pushedDown);
1850 /* FOR UPDATE/SHARE of subquery is propagated to subquery's rels */
1851 markQueryForLocking(rte->subquery, (Node *) rte->subquery->jointree,
1852 strength, waitPolicy, true);
1853 }
1854 /* other RTE types are unaffected by FOR UPDATE */
1855 }
1856 else if (IsA(jtnode, FromExpr))
1857 {
1858 FromExpr *f = (FromExpr *) jtnode;
1859 ListCell *l;
1860
1861 foreach(l, f->fromlist)
1862 markQueryForLocking(qry, lfirst(l), strength, waitPolicy, pushedDown);
1863 }
1864 else if (IsA(jtnode, JoinExpr))
1865 {
1866 JoinExpr *j = (JoinExpr *) jtnode;
1867
1868 markQueryForLocking(qry, j->larg, strength, waitPolicy, pushedDown);
1869 markQueryForLocking(qry, j->rarg, strength, waitPolicy, pushedDown);
1870 }
1871 else
1872 elog(ERROR, "unrecognized node type: %d",
1873 (int) nodeTag(jtnode));
1874 }
1875
1876
1877 /*
1878 * fireRIRonSubLink -
1879 * Apply fireRIRrules() to each SubLink (subselect in expression) found
1880 * in the given tree.
1881 *
1882 * NOTE: although this has the form of a walker, we cheat and modify the
1883 * SubLink nodes in-place. It is caller's responsibility to ensure that
1884 * no unwanted side-effects occur!
1885 *
1886 * This is unlike most of the other routines that recurse into subselects,
1887 * because we must take control at the SubLink node in order to replace
1888 * the SubLink's subselect link with the possibly-rewritten subquery.
1889 */
1890 static bool
fireRIRonSubLink(Node * node,List * activeRIRs)1891 fireRIRonSubLink(Node *node, List *activeRIRs)
1892 {
1893 if (node == NULL)
1894 return false;
1895 if (IsA(node, SubLink))
1896 {
1897 SubLink *sub = (SubLink *) node;
1898
1899 /* Do what we came for */
1900 sub->subselect = (Node *) fireRIRrules((Query *) sub->subselect,
1901 activeRIRs);
1902 /* Fall through to process lefthand args of SubLink */
1903 }
1904
1905 /*
1906 * Do NOT recurse into Query nodes, because fireRIRrules already processed
1907 * subselects of subselects for us.
1908 */
1909 return expression_tree_walker(node, fireRIRonSubLink,
1910 (void *) activeRIRs);
1911 }
1912
1913
1914 /*
1915 * fireRIRrules -
1916 * Apply all RIR rules on each rangetable entry in the given query
1917 *
1918 * activeRIRs is a list of the OIDs of views we're already processing RIR
1919 * rules for, used to detect/reject recursion.
1920 */
1921 static Query *
fireRIRrules(Query * parsetree,List * activeRIRs)1922 fireRIRrules(Query *parsetree, List *activeRIRs)
1923 {
1924 int origResultRelation = parsetree->resultRelation;
1925 int rt_index;
1926 ListCell *lc;
1927
1928 /*
1929 * don't try to convert this into a foreach loop, because rtable list can
1930 * get changed each time through...
1931 */
1932 rt_index = 0;
1933 while (rt_index < list_length(parsetree->rtable))
1934 {
1935 RangeTblEntry *rte;
1936 Relation rel;
1937 List *locks;
1938 RuleLock *rules;
1939 RewriteRule *rule;
1940 int i;
1941
1942 ++rt_index;
1943
1944 rte = rt_fetch(rt_index, parsetree->rtable);
1945
1946 /*
1947 * A subquery RTE can't have associated rules, so there's nothing to
1948 * do to this level of the query, but we must recurse into the
1949 * subquery to expand any rule references in it.
1950 */
1951 if (rte->rtekind == RTE_SUBQUERY)
1952 {
1953 rte->subquery = fireRIRrules(rte->subquery, activeRIRs);
1954 continue;
1955 }
1956
1957 /*
1958 * Joins and other non-relation RTEs can be ignored completely.
1959 */
1960 if (rte->rtekind != RTE_RELATION)
1961 continue;
1962
1963 /*
1964 * Always ignore RIR rules for materialized views referenced in
1965 * queries. (This does not prevent refreshing MVs, since they aren't
1966 * referenced in their own query definitions.)
1967 *
1968 * Note: in the future we might want to allow MVs to be conditionally
1969 * expanded as if they were regular views, if they are not scannable.
1970 * In that case this test would need to be postponed till after we've
1971 * opened the rel, so that we could check its state.
1972 */
1973 if (rte->relkind == RELKIND_MATVIEW)
1974 continue;
1975
1976 /*
1977 * In INSERT ... ON CONFLICT, ignore the EXCLUDED pseudo-relation;
1978 * even if it points to a view, we needn't expand it, and should not
1979 * because we want the RTE to remain of RTE_RELATION type. Otherwise,
1980 * it would get changed to RTE_SUBQUERY type, which is an
1981 * untested/unsupported situation.
1982 */
1983 if (parsetree->onConflict &&
1984 rt_index == parsetree->onConflict->exclRelIndex)
1985 continue;
1986
1987 /*
1988 * If the table is not referenced in the query, then we ignore it.
1989 * This prevents infinite expansion loop due to new rtable entries
1990 * inserted by expansion of a rule. A table is referenced if it is
1991 * part of the join set (a source table), or is referenced by any Var
1992 * nodes, or is the result table.
1993 */
1994 if (rt_index != parsetree->resultRelation &&
1995 !rangeTableEntry_used((Node *) parsetree, rt_index, 0))
1996 continue;
1997
1998 /*
1999 * Also, if this is a new result relation introduced by
2000 * ApplyRetrieveRule, we don't want to do anything more with it.
2001 */
2002 if (rt_index == parsetree->resultRelation &&
2003 rt_index != origResultRelation)
2004 continue;
2005
2006 /*
2007 * We can use NoLock here since either the parser or
2008 * AcquireRewriteLocks should have locked the rel already.
2009 */
2010 rel = table_open(rte->relid, NoLock);
2011
2012 /*
2013 * Collect the RIR rules that we must apply
2014 */
2015 rules = rel->rd_rules;
2016 if (rules != NULL)
2017 {
2018 locks = NIL;
2019 for (i = 0; i < rules->numLocks; i++)
2020 {
2021 rule = rules->rules[i];
2022 if (rule->event != CMD_SELECT)
2023 continue;
2024
2025 locks = lappend(locks, rule);
2026 }
2027
2028 /*
2029 * If we found any, apply them --- but first check for recursion!
2030 */
2031 if (locks != NIL)
2032 {
2033 ListCell *l;
2034
2035 if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
2036 ereport(ERROR,
2037 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2038 errmsg("infinite recursion detected in rules for relation \"%s\"",
2039 RelationGetRelationName(rel))));
2040 activeRIRs = lappend_oid(activeRIRs, RelationGetRelid(rel));
2041
2042 foreach(l, locks)
2043 {
2044 rule = lfirst(l);
2045
2046 parsetree = ApplyRetrieveRule(parsetree,
2047 rule,
2048 rt_index,
2049 rel,
2050 activeRIRs);
2051 }
2052
2053 activeRIRs = list_delete_last(activeRIRs);
2054 }
2055 }
2056
2057 table_close(rel, NoLock);
2058 }
2059
2060 /* Recurse into subqueries in WITH */
2061 foreach(lc, parsetree->cteList)
2062 {
2063 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2064
2065 cte->ctequery = (Node *)
2066 fireRIRrules((Query *) cte->ctequery, activeRIRs);
2067 }
2068
2069 /*
2070 * Recurse into sublink subqueries, too. But we already did the ones in
2071 * the rtable and cteList.
2072 */
2073 if (parsetree->hasSubLinks)
2074 query_tree_walker(parsetree, fireRIRonSubLink, (void *) activeRIRs,
2075 QTW_IGNORE_RC_SUBQUERIES);
2076
2077 /*
2078 * Apply any row level security policies. We do this last because it
2079 * requires special recursion detection if the new quals have sublink
2080 * subqueries, and if we did it in the loop above query_tree_walker would
2081 * then recurse into those quals a second time.
2082 */
2083 rt_index = 0;
2084 foreach(lc, parsetree->rtable)
2085 {
2086 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2087 Relation rel;
2088 List *securityQuals;
2089 List *withCheckOptions;
2090 bool hasRowSecurity;
2091 bool hasSubLinks;
2092
2093 ++rt_index;
2094
2095 /* Only normal relations can have RLS policies */
2096 if (rte->rtekind != RTE_RELATION ||
2097 (rte->relkind != RELKIND_RELATION &&
2098 rte->relkind != RELKIND_PARTITIONED_TABLE))
2099 continue;
2100
2101 rel = table_open(rte->relid, NoLock);
2102
2103 /*
2104 * Fetch any new security quals that must be applied to this RTE.
2105 */
2106 get_row_security_policies(parsetree, rte, rt_index,
2107 &securityQuals, &withCheckOptions,
2108 &hasRowSecurity, &hasSubLinks);
2109
2110 if (securityQuals != NIL || withCheckOptions != NIL)
2111 {
2112 if (hasSubLinks)
2113 {
2114 acquireLocksOnSubLinks_context context;
2115
2116 /*
2117 * Recursively process the new quals, checking for infinite
2118 * recursion.
2119 */
2120 if (list_member_oid(activeRIRs, RelationGetRelid(rel)))
2121 ereport(ERROR,
2122 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2123 errmsg("infinite recursion detected in policy for relation \"%s\"",
2124 RelationGetRelationName(rel))));
2125
2126 activeRIRs = lappend_oid(activeRIRs, RelationGetRelid(rel));
2127
2128 /*
2129 * get_row_security_policies just passed back securityQuals
2130 * and/or withCheckOptions, and there were SubLinks, make sure
2131 * we lock any relations which are referenced.
2132 *
2133 * These locks would normally be acquired by the parser, but
2134 * securityQuals and withCheckOptions are added post-parsing.
2135 */
2136 context.for_execute = true;
2137 (void) acquireLocksOnSubLinks((Node *) securityQuals, &context);
2138 (void) acquireLocksOnSubLinks((Node *) withCheckOptions,
2139 &context);
2140
2141 /*
2142 * Now that we have the locks on anything added by
2143 * get_row_security_policies, fire any RIR rules for them.
2144 */
2145 expression_tree_walker((Node *) securityQuals,
2146 fireRIRonSubLink, (void *) activeRIRs);
2147
2148 expression_tree_walker((Node *) withCheckOptions,
2149 fireRIRonSubLink, (void *) activeRIRs);
2150
2151 activeRIRs = list_delete_last(activeRIRs);
2152 }
2153
2154 /*
2155 * Add the new security barrier quals to the start of the RTE's
2156 * list so that they get applied before any existing barrier quals
2157 * (which would have come from a security-barrier view, and should
2158 * get lower priority than RLS conditions on the table itself).
2159 */
2160 rte->securityQuals = list_concat(securityQuals,
2161 rte->securityQuals);
2162
2163 parsetree->withCheckOptions = list_concat(withCheckOptions,
2164 parsetree->withCheckOptions);
2165 }
2166
2167 /*
2168 * Make sure the query is marked correctly if row level security
2169 * applies, or if the new quals had sublinks.
2170 */
2171 if (hasRowSecurity)
2172 parsetree->hasRowSecurity = true;
2173 if (hasSubLinks)
2174 parsetree->hasSubLinks = true;
2175
2176 table_close(rel, NoLock);
2177 }
2178
2179 return parsetree;
2180 }
2181
2182
2183 /*
2184 * Modify the given query by adding 'AND rule_qual IS NOT TRUE' to its
2185 * qualification. This is used to generate suitable "else clauses" for
2186 * conditional INSTEAD rules. (Unfortunately we must use "x IS NOT TRUE",
2187 * not just "NOT x" which the planner is much smarter about, else we will
2188 * do the wrong thing when the qual evaluates to NULL.)
2189 *
2190 * The rule_qual may contain references to OLD or NEW. OLD references are
2191 * replaced by references to the specified rt_index (the relation that the
2192 * rule applies to). NEW references are only possible for INSERT and UPDATE
2193 * queries on the relation itself, and so they should be replaced by copies
2194 * of the related entries in the query's own targetlist.
2195 */
2196 static Query *
CopyAndAddInvertedQual(Query * parsetree,Node * rule_qual,int rt_index,CmdType event)2197 CopyAndAddInvertedQual(Query *parsetree,
2198 Node *rule_qual,
2199 int rt_index,
2200 CmdType event)
2201 {
2202 /* Don't scribble on the passed qual (it's in the relcache!) */
2203 Node *new_qual = copyObject(rule_qual);
2204 acquireLocksOnSubLinks_context context;
2205
2206 context.for_execute = true;
2207
2208 /*
2209 * In case there are subqueries in the qual, acquire necessary locks and
2210 * fix any deleted JOIN RTE entries. (This is somewhat redundant with
2211 * rewriteRuleAction, but not entirely ... consider restructuring so that
2212 * we only need to process the qual this way once.)
2213 */
2214 (void) acquireLocksOnSubLinks(new_qual, &context);
2215
2216 /* Fix references to OLD */
2217 ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
2218 /* Fix references to NEW */
2219 if (event == CMD_INSERT || event == CMD_UPDATE)
2220 new_qual = ReplaceVarsFromTargetList(new_qual,
2221 PRS2_NEW_VARNO,
2222 0,
2223 rt_fetch(rt_index,
2224 parsetree->rtable),
2225 parsetree->targetList,
2226 (event == CMD_UPDATE) ?
2227 REPLACEVARS_CHANGE_VARNO :
2228 REPLACEVARS_SUBSTITUTE_NULL,
2229 rt_index,
2230 &parsetree->hasSubLinks);
2231 /* And attach the fixed qual */
2232 AddInvertedQual(parsetree, new_qual);
2233
2234 return parsetree;
2235 }
2236
2237
2238 /*
2239 * fireRules -
2240 * Iterate through rule locks applying rules.
2241 *
2242 * Input arguments:
2243 * parsetree - original query
2244 * rt_index - RT index of result relation in original query
2245 * event - type of rule event
2246 * locks - list of rules to fire
2247 * Output arguments:
2248 * *instead_flag - set true if any unqualified INSTEAD rule is found
2249 * (must be initialized to false)
2250 * *returning_flag - set true if we rewrite RETURNING clause in any rule
2251 * (must be initialized to false)
2252 * *qual_product - filled with modified original query if any qualified
2253 * INSTEAD rule is found (must be initialized to NULL)
2254 * Return value:
2255 * list of rule actions adjusted for use with this query
2256 *
2257 * Qualified INSTEAD rules generate their action with the qualification
2258 * condition added. They also generate a modified version of the original
2259 * query with the negated qualification added, so that it will run only for
2260 * rows that the qualified action doesn't act on. (If there are multiple
2261 * qualified INSTEAD rules, we AND all the negated quals onto a single
2262 * modified original query.) We won't execute the original, unmodified
2263 * query if we find either qualified or unqualified INSTEAD rules. If
2264 * we find both, the modified original query is discarded too.
2265 */
2266 static List *
fireRules(Query * parsetree,int rt_index,CmdType event,List * locks,bool * instead_flag,bool * returning_flag,Query ** qual_product)2267 fireRules(Query *parsetree,
2268 int rt_index,
2269 CmdType event,
2270 List *locks,
2271 bool *instead_flag,
2272 bool *returning_flag,
2273 Query **qual_product)
2274 {
2275 List *results = NIL;
2276 ListCell *l;
2277
2278 foreach(l, locks)
2279 {
2280 RewriteRule *rule_lock = (RewriteRule *) lfirst(l);
2281 Node *event_qual = rule_lock->qual;
2282 List *actions = rule_lock->actions;
2283 QuerySource qsrc;
2284 ListCell *r;
2285
2286 /* Determine correct QuerySource value for actions */
2287 if (rule_lock->isInstead)
2288 {
2289 if (event_qual != NULL)
2290 qsrc = QSRC_QUAL_INSTEAD_RULE;
2291 else
2292 {
2293 qsrc = QSRC_INSTEAD_RULE;
2294 *instead_flag = true; /* report unqualified INSTEAD */
2295 }
2296 }
2297 else
2298 qsrc = QSRC_NON_INSTEAD_RULE;
2299
2300 if (qsrc == QSRC_QUAL_INSTEAD_RULE)
2301 {
2302 /*
2303 * If there are INSTEAD rules with qualifications, the original
2304 * query is still performed. But all the negated rule
2305 * qualifications of the INSTEAD rules are added so it does its
2306 * actions only in cases where the rule quals of all INSTEAD rules
2307 * are false. Think of it as the default action in a case. We save
2308 * this in *qual_product so RewriteQuery() can add it to the query
2309 * list after we mangled it up enough.
2310 *
2311 * If we have already found an unqualified INSTEAD rule, then
2312 * *qual_product won't be used, so don't bother building it.
2313 */
2314 if (!*instead_flag)
2315 {
2316 if (*qual_product == NULL)
2317 *qual_product = copyObject(parsetree);
2318 *qual_product = CopyAndAddInvertedQual(*qual_product,
2319 event_qual,
2320 rt_index,
2321 event);
2322 }
2323 }
2324
2325 /* Now process the rule's actions and add them to the result list */
2326 foreach(r, actions)
2327 {
2328 Query *rule_action = lfirst(r);
2329
2330 if (rule_action->commandType == CMD_NOTHING)
2331 continue;
2332
2333 rule_action = rewriteRuleAction(parsetree, rule_action,
2334 event_qual, rt_index, event,
2335 returning_flag);
2336
2337 rule_action->querySource = qsrc;
2338 rule_action->canSetTag = false; /* might change later */
2339
2340 results = lappend(results, rule_action);
2341 }
2342 }
2343
2344 return results;
2345 }
2346
2347
2348 /*
2349 * get_view_query - get the Query from a view's _RETURN rule.
2350 *
2351 * Caller should have verified that the relation is a view, and therefore
2352 * we should find an ON SELECT action.
2353 *
2354 * Note that the pointer returned is into the relcache and therefore must
2355 * be treated as read-only to the caller and not modified or scribbled on.
2356 */
2357 Query *
get_view_query(Relation view)2358 get_view_query(Relation view)
2359 {
2360 int i;
2361
2362 Assert(view->rd_rel->relkind == RELKIND_VIEW);
2363
2364 for (i = 0; i < view->rd_rules->numLocks; i++)
2365 {
2366 RewriteRule *rule = view->rd_rules->rules[i];
2367
2368 if (rule->event == CMD_SELECT)
2369 {
2370 /* A _RETURN rule should have only one action */
2371 if (list_length(rule->actions) != 1)
2372 elog(ERROR, "invalid _RETURN rule action specification");
2373
2374 return (Query *) linitial(rule->actions);
2375 }
2376 }
2377
2378 elog(ERROR, "failed to find _RETURN rule for view");
2379 return NULL; /* keep compiler quiet */
2380 }
2381
2382
2383 /*
2384 * view_has_instead_trigger - does view have an INSTEAD OF trigger for event?
2385 *
2386 * If it does, we don't want to treat it as auto-updatable. This test can't
2387 * be folded into view_query_is_auto_updatable because it's not an error
2388 * condition.
2389 */
2390 static bool
view_has_instead_trigger(Relation view,CmdType event)2391 view_has_instead_trigger(Relation view, CmdType event)
2392 {
2393 TriggerDesc *trigDesc = view->trigdesc;
2394
2395 switch (event)
2396 {
2397 case CMD_INSERT:
2398 if (trigDesc && trigDesc->trig_insert_instead_row)
2399 return true;
2400 break;
2401 case CMD_UPDATE:
2402 if (trigDesc && trigDesc->trig_update_instead_row)
2403 return true;
2404 break;
2405 case CMD_DELETE:
2406 if (trigDesc && trigDesc->trig_delete_instead_row)
2407 return true;
2408 break;
2409 default:
2410 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2411 break;
2412 }
2413 return false;
2414 }
2415
2416
2417 /*
2418 * view_col_is_auto_updatable - test whether the specified column of a view
2419 * is auto-updatable. Returns NULL (if the column can be updated) or a message
2420 * string giving the reason that it cannot be.
2421 *
2422 * The returned string has not been translated; if it is shown as an error
2423 * message, the caller should apply _() to translate it.
2424 *
2425 * Note that the checks performed here are local to this view. We do not check
2426 * whether the referenced column of the underlying base relation is updatable.
2427 */
2428 static const char *
view_col_is_auto_updatable(RangeTblRef * rtr,TargetEntry * tle)2429 view_col_is_auto_updatable(RangeTblRef *rtr, TargetEntry *tle)
2430 {
2431 Var *var = (Var *) tle->expr;
2432
2433 /*
2434 * For now, the only updatable columns we support are those that are Vars
2435 * referring to user columns of the underlying base relation.
2436 *
2437 * The view targetlist may contain resjunk columns (e.g., a view defined
2438 * like "SELECT * FROM t ORDER BY a+b" is auto-updatable) but such columns
2439 * are not auto-updatable, and in fact should never appear in the outer
2440 * query's targetlist.
2441 */
2442 if (tle->resjunk)
2443 return gettext_noop("Junk view columns are not updatable.");
2444
2445 if (!IsA(var, Var) ||
2446 var->varno != rtr->rtindex ||
2447 var->varlevelsup != 0)
2448 return gettext_noop("View columns that are not columns of their base relation are not updatable.");
2449
2450 if (var->varattno < 0)
2451 return gettext_noop("View columns that refer to system columns are not updatable.");
2452
2453 if (var->varattno == 0)
2454 return gettext_noop("View columns that return whole-row references are not updatable.");
2455
2456 return NULL; /* the view column is updatable */
2457 }
2458
2459
2460 /*
2461 * view_query_is_auto_updatable - test whether the specified view definition
2462 * represents an auto-updatable view. Returns NULL (if the view can be updated)
2463 * or a message string giving the reason that it cannot be.
2464
2465 * The returned string has not been translated; if it is shown as an error
2466 * message, the caller should apply _() to translate it.
2467 *
2468 * If check_cols is true, the view is required to have at least one updatable
2469 * column (necessary for INSERT/UPDATE). Otherwise the view's columns are not
2470 * checked for updatability. See also view_cols_are_auto_updatable.
2471 *
2472 * Note that the checks performed here are only based on the view definition.
2473 * We do not check whether any base relations referred to by the view are
2474 * updatable.
2475 */
2476 const char *
view_query_is_auto_updatable(Query * viewquery,bool check_cols)2477 view_query_is_auto_updatable(Query *viewquery, bool check_cols)
2478 {
2479 RangeTblRef *rtr;
2480 RangeTblEntry *base_rte;
2481
2482 /*----------
2483 * Check if the view is simply updatable. According to SQL-92 this means:
2484 * - No DISTINCT clause.
2485 * - Each TLE is a column reference, and each column appears at most once.
2486 * - FROM contains exactly one base relation.
2487 * - No GROUP BY or HAVING clauses.
2488 * - No set operations (UNION, INTERSECT or EXCEPT).
2489 * - No sub-queries in the WHERE clause that reference the target table.
2490 *
2491 * We ignore that last restriction since it would be complex to enforce
2492 * and there isn't any actual benefit to disallowing sub-queries. (The
2493 * semantic issues that the standard is presumably concerned about don't
2494 * arise in Postgres, since any such sub-query will not see any updates
2495 * executed by the outer query anyway, thanks to MVCC snapshotting.)
2496 *
2497 * We also relax the second restriction by supporting part of SQL:1999
2498 * feature T111, which allows for a mix of updatable and non-updatable
2499 * columns, provided that an INSERT or UPDATE doesn't attempt to assign to
2500 * a non-updatable column.
2501 *
2502 * In addition we impose these constraints, involving features that are
2503 * not part of SQL-92:
2504 * - No CTEs (WITH clauses).
2505 * - No OFFSET or LIMIT clauses (this matches a SQL:2008 restriction).
2506 * - No system columns (including whole-row references) in the tlist.
2507 * - No window functions in the tlist.
2508 * - No set-returning functions in the tlist.
2509 *
2510 * Note that we do these checks without recursively expanding the view.
2511 * If the base relation is a view, we'll recursively deal with it later.
2512 *----------
2513 */
2514 if (viewquery->distinctClause != NIL)
2515 return gettext_noop("Views containing DISTINCT are not automatically updatable.");
2516
2517 if (viewquery->groupClause != NIL || viewquery->groupingSets)
2518 return gettext_noop("Views containing GROUP BY are not automatically updatable.");
2519
2520 if (viewquery->havingQual != NULL)
2521 return gettext_noop("Views containing HAVING are not automatically updatable.");
2522
2523 if (viewquery->setOperations != NULL)
2524 return gettext_noop("Views containing UNION, INTERSECT, or EXCEPT are not automatically updatable.");
2525
2526 if (viewquery->cteList != NIL)
2527 return gettext_noop("Views containing WITH are not automatically updatable.");
2528
2529 if (viewquery->limitOffset != NULL || viewquery->limitCount != NULL)
2530 return gettext_noop("Views containing LIMIT or OFFSET are not automatically updatable.");
2531
2532 /*
2533 * We must not allow window functions or set returning functions in the
2534 * targetlist. Otherwise we might end up inserting them into the quals of
2535 * the main query. We must also check for aggregates in the targetlist in
2536 * case they appear without a GROUP BY.
2537 *
2538 * These restrictions ensure that each row of the view corresponds to a
2539 * unique row in the underlying base relation.
2540 */
2541 if (viewquery->hasAggs)
2542 return gettext_noop("Views that return aggregate functions are not automatically updatable.");
2543
2544 if (viewquery->hasWindowFuncs)
2545 return gettext_noop("Views that return window functions are not automatically updatable.");
2546
2547 if (viewquery->hasTargetSRFs)
2548 return gettext_noop("Views that return set-returning functions are not automatically updatable.");
2549
2550 /*
2551 * The view query should select from a single base relation, which must be
2552 * a table or another view.
2553 */
2554 if (list_length(viewquery->jointree->fromlist) != 1)
2555 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2556
2557 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2558 if (!IsA(rtr, RangeTblRef))
2559 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2560
2561 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2562 if (base_rte->rtekind != RTE_RELATION ||
2563 (base_rte->relkind != RELKIND_RELATION &&
2564 base_rte->relkind != RELKIND_FOREIGN_TABLE &&
2565 base_rte->relkind != RELKIND_VIEW &&
2566 base_rte->relkind != RELKIND_PARTITIONED_TABLE))
2567 return gettext_noop("Views that do not select from a single table or view are not automatically updatable.");
2568
2569 if (base_rte->tablesample)
2570 return gettext_noop("Views containing TABLESAMPLE are not automatically updatable.");
2571
2572 /*
2573 * Check that the view has at least one updatable column. This is required
2574 * for INSERT/UPDATE but not for DELETE.
2575 */
2576 if (check_cols)
2577 {
2578 ListCell *cell;
2579 bool found;
2580
2581 found = false;
2582 foreach(cell, viewquery->targetList)
2583 {
2584 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2585
2586 if (view_col_is_auto_updatable(rtr, tle) == NULL)
2587 {
2588 found = true;
2589 break;
2590 }
2591 }
2592
2593 if (!found)
2594 return gettext_noop("Views that have no updatable columns are not automatically updatable.");
2595 }
2596
2597 return NULL; /* the view is updatable */
2598 }
2599
2600
2601 /*
2602 * view_cols_are_auto_updatable - test whether all of the required columns of
2603 * an auto-updatable view are actually updatable. Returns NULL (if all the
2604 * required columns can be updated) or a message string giving the reason that
2605 * they cannot be.
2606 *
2607 * The returned string has not been translated; if it is shown as an error
2608 * message, the caller should apply _() to translate it.
2609 *
2610 * This should be used for INSERT/UPDATE to ensure that we don't attempt to
2611 * assign to any non-updatable columns.
2612 *
2613 * Additionally it may be used to retrieve the set of updatable columns in the
2614 * view, or if one or more of the required columns is not updatable, the name
2615 * of the first offending non-updatable column.
2616 *
2617 * The caller must have already verified that this is an auto-updatable view
2618 * using view_query_is_auto_updatable.
2619 *
2620 * Note that the checks performed here are only based on the view definition.
2621 * We do not check whether the referenced columns of the base relation are
2622 * updatable.
2623 */
2624 static const char *
view_cols_are_auto_updatable(Query * viewquery,Bitmapset * required_cols,Bitmapset ** updatable_cols,char ** non_updatable_col)2625 view_cols_are_auto_updatable(Query *viewquery,
2626 Bitmapset *required_cols,
2627 Bitmapset **updatable_cols,
2628 char **non_updatable_col)
2629 {
2630 RangeTblRef *rtr;
2631 AttrNumber col;
2632 ListCell *cell;
2633
2634 /*
2635 * The caller should have verified that this view is auto-updatable and so
2636 * there should be a single base relation.
2637 */
2638 Assert(list_length(viewquery->jointree->fromlist) == 1);
2639 rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
2640
2641 /* Initialize the optional return values */
2642 if (updatable_cols != NULL)
2643 *updatable_cols = NULL;
2644 if (non_updatable_col != NULL)
2645 *non_updatable_col = NULL;
2646
2647 /* Test each view column for updatability */
2648 col = -FirstLowInvalidHeapAttributeNumber;
2649 foreach(cell, viewquery->targetList)
2650 {
2651 TargetEntry *tle = (TargetEntry *) lfirst(cell);
2652 const char *col_update_detail;
2653
2654 col++;
2655 col_update_detail = view_col_is_auto_updatable(rtr, tle);
2656
2657 if (col_update_detail == NULL)
2658 {
2659 /* The column is updatable */
2660 if (updatable_cols != NULL)
2661 *updatable_cols = bms_add_member(*updatable_cols, col);
2662 }
2663 else if (bms_is_member(col, required_cols))
2664 {
2665 /* The required column is not updatable */
2666 if (non_updatable_col != NULL)
2667 *non_updatable_col = tle->resname;
2668 return col_update_detail;
2669 }
2670 }
2671
2672 return NULL; /* all the required view columns are updatable */
2673 }
2674
2675
2676 /*
2677 * relation_is_updatable - determine which update events the specified
2678 * relation supports.
2679 *
2680 * Note that views may contain a mix of updatable and non-updatable columns.
2681 * For a view to support INSERT/UPDATE it must have at least one updatable
2682 * column, but there is no such restriction for DELETE. If include_cols is
2683 * non-NULL, then only the specified columns are considered when testing for
2684 * updatability.
2685 *
2686 * Unlike the preceding functions, this does recurse to look at a view's
2687 * base relations, so it needs to detect recursion. To do that, we pass
2688 * a list of currently-considered outer relations. External callers need
2689 * only pass NIL.
2690 *
2691 * This is used for the information_schema views, which have separate concepts
2692 * of "updatable" and "trigger updatable". A relation is "updatable" if it
2693 * can be updated without the need for triggers (either because it has a
2694 * suitable RULE, or because it is simple enough to be automatically updated).
2695 * A relation is "trigger updatable" if it has a suitable INSTEAD OF trigger.
2696 * The SQL standard regards this as not necessarily updatable, presumably
2697 * because there is no way of knowing what the trigger will actually do.
2698 * The information_schema views therefore call this function with
2699 * include_triggers = false. However, other callers might only care whether
2700 * data-modifying SQL will work, so they can pass include_triggers = true
2701 * to have trigger updatability included in the result.
2702 *
2703 * The return value is a bitmask of rule event numbers indicating which of
2704 * the INSERT, UPDATE and DELETE operations are supported. (We do it this way
2705 * so that we can test for UPDATE plus DELETE support in a single call.)
2706 */
2707 int
relation_is_updatable(Oid reloid,List * outer_reloids,bool include_triggers,Bitmapset * include_cols)2708 relation_is_updatable(Oid reloid,
2709 List *outer_reloids,
2710 bool include_triggers,
2711 Bitmapset *include_cols)
2712 {
2713 int events = 0;
2714 Relation rel;
2715 RuleLock *rulelocks;
2716
2717 #define ALL_EVENTS ((1 << CMD_INSERT) | (1 << CMD_UPDATE) | (1 << CMD_DELETE))
2718
2719 /* Since this function recurses, it could be driven to stack overflow */
2720 check_stack_depth();
2721
2722 rel = try_relation_open(reloid, AccessShareLock);
2723
2724 /*
2725 * If the relation doesn't exist, return zero rather than throwing an
2726 * error. This is helpful since scanning an information_schema view under
2727 * MVCC rules can result in referencing rels that have actually been
2728 * deleted already.
2729 */
2730 if (rel == NULL)
2731 return 0;
2732
2733 /* If we detect a recursive view, report that it is not updatable */
2734 if (list_member_oid(outer_reloids, RelationGetRelid(rel)))
2735 {
2736 relation_close(rel, AccessShareLock);
2737 return 0;
2738 }
2739
2740 /* If the relation is a table, it is always updatable */
2741 if (rel->rd_rel->relkind == RELKIND_RELATION ||
2742 rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2743 {
2744 relation_close(rel, AccessShareLock);
2745 return ALL_EVENTS;
2746 }
2747
2748 /* Look for unconditional DO INSTEAD rules, and note supported events */
2749 rulelocks = rel->rd_rules;
2750 if (rulelocks != NULL)
2751 {
2752 int i;
2753
2754 for (i = 0; i < rulelocks->numLocks; i++)
2755 {
2756 if (rulelocks->rules[i]->isInstead &&
2757 rulelocks->rules[i]->qual == NULL)
2758 {
2759 events |= ((1 << rulelocks->rules[i]->event) & ALL_EVENTS);
2760 }
2761 }
2762
2763 /* If we have rules for all events, we're done */
2764 if (events == ALL_EVENTS)
2765 {
2766 relation_close(rel, AccessShareLock);
2767 return events;
2768 }
2769 }
2770
2771 /* Similarly look for INSTEAD OF triggers, if they are to be included */
2772 if (include_triggers)
2773 {
2774 TriggerDesc *trigDesc = rel->trigdesc;
2775
2776 if (trigDesc)
2777 {
2778 if (trigDesc->trig_insert_instead_row)
2779 events |= (1 << CMD_INSERT);
2780 if (trigDesc->trig_update_instead_row)
2781 events |= (1 << CMD_UPDATE);
2782 if (trigDesc->trig_delete_instead_row)
2783 events |= (1 << CMD_DELETE);
2784
2785 /* If we have triggers for all events, we're done */
2786 if (events == ALL_EVENTS)
2787 {
2788 relation_close(rel, AccessShareLock);
2789 return events;
2790 }
2791 }
2792 }
2793
2794 /* If this is a foreign table, check which update events it supports */
2795 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2796 {
2797 FdwRoutine *fdwroutine = GetFdwRoutineForRelation(rel, false);
2798
2799 if (fdwroutine->IsForeignRelUpdatable != NULL)
2800 events |= fdwroutine->IsForeignRelUpdatable(rel);
2801 else
2802 {
2803 /* Assume presence of executor functions is sufficient */
2804 if (fdwroutine->ExecForeignInsert != NULL)
2805 events |= (1 << CMD_INSERT);
2806 if (fdwroutine->ExecForeignUpdate != NULL)
2807 events |= (1 << CMD_UPDATE);
2808 if (fdwroutine->ExecForeignDelete != NULL)
2809 events |= (1 << CMD_DELETE);
2810 }
2811
2812 relation_close(rel, AccessShareLock);
2813 return events;
2814 }
2815
2816 /* Check if this is an automatically updatable view */
2817 if (rel->rd_rel->relkind == RELKIND_VIEW)
2818 {
2819 Query *viewquery = get_view_query(rel);
2820
2821 if (view_query_is_auto_updatable(viewquery, false) == NULL)
2822 {
2823 Bitmapset *updatable_cols;
2824 int auto_events;
2825 RangeTblRef *rtr;
2826 RangeTblEntry *base_rte;
2827 Oid baseoid;
2828
2829 /*
2830 * Determine which of the view's columns are updatable. If there
2831 * are none within the set of columns we are looking at, then the
2832 * view doesn't support INSERT/UPDATE, but it may still support
2833 * DELETE.
2834 */
2835 view_cols_are_auto_updatable(viewquery, NULL,
2836 &updatable_cols, NULL);
2837
2838 if (include_cols != NULL)
2839 updatable_cols = bms_int_members(updatable_cols, include_cols);
2840
2841 if (bms_is_empty(updatable_cols))
2842 auto_events = (1 << CMD_DELETE); /* May support DELETE */
2843 else
2844 auto_events = ALL_EVENTS; /* May support all events */
2845
2846 /*
2847 * The base relation must also support these update commands.
2848 * Tables are always updatable, but for any other kind of base
2849 * relation we must do a recursive check limited to the columns
2850 * referenced by the locally updatable columns in this view.
2851 */
2852 rtr = (RangeTblRef *) linitial(viewquery->jointree->fromlist);
2853 base_rte = rt_fetch(rtr->rtindex, viewquery->rtable);
2854 Assert(base_rte->rtekind == RTE_RELATION);
2855
2856 if (base_rte->relkind != RELKIND_RELATION &&
2857 base_rte->relkind != RELKIND_PARTITIONED_TABLE)
2858 {
2859 baseoid = base_rte->relid;
2860 outer_reloids = lappend_oid(outer_reloids,
2861 RelationGetRelid(rel));
2862 include_cols = adjust_view_column_set(updatable_cols,
2863 viewquery->targetList);
2864 auto_events &= relation_is_updatable(baseoid,
2865 outer_reloids,
2866 include_triggers,
2867 include_cols);
2868 outer_reloids = list_delete_last(outer_reloids);
2869 }
2870 events |= auto_events;
2871 }
2872 }
2873
2874 /* If we reach here, the relation may support some update commands */
2875 relation_close(rel, AccessShareLock);
2876 return events;
2877 }
2878
2879
2880 /*
2881 * adjust_view_column_set - map a set of column numbers according to targetlist
2882 *
2883 * This is used with simply-updatable views to map column-permissions sets for
2884 * the view columns onto the matching columns in the underlying base relation.
2885 * The targetlist is expected to be a list of plain Vars of the underlying
2886 * relation (as per the checks above in view_query_is_auto_updatable).
2887 */
2888 static Bitmapset *
adjust_view_column_set(Bitmapset * cols,List * targetlist)2889 adjust_view_column_set(Bitmapset *cols, List *targetlist)
2890 {
2891 Bitmapset *result = NULL;
2892 int col;
2893
2894 col = -1;
2895 while ((col = bms_next_member(cols, col)) >= 0)
2896 {
2897 /* bit numbers are offset by FirstLowInvalidHeapAttributeNumber */
2898 AttrNumber attno = col + FirstLowInvalidHeapAttributeNumber;
2899
2900 if (attno == InvalidAttrNumber)
2901 {
2902 /*
2903 * There's a whole-row reference to the view. For permissions
2904 * purposes, treat it as a reference to each column available from
2905 * the view. (We should *not* convert this to a whole-row
2906 * reference to the base relation, since the view may not touch
2907 * all columns of the base relation.)
2908 */
2909 ListCell *lc;
2910
2911 foreach(lc, targetlist)
2912 {
2913 TargetEntry *tle = lfirst_node(TargetEntry, lc);
2914 Var *var;
2915
2916 if (tle->resjunk)
2917 continue;
2918 var = castNode(Var, tle->expr);
2919 result = bms_add_member(result,
2920 var->varattno - FirstLowInvalidHeapAttributeNumber);
2921 }
2922 }
2923 else
2924 {
2925 /*
2926 * Views do not have system columns, so we do not expect to see
2927 * any other system attnos here. If we do find one, the error
2928 * case will apply.
2929 */
2930 TargetEntry *tle = get_tle_by_resno(targetlist, attno);
2931
2932 if (tle != NULL && !tle->resjunk && IsA(tle->expr, Var))
2933 {
2934 Var *var = (Var *) tle->expr;
2935
2936 result = bms_add_member(result,
2937 var->varattno - FirstLowInvalidHeapAttributeNumber);
2938 }
2939 else
2940 elog(ERROR, "attribute number %d not found in view targetlist",
2941 attno);
2942 }
2943 }
2944
2945 return result;
2946 }
2947
2948
2949 /*
2950 * rewriteTargetView -
2951 * Attempt to rewrite a query where the target relation is a view, so that
2952 * the view's base relation becomes the target relation.
2953 *
2954 * Note that the base relation here may itself be a view, which may or may not
2955 * have INSTEAD OF triggers or rules to handle the update. That is handled by
2956 * the recursion in RewriteQuery.
2957 */
2958 static Query *
rewriteTargetView(Query * parsetree,Relation view)2959 rewriteTargetView(Query *parsetree, Relation view)
2960 {
2961 Query *viewquery;
2962 const char *auto_update_detail;
2963 RangeTblRef *rtr;
2964 int base_rt_index;
2965 int new_rt_index;
2966 RangeTblEntry *base_rte;
2967 RangeTblEntry *view_rte;
2968 RangeTblEntry *new_rte;
2969 Relation base_rel;
2970 List *view_targetlist;
2971 ListCell *lc;
2972
2973 /*
2974 * Get the Query from the view's ON SELECT rule. We're going to munge the
2975 * Query to change the view's base relation into the target relation,
2976 * along with various other changes along the way, so we need to make a
2977 * copy of it (get_view_query() returns a pointer into the relcache, so we
2978 * have to treat it as read-only).
2979 */
2980 viewquery = copyObject(get_view_query(view));
2981
2982 /* The view must be updatable, else fail */
2983 auto_update_detail =
2984 view_query_is_auto_updatable(viewquery,
2985 parsetree->commandType != CMD_DELETE);
2986
2987 if (auto_update_detail)
2988 {
2989 /* messages here should match execMain.c's CheckValidResultRel */
2990 switch (parsetree->commandType)
2991 {
2992 case CMD_INSERT:
2993 ereport(ERROR,
2994 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2995 errmsg("cannot insert into view \"%s\"",
2996 RelationGetRelationName(view)),
2997 errdetail_internal("%s", _(auto_update_detail)),
2998 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
2999 break;
3000 case CMD_UPDATE:
3001 ereport(ERROR,
3002 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3003 errmsg("cannot update view \"%s\"",
3004 RelationGetRelationName(view)),
3005 errdetail_internal("%s", _(auto_update_detail)),
3006 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
3007 break;
3008 case CMD_DELETE:
3009 ereport(ERROR,
3010 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3011 errmsg("cannot delete from view \"%s\"",
3012 RelationGetRelationName(view)),
3013 errdetail_internal("%s", _(auto_update_detail)),
3014 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
3015 break;
3016 default:
3017 elog(ERROR, "unrecognized CmdType: %d",
3018 (int) parsetree->commandType);
3019 break;
3020 }
3021 }
3022
3023 /*
3024 * For INSERT/UPDATE the modified columns must all be updatable. Note that
3025 * we get the modified columns from the query's targetlist, not from the
3026 * result RTE's insertedCols and/or updatedCols set, since
3027 * rewriteTargetListIU may have added additional targetlist entries for
3028 * view defaults, and these must also be updatable.
3029 */
3030 if (parsetree->commandType != CMD_DELETE)
3031 {
3032 Bitmapset *modified_cols = NULL;
3033 char *non_updatable_col;
3034
3035 foreach(lc, parsetree->targetList)
3036 {
3037 TargetEntry *tle = (TargetEntry *) lfirst(lc);
3038
3039 if (!tle->resjunk)
3040 modified_cols = bms_add_member(modified_cols,
3041 tle->resno - FirstLowInvalidHeapAttributeNumber);
3042 }
3043
3044 if (parsetree->onConflict)
3045 {
3046 foreach(lc, parsetree->onConflict->onConflictSet)
3047 {
3048 TargetEntry *tle = (TargetEntry *) lfirst(lc);
3049
3050 if (!tle->resjunk)
3051 modified_cols = bms_add_member(modified_cols,
3052 tle->resno - FirstLowInvalidHeapAttributeNumber);
3053 }
3054 }
3055
3056 auto_update_detail = view_cols_are_auto_updatable(viewquery,
3057 modified_cols,
3058 NULL,
3059 &non_updatable_col);
3060 if (auto_update_detail)
3061 {
3062 /*
3063 * This is a different error, caused by an attempt to update a
3064 * non-updatable column in an otherwise updatable view.
3065 */
3066 switch (parsetree->commandType)
3067 {
3068 case CMD_INSERT:
3069 ereport(ERROR,
3070 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3071 errmsg("cannot insert into column \"%s\" of view \"%s\"",
3072 non_updatable_col,
3073 RelationGetRelationName(view)),
3074 errdetail_internal("%s", _(auto_update_detail))));
3075 break;
3076 case CMD_UPDATE:
3077 ereport(ERROR,
3078 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3079 errmsg("cannot update column \"%s\" of view \"%s\"",
3080 non_updatable_col,
3081 RelationGetRelationName(view)),
3082 errdetail_internal("%s", _(auto_update_detail))));
3083 break;
3084 default:
3085 elog(ERROR, "unrecognized CmdType: %d",
3086 (int) parsetree->commandType);
3087 break;
3088 }
3089 }
3090 }
3091
3092 /* Locate RTE describing the view in the outer query */
3093 view_rte = rt_fetch(parsetree->resultRelation, parsetree->rtable);
3094
3095 /*
3096 * If we get here, view_query_is_auto_updatable() has verified that the
3097 * view contains a single base relation.
3098 */
3099 Assert(list_length(viewquery->jointree->fromlist) == 1);
3100 rtr = linitial_node(RangeTblRef, viewquery->jointree->fromlist);
3101
3102 base_rt_index = rtr->rtindex;
3103 base_rte = rt_fetch(base_rt_index, viewquery->rtable);
3104 Assert(base_rte->rtekind == RTE_RELATION);
3105
3106 /*
3107 * Up to now, the base relation hasn't been touched at all in our query.
3108 * We need to acquire lock on it before we try to do anything with it.
3109 * (The subsequent recursive call of RewriteQuery will suppose that we
3110 * already have the right lock!) Since it will become the query target
3111 * relation, RowExclusiveLock is always the right thing.
3112 */
3113 base_rel = table_open(base_rte->relid, RowExclusiveLock);
3114
3115 /*
3116 * While we have the relation open, update the RTE's relkind, just in case
3117 * it changed since this view was made (cf. AcquireRewriteLocks).
3118 */
3119 base_rte->relkind = base_rel->rd_rel->relkind;
3120
3121 /*
3122 * If the view query contains any sublink subqueries then we need to also
3123 * acquire locks on any relations they refer to. We know that there won't
3124 * be any subqueries in the range table or CTEs, so we can skip those, as
3125 * in AcquireRewriteLocks.
3126 */
3127 if (viewquery->hasSubLinks)
3128 {
3129 acquireLocksOnSubLinks_context context;
3130
3131 context.for_execute = true;
3132 query_tree_walker(viewquery, acquireLocksOnSubLinks, &context,
3133 QTW_IGNORE_RC_SUBQUERIES);
3134 }
3135
3136 /*
3137 * Create a new target RTE describing the base relation, and add it to the
3138 * outer query's rangetable. (What's happening in the next few steps is
3139 * very much like what the planner would do to "pull up" the view into the
3140 * outer query. Perhaps someday we should refactor things enough so that
3141 * we can share code with the planner.)
3142 *
3143 * Be sure to set rellockmode to the correct thing for the target table.
3144 * Since we copied the whole viewquery above, we can just scribble on
3145 * base_rte instead of copying it.
3146 */
3147 new_rte = base_rte;
3148 new_rte->rellockmode = RowExclusiveLock;
3149
3150 parsetree->rtable = lappend(parsetree->rtable, new_rte);
3151 new_rt_index = list_length(parsetree->rtable);
3152
3153 /*
3154 * INSERTs never inherit. For UPDATE/DELETE, we use the view query's
3155 * inheritance flag for the base relation.
3156 */
3157 if (parsetree->commandType == CMD_INSERT)
3158 new_rte->inh = false;
3159
3160 /*
3161 * Adjust the view's targetlist Vars to reference the new target RTE, ie
3162 * make their varnos be new_rt_index instead of base_rt_index. There can
3163 * be no Vars for other rels in the tlist, so this is sufficient to pull
3164 * up the tlist expressions for use in the outer query. The tlist will
3165 * provide the replacement expressions used by ReplaceVarsFromTargetList
3166 * below.
3167 */
3168 view_targetlist = viewquery->targetList;
3169
3170 ChangeVarNodes((Node *) view_targetlist,
3171 base_rt_index,
3172 new_rt_index,
3173 0);
3174
3175 /*
3176 * Mark the new target RTE for the permissions checks that we want to
3177 * enforce against the view owner, as distinct from the query caller. At
3178 * the relation level, require the same INSERT/UPDATE/DELETE permissions
3179 * that the query caller needs against the view. We drop the ACL_SELECT
3180 * bit that is presumably in new_rte->requiredPerms initially.
3181 *
3182 * Note: the original view RTE remains in the query's rangetable list.
3183 * Although it will be unused in the query plan, we need it there so that
3184 * the executor still performs appropriate permissions checks for the
3185 * query caller's use of the view.
3186 */
3187 new_rte->checkAsUser = view->rd_rel->relowner;
3188 new_rte->requiredPerms = view_rte->requiredPerms;
3189
3190 /*
3191 * Now for the per-column permissions bits.
3192 *
3193 * Initially, new_rte contains selectedCols permission check bits for all
3194 * base-rel columns referenced by the view, but since the view is a SELECT
3195 * query its insertedCols/updatedCols is empty. We set insertedCols and
3196 * updatedCols to include all the columns the outer query is trying to
3197 * modify, adjusting the column numbers as needed. But we leave
3198 * selectedCols as-is, so the view owner must have read permission for all
3199 * columns used in the view definition, even if some of them are not read
3200 * by the outer query. We could try to limit selectedCols to only columns
3201 * used in the transformed query, but that does not correspond to what
3202 * happens in ordinary SELECT usage of a view: all referenced columns must
3203 * have read permission, even if optimization finds that some of them can
3204 * be discarded during query transformation. The flattening we're doing
3205 * here is an optional optimization, too. (If you are unpersuaded and
3206 * want to change this, note that applying adjust_view_column_set to
3207 * view_rte->selectedCols is clearly *not* the right answer, since that
3208 * neglects base-rel columns used in the view's WHERE quals.)
3209 *
3210 * This step needs the modified view targetlist, so we have to do things
3211 * in this order.
3212 */
3213 Assert(bms_is_empty(new_rte->insertedCols) &&
3214 bms_is_empty(new_rte->updatedCols));
3215
3216 new_rte->insertedCols = adjust_view_column_set(view_rte->insertedCols,
3217 view_targetlist);
3218
3219 new_rte->updatedCols = adjust_view_column_set(view_rte->updatedCols,
3220 view_targetlist);
3221
3222 /*
3223 * Move any security barrier quals from the view RTE onto the new target
3224 * RTE. Any such quals should now apply to the new target RTE and will
3225 * not reference the original view RTE in the rewritten query.
3226 */
3227 new_rte->securityQuals = view_rte->securityQuals;
3228 view_rte->securityQuals = NIL;
3229
3230 /*
3231 * Now update all Vars in the outer query that reference the view to
3232 * reference the appropriate column of the base relation instead.
3233 */
3234 parsetree = (Query *)
3235 ReplaceVarsFromTargetList((Node *) parsetree,
3236 parsetree->resultRelation,
3237 0,
3238 view_rte,
3239 view_targetlist,
3240 REPLACEVARS_REPORT_ERROR,
3241 0,
3242 &parsetree->hasSubLinks);
3243
3244 /*
3245 * Update all other RTI references in the query that point to the view
3246 * (for example, parsetree->resultRelation itself) to point to the new
3247 * base relation instead. Vars will not be affected since none of them
3248 * reference parsetree->resultRelation any longer.
3249 */
3250 ChangeVarNodes((Node *) parsetree,
3251 parsetree->resultRelation,
3252 new_rt_index,
3253 0);
3254 Assert(parsetree->resultRelation == new_rt_index);
3255
3256 /*
3257 * For INSERT/UPDATE we must also update resnos in the targetlist to refer
3258 * to columns of the base relation, since those indicate the target
3259 * columns to be affected.
3260 *
3261 * Note that this destroys the resno ordering of the targetlist, but that
3262 * will be fixed when we recurse through rewriteQuery, which will invoke
3263 * rewriteTargetListIU again on the updated targetlist.
3264 */
3265 if (parsetree->commandType != CMD_DELETE)
3266 {
3267 foreach(lc, parsetree->targetList)
3268 {
3269 TargetEntry *tle = (TargetEntry *) lfirst(lc);
3270 TargetEntry *view_tle;
3271
3272 if (tle->resjunk)
3273 continue;
3274
3275 view_tle = get_tle_by_resno(view_targetlist, tle->resno);
3276 if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
3277 tle->resno = ((Var *) view_tle->expr)->varattno;
3278 else
3279 elog(ERROR, "attribute number %d not found in view targetlist",
3280 tle->resno);
3281 }
3282 }
3283
3284 /*
3285 * For INSERT .. ON CONFLICT .. DO UPDATE, we must also update assorted
3286 * stuff in the onConflict data structure.
3287 */
3288 if (parsetree->onConflict &&
3289 parsetree->onConflict->action == ONCONFLICT_UPDATE)
3290 {
3291 Index old_exclRelIndex,
3292 new_exclRelIndex;
3293 ParseNamespaceItem *new_exclNSItem;
3294 RangeTblEntry *new_exclRte;
3295 List *tmp_tlist;
3296
3297 /*
3298 * Like the INSERT/UPDATE code above, update the resnos in the
3299 * auxiliary UPDATE targetlist to refer to columns of the base
3300 * relation.
3301 */
3302 foreach(lc, parsetree->onConflict->onConflictSet)
3303 {
3304 TargetEntry *tle = (TargetEntry *) lfirst(lc);
3305 TargetEntry *view_tle;
3306
3307 if (tle->resjunk)
3308 continue;
3309
3310 view_tle = get_tle_by_resno(view_targetlist, tle->resno);
3311 if (view_tle != NULL && !view_tle->resjunk && IsA(view_tle->expr, Var))
3312 tle->resno = ((Var *) view_tle->expr)->varattno;
3313 else
3314 elog(ERROR, "attribute number %d not found in view targetlist",
3315 tle->resno);
3316 }
3317
3318 /*
3319 * Also, create a new RTE for the EXCLUDED pseudo-relation, using the
3320 * query's new base rel (which may well have a different column list
3321 * from the view, hence we need a new column alias list). This should
3322 * match transformOnConflictClause. In particular, note that the
3323 * relkind is set to composite to signal that we're not dealing with
3324 * an actual relation, and no permissions checks are wanted.
3325 */
3326 old_exclRelIndex = parsetree->onConflict->exclRelIndex;
3327
3328 new_exclNSItem = addRangeTableEntryForRelation(make_parsestate(NULL),
3329 base_rel,
3330 RowExclusiveLock,
3331 makeAlias("excluded", NIL),
3332 false, false);
3333 new_exclRte = new_exclNSItem->p_rte;
3334 new_exclRte->relkind = RELKIND_COMPOSITE_TYPE;
3335 new_exclRte->requiredPerms = 0;
3336 /* other permissions fields in new_exclRte are already empty */
3337
3338 parsetree->rtable = lappend(parsetree->rtable, new_exclRte);
3339 new_exclRelIndex = parsetree->onConflict->exclRelIndex =
3340 list_length(parsetree->rtable);
3341
3342 /*
3343 * Replace the targetlist for the EXCLUDED pseudo-relation with a new
3344 * one, representing the columns from the new base relation.
3345 */
3346 parsetree->onConflict->exclRelTlist =
3347 BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex);
3348
3349 /*
3350 * Update all Vars in the ON CONFLICT clause that refer to the old
3351 * EXCLUDED pseudo-relation. We want to use the column mappings
3352 * defined in the view targetlist, but we need the outputs to refer to
3353 * the new EXCLUDED pseudo-relation rather than the new target RTE.
3354 * Also notice that "EXCLUDED.*" will be expanded using the view's
3355 * rowtype, which seems correct.
3356 */
3357 tmp_tlist = copyObject(view_targetlist);
3358
3359 ChangeVarNodes((Node *) tmp_tlist, new_rt_index,
3360 new_exclRelIndex, 0);
3361
3362 parsetree->onConflict = (OnConflictExpr *)
3363 ReplaceVarsFromTargetList((Node *) parsetree->onConflict,
3364 old_exclRelIndex,
3365 0,
3366 view_rte,
3367 tmp_tlist,
3368 REPLACEVARS_REPORT_ERROR,
3369 0,
3370 &parsetree->hasSubLinks);
3371 }
3372
3373 /*
3374 * For UPDATE/DELETE, pull up any WHERE quals from the view. We know that
3375 * any Vars in the quals must reference the one base relation, so we need
3376 * only adjust their varnos to reference the new target (just the same as
3377 * we did with the view targetlist).
3378 *
3379 * If it's a security-barrier view, its WHERE quals must be applied before
3380 * quals from the outer query, so we attach them to the RTE as security
3381 * barrier quals rather than adding them to the main WHERE clause.
3382 *
3383 * For INSERT, the view's quals can be ignored in the main query.
3384 */
3385 if (parsetree->commandType != CMD_INSERT &&
3386 viewquery->jointree->quals != NULL)
3387 {
3388 Node *viewqual = (Node *) viewquery->jointree->quals;
3389
3390 /*
3391 * Even though we copied viewquery already at the top of this
3392 * function, we must duplicate the viewqual again here, because we may
3393 * need to use the quals again below for a WithCheckOption clause.
3394 */
3395 viewqual = copyObject(viewqual);
3396
3397 ChangeVarNodes(viewqual, base_rt_index, new_rt_index, 0);
3398
3399 if (RelationIsSecurityView(view))
3400 {
3401 /*
3402 * The view's quals go in front of existing barrier quals: those
3403 * would have come from an outer level of security-barrier view,
3404 * and so must get evaluated later.
3405 *
3406 * Note: the parsetree has been mutated, so the new_rte pointer is
3407 * stale and needs to be re-computed.
3408 */
3409 new_rte = rt_fetch(new_rt_index, parsetree->rtable);
3410 new_rte->securityQuals = lcons(viewqual, new_rte->securityQuals);
3411
3412 /*
3413 * Do not set parsetree->hasRowSecurity, because these aren't RLS
3414 * conditions (they aren't affected by enabling/disabling RLS).
3415 */
3416
3417 /*
3418 * Make sure that the query is marked correctly if the added qual
3419 * has sublinks.
3420 */
3421 if (!parsetree->hasSubLinks)
3422 parsetree->hasSubLinks = checkExprHasSubLink(viewqual);
3423 }
3424 else
3425 AddQual(parsetree, (Node *) viewqual);
3426 }
3427
3428 /*
3429 * For INSERT/UPDATE, if the view has the WITH CHECK OPTION, or any parent
3430 * view specified WITH CASCADED CHECK OPTION, add the quals from the view
3431 * to the query's withCheckOptions list.
3432 */
3433 if (parsetree->commandType != CMD_DELETE)
3434 {
3435 bool has_wco = RelationHasCheckOption(view);
3436 bool cascaded = RelationHasCascadedCheckOption(view);
3437
3438 /*
3439 * If the parent view has a cascaded check option, treat this view as
3440 * if it also had a cascaded check option.
3441 *
3442 * New WithCheckOptions are added to the start of the list, so if
3443 * there is a cascaded check option, it will be the first item in the
3444 * list.
3445 */
3446 if (parsetree->withCheckOptions != NIL)
3447 {
3448 WithCheckOption *parent_wco =
3449 (WithCheckOption *) linitial(parsetree->withCheckOptions);
3450
3451 if (parent_wco->cascaded)
3452 {
3453 has_wco = true;
3454 cascaded = true;
3455 }
3456 }
3457
3458 /*
3459 * Add the new WithCheckOption to the start of the list, so that
3460 * checks on inner views are run before checks on outer views, as
3461 * required by the SQL standard.
3462 *
3463 * If the new check is CASCADED, we need to add it even if this view
3464 * has no quals, since there may be quals on child views. A LOCAL
3465 * check can be omitted if this view has no quals.
3466 */
3467 if (has_wco && (cascaded || viewquery->jointree->quals != NULL))
3468 {
3469 WithCheckOption *wco;
3470
3471 wco = makeNode(WithCheckOption);
3472 wco->kind = WCO_VIEW_CHECK;
3473 wco->relname = pstrdup(RelationGetRelationName(view));
3474 wco->polname = NULL;
3475 wco->qual = NULL;
3476 wco->cascaded = cascaded;
3477
3478 parsetree->withCheckOptions = lcons(wco,
3479 parsetree->withCheckOptions);
3480
3481 if (viewquery->jointree->quals != NULL)
3482 {
3483 wco->qual = (Node *) viewquery->jointree->quals;
3484 ChangeVarNodes(wco->qual, base_rt_index, new_rt_index, 0);
3485
3486 /*
3487 * Make sure that the query is marked correctly if the added
3488 * qual has sublinks. We can skip this check if the query is
3489 * already marked, or if the command is an UPDATE, in which
3490 * case the same qual will have already been added, and this
3491 * check will already have been done.
3492 */
3493 if (!parsetree->hasSubLinks &&
3494 parsetree->commandType != CMD_UPDATE)
3495 parsetree->hasSubLinks = checkExprHasSubLink(wco->qual);
3496 }
3497 }
3498 }
3499
3500 table_close(base_rel, NoLock);
3501
3502 return parsetree;
3503 }
3504
3505
3506 /*
3507 * RewriteQuery -
3508 * rewrites the query and apply the rules again on the queries rewritten
3509 *
3510 * rewrite_events is a list of open query-rewrite actions, so we can detect
3511 * infinite recursion.
3512 */
3513 static List *
RewriteQuery(Query * parsetree,List * rewrite_events)3514 RewriteQuery(Query *parsetree, List *rewrite_events)
3515 {
3516 CmdType event = parsetree->commandType;
3517 bool instead = false;
3518 bool returning = false;
3519 bool updatableview = false;
3520 Query *qual_product = NULL;
3521 List *rewritten = NIL;
3522 ListCell *lc1;
3523
3524 /*
3525 * First, recursively process any insert/update/delete statements in WITH
3526 * clauses. (We have to do this first because the WITH clauses may get
3527 * copied into rule actions below.)
3528 */
3529 foreach(lc1, parsetree->cteList)
3530 {
3531 CommonTableExpr *cte = lfirst_node(CommonTableExpr, lc1);
3532 Query *ctequery = castNode(Query, cte->ctequery);
3533 List *newstuff;
3534
3535 if (ctequery->commandType == CMD_SELECT)
3536 continue;
3537
3538 newstuff = RewriteQuery(ctequery, rewrite_events);
3539
3540 /*
3541 * Currently we can only handle unconditional, single-statement DO
3542 * INSTEAD rules correctly; we have to get exactly one non-utility
3543 * Query out of the rewrite operation to stuff back into the CTE node.
3544 */
3545 if (list_length(newstuff) == 1)
3546 {
3547 /* Must check it's not a utility command */
3548 ctequery = linitial_node(Query, newstuff);
3549 if (!(ctequery->commandType == CMD_SELECT ||
3550 ctequery->commandType == CMD_UPDATE ||
3551 ctequery->commandType == CMD_INSERT ||
3552 ctequery->commandType == CMD_DELETE))
3553 {
3554 /*
3555 * Currently it could only be NOTIFY; this error message will
3556 * need work if we ever allow other utility commands in rules.
3557 */
3558 ereport(ERROR,
3559 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3560 errmsg("DO INSTEAD NOTIFY rules are not supported for data-modifying statements in WITH")));
3561 }
3562 /* WITH queries should never be canSetTag */
3563 Assert(!ctequery->canSetTag);
3564 /* Push the single Query back into the CTE node */
3565 cte->ctequery = (Node *) ctequery;
3566 }
3567 else if (newstuff == NIL)
3568 {
3569 ereport(ERROR,
3570 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3571 errmsg("DO INSTEAD NOTHING rules are not supported for data-modifying statements in WITH")));
3572 }
3573 else
3574 {
3575 ListCell *lc2;
3576
3577 /* examine queries to determine which error message to issue */
3578 foreach(lc2, newstuff)
3579 {
3580 Query *q = (Query *) lfirst(lc2);
3581
3582 if (q->querySource == QSRC_QUAL_INSTEAD_RULE)
3583 ereport(ERROR,
3584 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3585 errmsg("conditional DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3586 if (q->querySource == QSRC_NON_INSTEAD_RULE)
3587 ereport(ERROR,
3588 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3589 errmsg("DO ALSO rules are not supported for data-modifying statements in WITH")));
3590 }
3591
3592 ereport(ERROR,
3593 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3594 errmsg("multi-statement DO INSTEAD rules are not supported for data-modifying statements in WITH")));
3595 }
3596 }
3597
3598 /*
3599 * If the statement is an insert, update, or delete, adjust its targetlist
3600 * as needed, and then fire INSERT/UPDATE/DELETE rules on it.
3601 *
3602 * SELECT rules are handled later when we have all the queries that should
3603 * get executed. Also, utilities aren't rewritten at all (do we still
3604 * need that check?)
3605 */
3606 if (event != CMD_SELECT && event != CMD_UTILITY)
3607 {
3608 int result_relation;
3609 RangeTblEntry *rt_entry;
3610 Relation rt_entry_relation;
3611 List *locks;
3612 List *product_queries;
3613 bool hasUpdate = false;
3614 int values_rte_index = 0;
3615 bool defaults_remaining = false;
3616
3617 result_relation = parsetree->resultRelation;
3618 Assert(result_relation != 0);
3619 rt_entry = rt_fetch(result_relation, parsetree->rtable);
3620 Assert(rt_entry->rtekind == RTE_RELATION);
3621
3622 /*
3623 * We can use NoLock here since either the parser or
3624 * AcquireRewriteLocks should have locked the rel already.
3625 */
3626 rt_entry_relation = table_open(rt_entry->relid, NoLock);
3627
3628 /*
3629 * Rewrite the targetlist as needed for the command type.
3630 */
3631 if (event == CMD_INSERT)
3632 {
3633 RangeTblEntry *values_rte = NULL;
3634
3635 /*
3636 * If it's an INSERT ... VALUES (...), (...), ... there will be a
3637 * single RTE for the VALUES targetlists.
3638 */
3639 if (list_length(parsetree->jointree->fromlist) == 1)
3640 {
3641 RangeTblRef *rtr = (RangeTblRef *) linitial(parsetree->jointree->fromlist);
3642
3643 if (IsA(rtr, RangeTblRef))
3644 {
3645 RangeTblEntry *rte = rt_fetch(rtr->rtindex,
3646 parsetree->rtable);
3647
3648 if (rte->rtekind == RTE_VALUES)
3649 {
3650 values_rte = rte;
3651 values_rte_index = rtr->rtindex;
3652 }
3653 }
3654 }
3655
3656 if (values_rte)
3657 {
3658 /* Process the main targetlist ... */
3659 parsetree->targetList = rewriteTargetListIU(parsetree->targetList,
3660 parsetree->commandType,
3661 parsetree->override,
3662 rt_entry_relation,
3663 parsetree->resultRelation);
3664 /* ... and the VALUES expression lists */
3665 if (!rewriteValuesRTE(parsetree, values_rte, values_rte_index,
3666 rt_entry_relation, false))
3667 defaults_remaining = true;
3668 }
3669 else
3670 {
3671 /* Process just the main targetlist */
3672 parsetree->targetList =
3673 rewriteTargetListIU(parsetree->targetList,
3674 parsetree->commandType,
3675 parsetree->override,
3676 rt_entry_relation,
3677 parsetree->resultRelation);
3678 }
3679
3680 if (parsetree->onConflict &&
3681 parsetree->onConflict->action == ONCONFLICT_UPDATE)
3682 {
3683 parsetree->onConflict->onConflictSet =
3684 rewriteTargetListIU(parsetree->onConflict->onConflictSet,
3685 CMD_UPDATE,
3686 parsetree->override,
3687 rt_entry_relation,
3688 parsetree->resultRelation);
3689 }
3690 }
3691 else if (event == CMD_UPDATE)
3692 {
3693 parsetree->targetList =
3694 rewriteTargetListIU(parsetree->targetList,
3695 parsetree->commandType,
3696 parsetree->override,
3697 rt_entry_relation,
3698 parsetree->resultRelation);
3699
3700 /* Also populate extraUpdatedCols (for generated columns) */
3701 fill_extraUpdatedCols(rt_entry, rt_entry_relation);
3702 }
3703 else if (event == CMD_DELETE)
3704 {
3705 /* Nothing to do here */
3706 }
3707 else
3708 elog(ERROR, "unrecognized commandType: %d", (int) event);
3709
3710 /*
3711 * Collect and apply the appropriate rules.
3712 */
3713 locks = matchLocks(event, rt_entry_relation->rd_rules,
3714 result_relation, parsetree, &hasUpdate);
3715
3716 product_queries = fireRules(parsetree,
3717 result_relation,
3718 event,
3719 locks,
3720 &instead,
3721 &returning,
3722 &qual_product);
3723
3724 /*
3725 * If we have a VALUES RTE with any remaining untouched DEFAULT items,
3726 * and we got any product queries, finalize the VALUES RTE for each
3727 * product query (replacing the remaining DEFAULT items with NULLs).
3728 * We don't do this for the original query, because we know that it
3729 * must be an auto-insert on a view, and so should use the base
3730 * relation's defaults for any remaining DEFAULT items.
3731 */
3732 if (defaults_remaining && product_queries != NIL)
3733 {
3734 ListCell *n;
3735
3736 /*
3737 * Each product query has its own copy of the VALUES RTE at the
3738 * same index in the rangetable, so we must finalize each one.
3739 */
3740 foreach(n, product_queries)
3741 {
3742 Query *pt = (Query *) lfirst(n);
3743 RangeTblEntry *values_rte = rt_fetch(values_rte_index,
3744 pt->rtable);
3745
3746 rewriteValuesRTE(pt, values_rte, values_rte_index,
3747 rt_entry_relation,
3748 true); /* Force remaining defaults to NULL */
3749 }
3750 }
3751
3752 /*
3753 * If there was no unqualified INSTEAD rule, and the target relation
3754 * is a view without any INSTEAD OF triggers, see if the view can be
3755 * automatically updated. If so, we perform the necessary query
3756 * transformation here and add the resulting query to the
3757 * product_queries list, so that it gets recursively rewritten if
3758 * necessary.
3759 *
3760 * If the view cannot be automatically updated, we throw an error here
3761 * which is OK since the query would fail at runtime anyway. Throwing
3762 * the error here is preferable to the executor check since we have
3763 * more detailed information available about why the view isn't
3764 * updatable.
3765 */
3766 if (!instead &&
3767 rt_entry_relation->rd_rel->relkind == RELKIND_VIEW &&
3768 !view_has_instead_trigger(rt_entry_relation, event))
3769 {
3770 /*
3771 * If there were any qualified INSTEAD rules, don't allow the view
3772 * to be automatically updated (an unqualified INSTEAD rule or
3773 * INSTEAD OF trigger is required).
3774 *
3775 * The messages here should match execMain.c's CheckValidResultRel
3776 * and in principle make those checks in executor unnecessary, but
3777 * we keep them just in case.
3778 */
3779 if (qual_product != NULL)
3780 {
3781 switch (parsetree->commandType)
3782 {
3783 case CMD_INSERT:
3784 ereport(ERROR,
3785 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3786 errmsg("cannot insert into view \"%s\"",
3787 RelationGetRelationName(rt_entry_relation)),
3788 errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3789 errhint("To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.")));
3790 break;
3791 case CMD_UPDATE:
3792 ereport(ERROR,
3793 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3794 errmsg("cannot update view \"%s\"",
3795 RelationGetRelationName(rt_entry_relation)),
3796 errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3797 errhint("To enable updating the view, provide an INSTEAD OF UPDATE trigger or an unconditional ON UPDATE DO INSTEAD rule.")));
3798 break;
3799 case CMD_DELETE:
3800 ereport(ERROR,
3801 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3802 errmsg("cannot delete from view \"%s\"",
3803 RelationGetRelationName(rt_entry_relation)),
3804 errdetail("Views with conditional DO INSTEAD rules are not automatically updatable."),
3805 errhint("To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.")));
3806 break;
3807 default:
3808 elog(ERROR, "unrecognized CmdType: %d",
3809 (int) parsetree->commandType);
3810 break;
3811 }
3812 }
3813
3814 /*
3815 * Attempt to rewrite the query to automatically update the view.
3816 * This throws an error if the view can't be automatically
3817 * updated.
3818 */
3819 parsetree = rewriteTargetView(parsetree, rt_entry_relation);
3820
3821 /*
3822 * At this point product_queries contains any DO ALSO rule
3823 * actions. Add the rewritten query before or after those. This
3824 * must match the handling the original query would have gotten
3825 * below, if we allowed it to be included again.
3826 */
3827 if (parsetree->commandType == CMD_INSERT)
3828 product_queries = lcons(parsetree, product_queries);
3829 else
3830 product_queries = lappend(product_queries, parsetree);
3831
3832 /*
3833 * Set the "instead" flag, as if there had been an unqualified
3834 * INSTEAD, to prevent the original query from being included a
3835 * second time below. The transformation will have rewritten any
3836 * RETURNING list, so we can also set "returning" to forestall
3837 * throwing an error below.
3838 */
3839 instead = true;
3840 returning = true;
3841 updatableview = true;
3842 }
3843
3844 /*
3845 * If we got any product queries, recursively rewrite them --- but
3846 * first check for recursion!
3847 */
3848 if (product_queries != NIL)
3849 {
3850 ListCell *n;
3851 rewrite_event *rev;
3852
3853 foreach(n, rewrite_events)
3854 {
3855 rev = (rewrite_event *) lfirst(n);
3856 if (rev->relation == RelationGetRelid(rt_entry_relation) &&
3857 rev->event == event)
3858 ereport(ERROR,
3859 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
3860 errmsg("infinite recursion detected in rules for relation \"%s\"",
3861 RelationGetRelationName(rt_entry_relation))));
3862 }
3863
3864 rev = (rewrite_event *) palloc(sizeof(rewrite_event));
3865 rev->relation = RelationGetRelid(rt_entry_relation);
3866 rev->event = event;
3867 rewrite_events = lappend(rewrite_events, rev);
3868
3869 foreach(n, product_queries)
3870 {
3871 Query *pt = (Query *) lfirst(n);
3872 List *newstuff;
3873
3874 newstuff = RewriteQuery(pt, rewrite_events);
3875 rewritten = list_concat(rewritten, newstuff);
3876 }
3877
3878 rewrite_events = list_delete_last(rewrite_events);
3879 }
3880
3881 /*
3882 * If there is an INSTEAD, and the original query has a RETURNING, we
3883 * have to have found a RETURNING in the rule(s), else fail. (Because
3884 * DefineQueryRewrite only allows RETURNING in unconditional INSTEAD
3885 * rules, there's no need to worry whether the substituted RETURNING
3886 * will actually be executed --- it must be.)
3887 */
3888 if ((instead || qual_product != NULL) &&
3889 parsetree->returningList &&
3890 !returning)
3891 {
3892 switch (event)
3893 {
3894 case CMD_INSERT:
3895 ereport(ERROR,
3896 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3897 errmsg("cannot perform INSERT RETURNING on relation \"%s\"",
3898 RelationGetRelationName(rt_entry_relation)),
3899 errhint("You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.")));
3900 break;
3901 case CMD_UPDATE:
3902 ereport(ERROR,
3903 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3904 errmsg("cannot perform UPDATE RETURNING on relation \"%s\"",
3905 RelationGetRelationName(rt_entry_relation)),
3906 errhint("You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.")));
3907 break;
3908 case CMD_DELETE:
3909 ereport(ERROR,
3910 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3911 errmsg("cannot perform DELETE RETURNING on relation \"%s\"",
3912 RelationGetRelationName(rt_entry_relation)),
3913 errhint("You need an unconditional ON DELETE DO INSTEAD rule with a RETURNING clause.")));
3914 break;
3915 default:
3916 elog(ERROR, "unrecognized commandType: %d",
3917 (int) event);
3918 break;
3919 }
3920 }
3921
3922 /*
3923 * Updatable views are supported by ON CONFLICT, so don't prevent that
3924 * case from proceeding
3925 */
3926 if (parsetree->onConflict &&
3927 (product_queries != NIL || hasUpdate) &&
3928 !updatableview)
3929 ereport(ERROR,
3930 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3931 errmsg("INSERT with ON CONFLICT clause cannot be used with table that has INSERT or UPDATE rules")));
3932
3933 table_close(rt_entry_relation, NoLock);
3934 }
3935
3936 /*
3937 * For INSERTs, the original query is done first; for UPDATE/DELETE, it is
3938 * done last. This is needed because update and delete rule actions might
3939 * not do anything if they are invoked after the update or delete is
3940 * performed. The command counter increment between the query executions
3941 * makes the deleted (and maybe the updated) tuples disappear so the scans
3942 * for them in the rule actions cannot find them.
3943 *
3944 * If we found any unqualified INSTEAD, the original query is not done at
3945 * all, in any form. Otherwise, we add the modified form if qualified
3946 * INSTEADs were found, else the unmodified form.
3947 */
3948 if (!instead)
3949 {
3950 if (parsetree->commandType == CMD_INSERT)
3951 {
3952 if (qual_product != NULL)
3953 rewritten = lcons(qual_product, rewritten);
3954 else
3955 rewritten = lcons(parsetree, rewritten);
3956 }
3957 else
3958 {
3959 if (qual_product != NULL)
3960 rewritten = lappend(rewritten, qual_product);
3961 else
3962 rewritten = lappend(rewritten, parsetree);
3963 }
3964 }
3965
3966 /*
3967 * If the original query has a CTE list, and we generated more than one
3968 * non-utility result query, we have to fail because we'll have copied the
3969 * CTE list into each result query. That would break the expectation of
3970 * single evaluation of CTEs. This could possibly be fixed by
3971 * restructuring so that a CTE list can be shared across multiple Query
3972 * and PlannableStatement nodes.
3973 */
3974 if (parsetree->cteList != NIL)
3975 {
3976 int qcount = 0;
3977
3978 foreach(lc1, rewritten)
3979 {
3980 Query *q = (Query *) lfirst(lc1);
3981
3982 if (q->commandType != CMD_UTILITY)
3983 qcount++;
3984 }
3985 if (qcount > 1)
3986 ereport(ERROR,
3987 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3988 errmsg("WITH cannot be used in a query that is rewritten by rules into multiple queries")));
3989 }
3990
3991 return rewritten;
3992 }
3993
3994
3995 /*
3996 * QueryRewrite -
3997 * Primary entry point to the query rewriter.
3998 * Rewrite one query via query rewrite system, possibly returning 0
3999 * or many queries.
4000 *
4001 * NOTE: the parsetree must either have come straight from the parser,
4002 * or have been scanned by AcquireRewriteLocks to acquire suitable locks.
4003 */
4004 List *
QueryRewrite(Query * parsetree)4005 QueryRewrite(Query *parsetree)
4006 {
4007 uint64 input_query_id = parsetree->queryId;
4008 List *querylist;
4009 List *results;
4010 ListCell *l;
4011 CmdType origCmdType;
4012 bool foundOriginalQuery;
4013 Query *lastInstead;
4014
4015 /*
4016 * This function is only applied to top-level original queries
4017 */
4018 Assert(parsetree->querySource == QSRC_ORIGINAL);
4019 Assert(parsetree->canSetTag);
4020
4021 /*
4022 * Step 1
4023 *
4024 * Apply all non-SELECT rules possibly getting 0 or many queries
4025 */
4026 querylist = RewriteQuery(parsetree, NIL);
4027
4028 /*
4029 * Step 2
4030 *
4031 * Apply all the RIR rules on each query
4032 *
4033 * This is also a handy place to mark each query with the original queryId
4034 */
4035 results = NIL;
4036 foreach(l, querylist)
4037 {
4038 Query *query = (Query *) lfirst(l);
4039
4040 query = fireRIRrules(query, NIL);
4041
4042 query->queryId = input_query_id;
4043
4044 results = lappend(results, query);
4045 }
4046
4047 /*
4048 * Step 3
4049 *
4050 * Determine which, if any, of the resulting queries is supposed to set
4051 * the command-result tag; and update the canSetTag fields accordingly.
4052 *
4053 * If the original query is still in the list, it sets the command tag.
4054 * Otherwise, the last INSTEAD query of the same kind as the original is
4055 * allowed to set the tag. (Note these rules can leave us with no query
4056 * setting the tag. The tcop code has to cope with this by setting up a
4057 * default tag based on the original un-rewritten query.)
4058 *
4059 * The Asserts verify that at most one query in the result list is marked
4060 * canSetTag. If we aren't checking asserts, we can fall out of the loop
4061 * as soon as we find the original query.
4062 */
4063 origCmdType = parsetree->commandType;
4064 foundOriginalQuery = false;
4065 lastInstead = NULL;
4066
4067 foreach(l, results)
4068 {
4069 Query *query = (Query *) lfirst(l);
4070
4071 if (query->querySource == QSRC_ORIGINAL)
4072 {
4073 Assert(query->canSetTag);
4074 Assert(!foundOriginalQuery);
4075 foundOriginalQuery = true;
4076 #ifndef USE_ASSERT_CHECKING
4077 break;
4078 #endif
4079 }
4080 else
4081 {
4082 Assert(!query->canSetTag);
4083 if (query->commandType == origCmdType &&
4084 (query->querySource == QSRC_INSTEAD_RULE ||
4085 query->querySource == QSRC_QUAL_INSTEAD_RULE))
4086 lastInstead = query;
4087 }
4088 }
4089
4090 if (!foundOriginalQuery && lastInstead != NULL)
4091 lastInstead->canSetTag = true;
4092
4093 return results;
4094 }
4095