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