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