LCOV - code coverage report
Current view: top level - src/backend/rewrite - rewriteHandler.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.8 % 1324 1202
Test Date: 2026-09-25 23:15:50 Functions: 100.0 % 33 33
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.4 % 1384 1071

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

Generated by: LCOV version 2.0-1