Debian Codegraph @

src/backend/rewrite/rewriteHandler.c

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