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