LCOV - code coverage report
Current view: top level - src/backend/rewrite - rewriteHandler.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 1134 1257 90.2 %
Date: 2024-03-28 23:11:20 Functions: 30 30 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14