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

Generated by: LCOV version 1.14