LCOV - code coverage report
Current view: top level - src/backend/executor - nodeModifyTable.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 93.0 % 1705 1585
Test Date: 2026-08-22 10:15:50 Functions: 97.7 % 43 42
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 78.4 % 1212 950

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * nodeModifyTable.c
       4                 :             :  *    routines to handle ModifyTable nodes.
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/executor/nodeModifyTable.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : /*
      16                 :             :  * INTERFACE ROUTINES
      17                 :             :  *      ExecInitModifyTable - initialize the ModifyTable node
      18                 :             :  *      ExecModifyTable     - retrieve the next tuple from the node
      19                 :             :  *      ExecEndModifyTable  - shut down the ModifyTable node
      20                 :             :  *      ExecReScanModifyTable - rescan the ModifyTable node
      21                 :             :  *
      22                 :             :  *   NOTES
      23                 :             :  *      The ModifyTable node receives input from its outerPlan, which is
      24                 :             :  *      the data to insert for INSERT cases, the changed columns' new
      25                 :             :  *      values plus row-locating info for UPDATE and MERGE cases, or just the
      26                 :             :  *      row-locating info for DELETE cases.
      27                 :             :  *
      28                 :             :  *      The relation to modify can be an ordinary table, a foreign table, or a
      29                 :             :  *      view.  If it's a view, either it has sufficient INSTEAD OF triggers or
      30                 :             :  *      this node executes only MERGE ... DO NOTHING.  If the original MERGE
      31                 :             :  *      targeted a view not in one of those two categories, earlier processing
      32                 :             :  *      already pointed the ModifyTable result relation to an underlying
      33                 :             :  *      relation of that other view.  This node does process
      34                 :             :  *      ri_WithCheckOptions, which may have expressions from those other,
      35                 :             :  *      automatically updatable views.
      36                 :             :  *
      37                 :             :  *      MERGE runs a join between the source relation and the target table.
      38                 :             :  *      If any WHEN NOT MATCHED [BY TARGET] clauses are present, then the join
      39                 :             :  *      is an outer join that might output tuples without a matching target
      40                 :             :  *      tuple.  In this case, any unmatched target tuples will have NULL
      41                 :             :  *      row-locating info, and only INSERT can be run.  But for matched target
      42                 :             :  *      tuples, the row-locating info is used to determine the tuple to UPDATE
      43                 :             :  *      or DELETE.  When all clauses are WHEN MATCHED or WHEN NOT MATCHED BY
      44                 :             :  *      SOURCE, all tuples produced by the join will include a matching target
      45                 :             :  *      tuple, so all tuples contain row-locating info.
      46                 :             :  *
      47                 :             :  *      If the query specifies RETURNING, then the ModifyTable returns a
      48                 :             :  *      RETURNING tuple after completing each row insert, update, or delete.
      49                 :             :  *      It must be called again to continue the operation.  Without RETURNING,
      50                 :             :  *      we just loop within the node until all the work is done, then
      51                 :             :  *      return NULL.  This avoids useless call/return overhead.
      52                 :             :  */
      53                 :             : 
      54                 :             : #include "postgres.h"
      55                 :             : 
      56                 :             : #include "access/htup_details.h"
      57                 :             : #include "access/tableam.h"
      58                 :             : #include "access/tupconvert.h"
      59                 :             : #include "access/xact.h"
      60                 :             : #include "commands/trigger.h"
      61                 :             : #include "executor/execPartition.h"
      62                 :             : #include "executor/executor.h"
      63                 :             : #include "executor/instrument.h"
      64                 :             : #include "executor/nodeModifyTable.h"
      65                 :             : #include "foreign/fdwapi.h"
      66                 :             : #include "miscadmin.h"
      67                 :             : #include "nodes/nodeFuncs.h"
      68                 :             : #include "optimizer/optimizer.h"
      69                 :             : #include "pgstat.h"
      70                 :             : #include "rewrite/rewriteHandler.h"
      71                 :             : #include "rewrite/rewriteManip.h"
      72                 :             : #include "storage/lmgr.h"
      73                 :             : #include "utils/builtins.h"
      74                 :             : #include "utils/datum.h"
      75                 :             : #include "utils/injection_point.h"
      76                 :             : #include "utils/rangetypes.h"
      77                 :             : #include "utils/rel.h"
      78                 :             : #include "utils/snapmgr.h"
      79                 :             : 
      80                 :             : 
      81                 :             : typedef struct MTTargetRelLookup
      82                 :             : {
      83                 :             :     Oid         relationOid;    /* hash key, must be first */
      84                 :             :     int         relationIndex;  /* rel's index in resultRelInfo[] array */
      85                 :             : } MTTargetRelLookup;
      86                 :             : 
      87                 :             : /*
      88                 :             :  * Context struct for a ModifyTable operation, containing basic execution
      89                 :             :  * state and some output variables populated by ExecUpdateAct() and
      90                 :             :  * ExecDeleteAct() to report the result of their actions to callers.
      91                 :             :  */
      92                 :             : typedef struct ModifyTableContext
      93                 :             : {
      94                 :             :     /* Operation state */
      95                 :             :     ModifyTableState *mtstate;
      96                 :             :     EPQState   *epqstate;
      97                 :             :     EState     *estate;
      98                 :             : 
      99                 :             :     /*
     100                 :             :      * Slot containing tuple obtained from ModifyTable's subplan.  Used to
     101                 :             :      * access "junk" columns that are not going to be stored.
     102                 :             :      */
     103                 :             :     TupleTableSlot *planSlot;
     104                 :             : 
     105                 :             :     /*
     106                 :             :      * Information about the changes that were made concurrently to a tuple
     107                 :             :      * being updated or deleted
     108                 :             :      */
     109                 :             :     TM_FailureData tmfd;
     110                 :             : 
     111                 :             :     /*
     112                 :             :      * The tuple deleted when doing a cross-partition UPDATE with a RETURNING
     113                 :             :      * clause that refers to OLD columns (converted to the root's tuple
     114                 :             :      * descriptor).
     115                 :             :      */
     116                 :             :     TupleTableSlot *cpDeletedSlot;
     117                 :             : 
     118                 :             :     /*
     119                 :             :      * The tuple projected by the INSERT's RETURNING clause, when doing a
     120                 :             :      * cross-partition UPDATE
     121                 :             :      */
     122                 :             :     TupleTableSlot *cpUpdateReturningSlot;
     123                 :             : } ModifyTableContext;
     124                 :             : 
     125                 :             : /*
     126                 :             :  * Context struct containing output data specific to UPDATE operations.
     127                 :             :  */
     128                 :             : typedef struct UpdateContext
     129                 :             : {
     130                 :             :     bool        crossPartUpdate;    /* was it a cross-partition update? */
     131                 :             :     TU_UpdateIndexes updateIndexes; /* Which index updates are required? */
     132                 :             : 
     133                 :             :     /*
     134                 :             :      * Lock mode to acquire on the latest tuple version before performing
     135                 :             :      * EvalPlanQual on it
     136                 :             :      */
     137                 :             :     LockTupleMode lockmode;
     138                 :             : } UpdateContext;
     139                 :             : 
     140                 :             : 
     141                 :             : static void ExecBatchInsert(ModifyTableState *mtstate,
     142                 :             :                             ResultRelInfo *resultRelInfo,
     143                 :             :                             TupleTableSlot **slots,
     144                 :             :                             TupleTableSlot **planSlots,
     145                 :             :                             int numSlots,
     146                 :             :                             EState *estate,
     147                 :             :                             bool canSetTag);
     148                 :             : static void ExecPendingInserts(EState *estate);
     149                 :             : static void ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context,
     150                 :             :                                                ResultRelInfo *sourcePartInfo,
     151                 :             :                                                ResultRelInfo *destPartInfo,
     152                 :             :                                                ItemPointer tupleid,
     153                 :             :                                                TupleTableSlot *oldslot,
     154                 :             :                                                TupleTableSlot *newslot);
     155                 :             : static bool ExecOnConflictLockRow(ModifyTableContext *context,
     156                 :             :                                   TupleTableSlot *existing,
     157                 :             :                                   ItemPointer conflictTid,
     158                 :             :                                   Relation relation,
     159                 :             :                                   LockTupleMode lockmode,
     160                 :             :                                   bool isUpdate);
     161                 :             : static bool ExecOnConflictUpdate(ModifyTableContext *context,
     162                 :             :                                  ResultRelInfo *resultRelInfo,
     163                 :             :                                  ItemPointer conflictTid,
     164                 :             :                                  TupleTableSlot *excludedSlot,
     165                 :             :                                  bool canSetTag,
     166                 :             :                                  TupleTableSlot **returning);
     167                 :             : static bool ExecOnConflictSelect(ModifyTableContext *context,
     168                 :             :                                  ResultRelInfo *resultRelInfo,
     169                 :             :                                  ItemPointer conflictTid,
     170                 :             :                                  TupleTableSlot *excludedSlot,
     171                 :             :                                  bool canSetTag,
     172                 :             :                                  TupleTableSlot **returning);
     173                 :             : static void ExecForPortionOfLeftovers(ModifyTableContext *context,
     174                 :             :                                       EState *estate,
     175                 :             :                                       ResultRelInfo *resultRelInfo,
     176                 :             :                                       ItemPointer tupleid);
     177                 :             : static TupleTableSlot *ExecPrepareTupleRouting(ModifyTableState *mtstate,
     178                 :             :                                                EState *estate,
     179                 :             :                                                PartitionTupleRouting *proute,
     180                 :             :                                                ResultRelInfo *targetRelInfo,
     181                 :             :                                                TupleTableSlot *slot,
     182                 :             :                                                ResultRelInfo **partRelInfo);
     183                 :             : 
     184                 :             : static TupleTableSlot *ExecMerge(ModifyTableContext *context,
     185                 :             :                                  ResultRelInfo *resultRelInfo,
     186                 :             :                                  ItemPointer tupleid,
     187                 :             :                                  HeapTuple oldtuple,
     188                 :             :                                  bool canSetTag);
     189                 :             : static void ExecInitMerge(ModifyTableState *mtstate, EState *estate);
     190                 :             : static TupleTableSlot *ExecMergeMatched(ModifyTableContext *context,
     191                 :             :                                         ResultRelInfo *resultRelInfo,
     192                 :             :                                         ItemPointer tupleid,
     193                 :             :                                         HeapTuple oldtuple,
     194                 :             :                                         bool canSetTag,
     195                 :             :                                         bool *matched);
     196                 :             : static TupleTableSlot *ExecMergeNotMatched(ModifyTableContext *context,
     197                 :             :                                            ResultRelInfo *resultRelInfo,
     198                 :             :                                            bool canSetTag);
     199                 :             : static void ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate);
     200                 :             : static void fireBSTriggers(ModifyTableState *node);
     201                 :             : static void fireASTriggers(ModifyTableState *node);
     202                 :             : static void ExecInitForPortionOf(ModifyTableState *mtstate, EState *estate,
     203                 :             :                                  ResultRelInfo *resultRelInfo);
     204                 :             : 
     205                 :             : 
     206                 :             : /*
     207                 :             :  * Verify that the tuples to be produced by INSERT match the
     208                 :             :  * target relation's rowtype
     209                 :             :  *
     210                 :             :  * We do this to guard against stale plans.  If plan invalidation is
     211                 :             :  * functioning properly then we should never get a failure here, but better
     212                 :             :  * safe than sorry.  Note that this is called after we have obtained lock
     213                 :             :  * on the target rel, so the rowtype can't change underneath us.
     214                 :             :  *
     215                 :             :  * The plan output is represented by its targetlist, because that makes
     216                 :             :  * handling the dropped-column case easier.
     217                 :             :  *
     218                 :             :  * We used to use this for UPDATE as well, but now the equivalent checks
     219                 :             :  * are done in ExecBuildUpdateProjection.
     220                 :             :  */
     221                 :             : static void
     222                 :       57724 : ExecCheckPlanOutput(Relation resultRel, List *targetList)
     223                 :             : {
     224                 :       57724 :     TupleDesc   resultDesc = RelationGetDescr(resultRel);
     225                 :       57724 :     int         attno = 0;
     226                 :             :     ListCell   *lc;
     227                 :             : 
     228   [ +  +  +  +  :      179114 :     foreach(lc, targetList)
                   +  + ]
     229                 :             :     {
     230                 :      121390 :         TargetEntry *tle = (TargetEntry *) lfirst(lc);
     231                 :             :         Form_pg_attribute attr;
     232                 :             : 
     233                 :             :         Assert(!tle->resjunk);   /* caller removed junk items already */
     234                 :             : 
     235         [ -  + ]:      121390 :         if (attno >= resultDesc->natts)
     236         [ #  # ]:           0 :             ereport(ERROR,
     237                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     238                 :             :                      errmsg("table row type and query-specified row type do not match"),
     239                 :             :                      errdetail("Query has too many columns.")));
     240                 :      121390 :         attr = TupleDescAttr(resultDesc, attno);
     241                 :      121390 :         attno++;
     242                 :             : 
     243                 :             :         /*
     244                 :             :          * Special cases here should match planner's expand_insert_targetlist.
     245                 :             :          */
     246         [ +  + ]:      121390 :         if (attr->attisdropped)
     247                 :             :         {
     248                 :             :             /*
     249                 :             :              * For a dropped column, we can't check atttypid (it's likely 0).
     250                 :             :              * In any case the planner has most likely inserted an INT4 null.
     251                 :             :              * What we insist on is just *some* NULL constant.
     252                 :             :              */
     253         [ +  - ]:         443 :             if (!IsA(tle->expr, Const) ||
     254         [ -  + ]:         443 :                 !((Const *) tle->expr)->constisnull)
     255         [ #  # ]:           0 :                 ereport(ERROR,
     256                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
     257                 :             :                          errmsg("table row type and query-specified row type do not match"),
     258                 :             :                          errdetail("Query provides a value for a dropped column at ordinal position %d.",
     259                 :             :                                    attno)));
     260                 :             :         }
     261         [ +  + ]:      120947 :         else if (attr->attgenerated)
     262                 :             :         {
     263                 :             :             /*
     264                 :             :              * For a generated column, the planner will have inserted a null
     265                 :             :              * of the column's base type (to avoid possibly failing on domain
     266                 :             :              * not-null constraints).  It doesn't seem worth insisting on that
     267                 :             :              * exact type though, since a null value is type-independent.  As
     268                 :             :              * above, just insist on *some* NULL constant.
     269                 :             :              */
     270         [ +  - ]:         927 :             if (!IsA(tle->expr, Const) ||
     271         [ -  + ]:         927 :                 !((Const *) tle->expr)->constisnull)
     272         [ #  # ]:           0 :                 ereport(ERROR,
     273                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
     274                 :             :                          errmsg("table row type and query-specified row type do not match"),
     275                 :             :                          errdetail("Query provides a value for a generated column at ordinal position %d.",
     276                 :             :                                    attno)));
     277                 :             :         }
     278                 :             :         else
     279                 :             :         {
     280                 :             :             /* Normal case: demand type match */
     281         [ -  + ]:      120020 :             if (exprType((Node *) tle->expr) != attr->atttypid)
     282         [ #  # ]:           0 :                 ereport(ERROR,
     283                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
     284                 :             :                          errmsg("table row type and query-specified row type do not match"),
     285                 :             :                          errdetail("Table has type %s at ordinal position %d, but query expects %s.",
     286                 :             :                                    format_type_be(attr->atttypid),
     287                 :             :                                    attno,
     288                 :             :                                    format_type_be(exprType((Node *) tle->expr)))));
     289                 :             :         }
     290                 :             :     }
     291         [ -  + ]:       57724 :     if (attno != resultDesc->natts)
     292         [ #  # ]:           0 :         ereport(ERROR,
     293                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
     294                 :             :                  errmsg("table row type and query-specified row type do not match"),
     295                 :             :                  errdetail("Query has too few columns.")));
     296                 :       57724 : }
     297                 :             : 
     298                 :             : /*
     299                 :             :  * ExecProcessReturning --- evaluate a RETURNING list
     300                 :             :  *
     301                 :             :  * context: context for the ModifyTable operation
     302                 :             :  * resultRelInfo: current result rel
     303                 :             :  * isDelete: true if the operation/merge action is a DELETE
     304                 :             :  * oldSlot: slot holding old tuple deleted or updated
     305                 :             :  * newSlot: slot holding new tuple inserted or updated
     306                 :             :  * planSlot: slot holding tuple returned by top subplan node
     307                 :             :  *
     308                 :             :  * Note: If oldSlot and newSlot are NULL, the FDW should have already provided
     309                 :             :  * econtext's scan tuple and its old & new tuples are not needed (FDW direct-
     310                 :             :  * modify is disabled if the RETURNING list refers to any OLD/NEW values).
     311                 :             :  *
     312                 :             :  * Note: For the SELECT path of INSERT ... ON CONFLICT DO SELECT, oldSlot and
     313                 :             :  * newSlot are both the existing tuple, since it's not changed.
     314                 :             :  *
     315                 :             :  * Returns a slot holding the result tuple
     316                 :             :  */
     317                 :             : static TupleTableSlot *
     318                 :        5745 : ExecProcessReturning(ModifyTableContext *context,
     319                 :             :                      ResultRelInfo *resultRelInfo,
     320                 :             :                      bool isDelete,
     321                 :             :                      TupleTableSlot *oldSlot,
     322                 :             :                      TupleTableSlot *newSlot,
     323                 :             :                      TupleTableSlot *planSlot)
     324                 :             : {
     325                 :        5745 :     EState     *estate = context->estate;
     326                 :        5745 :     ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning;
     327                 :        5745 :     ExprContext *econtext = projectReturning->pi_exprContext;
     328                 :             : 
     329                 :             :     /* Make tuple and any needed join variables available to ExecProject */
     330         [ +  + ]:        5745 :     if (isDelete)
     331                 :             :     {
     332                 :             :         /* return old tuple by default */
     333         [ +  + ]:         884 :         if (oldSlot)
     334                 :         765 :             econtext->ecxt_scantuple = oldSlot;
     335                 :             :     }
     336                 :             :     else
     337                 :             :     {
     338                 :             :         /* return new tuple by default */
     339         [ +  + ]:        4861 :         if (newSlot)
     340                 :        4631 :             econtext->ecxt_scantuple = newSlot;
     341                 :             :     }
     342                 :        5745 :     econtext->ecxt_outertuple = planSlot;
     343                 :             : 
     344                 :             :     /* Make old/new tuples available to ExecProject, if required */
     345         [ +  + ]:        5745 :     if (oldSlot)
     346                 :        2598 :         econtext->ecxt_oldtuple = oldSlot;
     347         [ +  + ]:        3147 :     else if (projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD)
     348                 :         138 :         econtext->ecxt_oldtuple = ExecGetAllNullSlot(estate, resultRelInfo);
     349                 :             :     else
     350                 :        3009 :         econtext->ecxt_oldtuple = NULL; /* No references to OLD columns */
     351                 :             : 
     352         [ +  + ]:        5745 :     if (newSlot)
     353                 :        4631 :         econtext->ecxt_newtuple = newSlot;
     354         [ +  + ]:        1114 :     else if (projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW)
     355                 :         103 :         econtext->ecxt_newtuple = ExecGetAllNullSlot(estate, resultRelInfo);
     356                 :             :     else
     357                 :        1011 :         econtext->ecxt_newtuple = NULL; /* No references to NEW columns */
     358                 :             : 
     359                 :             :     /*
     360                 :             :      * Tell ExecProject whether or not the OLD/NEW rows actually exist.  This
     361                 :             :      * information is required to evaluate ReturningExpr nodes and also in
     362                 :             :      * ExecEvalSysVar() and ExecEvalWholeRowVar().
     363                 :             :      */
     364         [ +  + ]:        5745 :     if (oldSlot == NULL)
     365                 :        3147 :         projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL;
     366                 :             :     else
     367                 :        2598 :         projectReturning->pi_state.flags &= ~EEO_FLAG_OLD_IS_NULL;
     368                 :             : 
     369         [ +  + ]:        5745 :     if (newSlot == NULL)
     370                 :        1114 :         projectReturning->pi_state.flags |= EEO_FLAG_NEW_IS_NULL;
     371                 :             :     else
     372                 :        4631 :         projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL;
     373                 :             : 
     374                 :             :     /* Compute the RETURNING expressions */
     375                 :        5745 :     return ExecProject(projectReturning);
     376                 :             : }
     377                 :             : 
     378                 :             : /*
     379                 :             :  * ExecCheckTupleVisible -- verify tuple is visible
     380                 :             :  *
     381                 :             :  * It would not be consistent with guarantees of the higher isolation levels to
     382                 :             :  * proceed with avoiding insertion (taking speculative insertion's alternative
     383                 :             :  * path) on the basis of another tuple that is not visible to MVCC snapshot.
     384                 :             :  * Check for the need to raise a serialization failure, and do so as necessary.
     385                 :             :  */
     386                 :             : static void
     387                 :        2956 : ExecCheckTupleVisible(EState *estate,
     388                 :             :                       Relation rel,
     389                 :             :                       TupleTableSlot *slot)
     390                 :             : {
     391         [ +  + ]:        2956 :     if (!IsolationUsesXactSnapshot())
     392                 :        2914 :         return;
     393                 :             : 
     394         [ +  + ]:          42 :     if (!table_tuple_satisfies_snapshot(rel, slot, estate->es_snapshot))
     395                 :             :     {
     396                 :             :         Datum       xminDatum;
     397                 :             :         TransactionId xmin;
     398                 :             :         bool        isnull;
     399                 :             : 
     400                 :          30 :         xminDatum = slot_getsysattr(slot, MinTransactionIdAttributeNumber, &isnull);
     401                 :             :         Assert(!isnull);
     402                 :          30 :         xmin = DatumGetTransactionId(xminDatum);
     403                 :             : 
     404                 :             :         /*
     405                 :             :          * We should not raise a serialization failure if the conflict is
     406                 :             :          * against a tuple inserted by our own transaction, even if it's not
     407                 :             :          * visible to our snapshot.  (This would happen, for example, if
     408                 :             :          * conflicting keys are proposed for insertion in a single command.)
     409                 :             :          */
     410         [ +  + ]:          30 :         if (!TransactionIdIsCurrentTransactionId(xmin))
     411         [ +  - ]:          10 :             ereport(ERROR,
     412                 :             :                     (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
     413                 :             :                      errmsg("could not serialize access due to concurrent update")));
     414                 :             :     }
     415                 :             : }
     416                 :             : 
     417                 :             : /*
     418                 :             :  * ExecCheckTIDVisible -- convenience variant of ExecCheckTupleVisible()
     419                 :             :  */
     420                 :             : static void
     421                 :         139 : ExecCheckTIDVisible(EState *estate,
     422                 :             :                     ResultRelInfo *relinfo,
     423                 :             :                     ItemPointer tid,
     424                 :             :                     TupleTableSlot *tempSlot)
     425                 :             : {
     426                 :         139 :     Relation    rel = relinfo->ri_RelationDesc;
     427                 :             : 
     428                 :             :     /* Redundantly check isolation level */
     429         [ +  + ]:         139 :     if (!IsolationUsesXactSnapshot())
     430                 :         105 :         return;
     431                 :             : 
     432         [ -  + ]:          34 :     if (!table_tuple_fetch_row_version(rel, tid, SnapshotAny, tempSlot))
     433         [ #  # ]:           0 :         elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
     434                 :          34 :     ExecCheckTupleVisible(estate, rel, tempSlot);
     435                 :          24 :     ExecClearTuple(tempSlot);
     436                 :             : }
     437                 :             : 
     438                 :             : /*
     439                 :             :  * Initialize generated columns handling for a tuple
     440                 :             :  *
     441                 :             :  * This fills the resultRelInfo's ri_GeneratedExprsI/ri_NumGeneratedNeededI or
     442                 :             :  * ri_GeneratedExprsU/ri_NumGeneratedNeededU fields, depending on cmdtype.
     443                 :             :  * This is used only for stored generated columns.
     444                 :             :  *
     445                 :             :  * If cmdType == CMD_UPDATE, the ri_extraUpdatedCols field is filled too.
     446                 :             :  * This is used by both stored and virtual generated columns.
     447                 :             :  *
     448                 :             :  * Note: usually, a given query would need only one of ri_GeneratedExprsI and
     449                 :             :  * ri_GeneratedExprsU per result rel; but MERGE can need both, and so can
     450                 :             :  * cross-partition UPDATEs, since a partition might be the target of both
     451                 :             :  * UPDATE and INSERT actions.
     452                 :             :  */
     453                 :             : void
     454                 :       32038 : ExecInitGenerated(ResultRelInfo *resultRelInfo,
     455                 :             :                   EState *estate,
     456                 :             :                   CmdType cmdtype)
     457                 :             : {
     458                 :       32038 :     Relation    rel = resultRelInfo->ri_RelationDesc;
     459                 :       32038 :     TupleDesc   tupdesc = RelationGetDescr(rel);
     460                 :       32038 :     int         natts = tupdesc->natts;
     461                 :             :     ExprState **ri_GeneratedExprs;
     462                 :             :     int         ri_NumGeneratedNeeded;
     463                 :             :     Bitmapset  *updatedCols;
     464                 :             :     MemoryContext oldContext;
     465                 :             : 
     466                 :             :     /* Nothing to do if no generated columns */
     467   [ +  +  +  +  :       32038 :     if (!(tupdesc->constr && (tupdesc->constr->has_generated_stored || tupdesc->constr->has_generated_virtual)))
                   +  + ]
     468                 :       31120 :         return;
     469                 :             : 
     470                 :             :     /*
     471                 :             :      * In an UPDATE, we can skip computing any generated columns that do not
     472                 :             :      * depend on any UPDATE target column.  But if there is a BEFORE ROW
     473                 :             :      * UPDATE trigger, we cannot skip because the trigger might change more
     474                 :             :      * columns.
     475                 :             :      */
     476         [ +  + ]:         918 :     if (cmdtype == CMD_UPDATE &&
     477   [ +  +  -  + ]:         220 :         !(rel->trigdesc && rel->trigdesc->trig_update_before_row))
     478                 :         192 :         updatedCols = ExecGetUpdatedCols(resultRelInfo, estate);
     479                 :             :     else
     480                 :         726 :         updatedCols = NULL;
     481                 :             : 
     482                 :             :     /*
     483                 :             :      * Make sure these data structures are built in the per-query memory
     484                 :             :      * context so they'll survive throughout the query.
     485                 :             :      */
     486                 :         918 :     oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
     487                 :             : 
     488                 :         918 :     ri_GeneratedExprs = palloc0_array(ExprState *, natts);
     489                 :         918 :     ri_NumGeneratedNeeded = 0;
     490                 :             : 
     491         [ +  + ]:        3884 :     for (int i = 0; i < natts; i++)
     492                 :             :     {
     493                 :        2970 :         char        attgenerated = TupleDescAttr(tupdesc, i)->attgenerated;
     494                 :             : 
     495         [ +  + ]:        2970 :         if (attgenerated)
     496                 :             :         {
     497                 :             :             Expr       *expr;
     498                 :             : 
     499                 :             :             /* Fetch the GENERATED AS expression tree */
     500                 :         990 :             expr = (Expr *) build_column_default(rel, i + 1);
     501         [ -  + ]:         990 :             if (expr == NULL)
     502         [ #  # ]:           0 :                 elog(ERROR, "no generation expression found for column number %d of table \"%s\"",
     503                 :             :                      i + 1, RelationGetRelationName(rel));
     504                 :             : 
     505                 :             :             /*
     506                 :             :              * If it's an update with a known set of update target columns,
     507                 :             :              * see if we can skip the computation.
     508                 :             :              */
     509         [ +  + ]:         990 :             if (updatedCols)
     510                 :             :             {
     511                 :         208 :                 Bitmapset  *attrs_used = NULL;
     512                 :             : 
     513                 :         208 :                 pull_varattnos((Node *) expr, 1, &attrs_used);
     514                 :             : 
     515         [ +  + ]:         208 :                 if (!bms_overlap(updatedCols, attrs_used))
     516                 :          21 :                     continue;   /* need not update this column */
     517                 :             :             }
     518                 :             : 
     519                 :             :             /* No luck, so prepare the expression for execution */
     520         [ +  + ]:         969 :             if (attgenerated == ATTRIBUTE_GENERATED_STORED)
     521                 :             :             {
     522                 :         876 :                 ri_GeneratedExprs[i] = ExecPrepareExpr(expr, estate);
     523                 :         872 :                 ri_NumGeneratedNeeded++;
     524                 :             :             }
     525                 :             : 
     526                 :             :             /* If UPDATE, mark column in resultRelInfo->ri_extraUpdatedCols */
     527         [ +  + ]:         965 :             if (cmdtype == CMD_UPDATE)
     528                 :         219 :                 resultRelInfo->ri_extraUpdatedCols =
     529                 :         219 :                     bms_add_member(resultRelInfo->ri_extraUpdatedCols,
     530                 :             :                                    i + 1 - FirstLowInvalidHeapAttributeNumber);
     531                 :             :         }
     532                 :             :     }
     533                 :             : 
     534         [ +  + ]:         914 :     if (ri_NumGeneratedNeeded == 0)
     535                 :             :     {
     536                 :             :         /* didn't need it after all */
     537                 :          53 :         pfree(ri_GeneratedExprs);
     538                 :          53 :         ri_GeneratedExprs = NULL;
     539                 :             :     }
     540                 :             : 
     541                 :             :     /* Save in appropriate set of fields */
     542         [ +  + ]:         914 :     if (cmdtype == CMD_UPDATE)
     543                 :             :     {
     544                 :             :         /* Don't call twice */
     545                 :             :         Assert(resultRelInfo->ri_GeneratedExprsU == NULL);
     546                 :             : 
     547                 :         220 :         resultRelInfo->ri_GeneratedExprsU = ri_GeneratedExprs;
     548                 :         220 :         resultRelInfo->ri_NumGeneratedNeededU = ri_NumGeneratedNeeded;
     549                 :             : 
     550                 :         220 :         resultRelInfo->ri_extraUpdatedCols_valid = true;
     551                 :             :     }
     552                 :             :     else
     553                 :             :     {
     554                 :             :         /* Don't call twice */
     555                 :             :         Assert(resultRelInfo->ri_GeneratedExprsI == NULL);
     556                 :             : 
     557                 :         694 :         resultRelInfo->ri_GeneratedExprsI = ri_GeneratedExprs;
     558                 :         694 :         resultRelInfo->ri_NumGeneratedNeededI = ri_NumGeneratedNeeded;
     559                 :             :     }
     560                 :             : 
     561                 :         914 :     MemoryContextSwitchTo(oldContext);
     562                 :             : }
     563                 :             : 
     564                 :             : /*
     565                 :             :  * Compute stored generated columns for a tuple
     566                 :             :  */
     567                 :             : void
     568                 :        1249 : ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo,
     569                 :             :                            EState *estate, TupleTableSlot *slot,
     570                 :             :                            CmdType cmdtype)
     571                 :             : {
     572                 :        1249 :     Relation    rel = resultRelInfo->ri_RelationDesc;
     573                 :        1249 :     TupleDesc   tupdesc = RelationGetDescr(rel);
     574                 :        1249 :     int         natts = tupdesc->natts;
     575         [ +  + ]:        1249 :     ExprContext *econtext = GetPerTupleExprContext(estate);
     576                 :             :     ExprState **ri_GeneratedExprs;
     577                 :             :     MemoryContext oldContext;
     578                 :             :     Datum      *values;
     579                 :             :     bool       *nulls;
     580                 :             : 
     581                 :             :     /* We should not be called unless this is true */
     582                 :             :     Assert(tupdesc->constr && tupdesc->constr->has_generated_stored);
     583                 :             : 
     584                 :             :     /*
     585                 :             :      * Initialize the expressions if we didn't already, and check whether we
     586                 :             :      * can exit early because nothing needs to be computed.
     587                 :             :      */
     588         [ +  + ]:        1249 :     if (cmdtype == CMD_UPDATE)
     589                 :             :     {
     590         [ +  + ]:         208 :         if (resultRelInfo->ri_GeneratedExprsU == NULL)
     591                 :         167 :             ExecInitGenerated(resultRelInfo, estate, cmdtype);
     592         [ +  + ]:         208 :         if (resultRelInfo->ri_NumGeneratedNeededU == 0)
     593                 :          17 :             return;
     594                 :         191 :         ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsU;
     595                 :             :     }
     596                 :             :     else
     597                 :             :     {
     598         [ +  + ]:        1041 :         if (resultRelInfo->ri_GeneratedExprsI == NULL)
     599                 :         698 :             ExecInitGenerated(resultRelInfo, estate, cmdtype);
     600                 :             :         /* Early exit is impossible given the prior Assert */
     601                 :             :         Assert(resultRelInfo->ri_NumGeneratedNeededI > 0);
     602                 :        1037 :         ri_GeneratedExprs = resultRelInfo->ri_GeneratedExprsI;
     603                 :             :     }
     604                 :             : 
     605         [ +  - ]:        1228 :     oldContext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
     606                 :             : 
     607                 :        1228 :     values = palloc_array(Datum, natts);
     608                 :        1228 :     nulls = palloc_array(bool, natts);
     609                 :             : 
     610                 :        1228 :     slot_getallattrs(slot);
     611                 :        1228 :     memcpy(nulls, slot->tts_isnull, sizeof(*nulls) * natts);
     612                 :             : 
     613         [ +  + ]:        5215 :     for (int i = 0; i < natts; i++)
     614                 :             :     {
     615                 :        4003 :         CompactAttribute *attr = TupleDescCompactAttr(tupdesc, i);
     616                 :             : 
     617         [ +  + ]:        4003 :         if (ri_GeneratedExprs[i])
     618                 :             :         {
     619                 :             :             Datum       val;
     620                 :             :             bool        isnull;
     621                 :             : 
     622                 :             :             Assert(TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED);
     623                 :             : 
     624                 :        1241 :             econtext->ecxt_scantuple = slot;
     625                 :             : 
     626                 :        1241 :             val = ExecEvalExpr(ri_GeneratedExprs[i], econtext, &isnull);
     627                 :             : 
     628                 :             :             /*
     629                 :             :              * We must make a copy of val as we have no guarantees about where
     630                 :             :              * memory for a pass-by-reference Datum is located.
     631                 :             :              */
     632         [ +  + ]:        1225 :             if (!isnull)
     633                 :        1169 :                 val = datumCopy(val, attr->attbyval, attr->attlen);
     634                 :             : 
     635                 :        1225 :             values[i] = val;
     636                 :        1225 :             nulls[i] = isnull;
     637                 :             :         }
     638                 :             :         else
     639                 :             :         {
     640         [ +  + ]:        2762 :             if (!nulls[i])
     641                 :        2442 :                 values[i] = datumCopy(slot->tts_values[i], attr->attbyval, attr->attlen);
     642                 :             :         }
     643                 :             :     }
     644                 :             : 
     645                 :        1212 :     ExecClearTuple(slot);
     646                 :        1212 :     memcpy(slot->tts_values, values, sizeof(*values) * natts);
     647                 :        1212 :     memcpy(slot->tts_isnull, nulls, sizeof(*nulls) * natts);
     648                 :        1212 :     ExecStoreVirtualTuple(slot);
     649                 :        1212 :     ExecMaterializeSlot(slot);
     650                 :             : 
     651                 :        1212 :     MemoryContextSwitchTo(oldContext);
     652                 :             : }
     653                 :             : 
     654                 :             : /*
     655                 :             :  * ExecInitInsertProjection
     656                 :             :  *      Do one-time initialization of projection data for INSERT tuples.
     657                 :             :  *
     658                 :             :  * INSERT queries may need a projection to filter out junk attrs in the tlist.
     659                 :             :  *
     660                 :             :  * This is also a convenient place to verify that the
     661                 :             :  * output of an INSERT matches the target table.
     662                 :             :  */
     663                 :             : static void
     664                 :       57020 : ExecInitInsertProjection(ModifyTableState *mtstate,
     665                 :             :                          ResultRelInfo *resultRelInfo)
     666                 :             : {
     667                 :       57020 :     ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
     668                 :       57020 :     Plan       *subplan = outerPlan(node);
     669                 :       57020 :     EState     *estate = mtstate->ps.state;
     670                 :       57020 :     List       *insertTargetList = NIL;
     671                 :       57020 :     bool        need_projection = false;
     672                 :             :     ListCell   *l;
     673                 :             : 
     674                 :             :     /* Extract non-junk columns of the subplan's result tlist. */
     675   [ +  +  +  +  :      176577 :     foreach(l, subplan->targetlist)
                   +  + ]
     676                 :             :     {
     677                 :      119557 :         TargetEntry *tle = (TargetEntry *) lfirst(l);
     678                 :             : 
     679         [ +  - ]:      119557 :         if (!tle->resjunk)
     680                 :      119557 :             insertTargetList = lappend(insertTargetList, tle);
     681                 :             :         else
     682                 :           0 :             need_projection = true;
     683                 :             :     }
     684                 :             : 
     685                 :             :     /*
     686                 :             :      * The junk-free list must produce a tuple suitable for the result
     687                 :             :      * relation.
     688                 :             :      */
     689                 :       57020 :     ExecCheckPlanOutput(resultRelInfo->ri_RelationDesc, insertTargetList);
     690                 :             : 
     691                 :             :     /* We'll need a slot matching the table's format. */
     692                 :       57020 :     resultRelInfo->ri_newTupleSlot =
     693                 :       57020 :         table_slot_create(resultRelInfo->ri_RelationDesc,
     694                 :             :                           &estate->es_tupleTable);
     695                 :             : 
     696                 :             :     /* Build ProjectionInfo if needed (it probably isn't). */
     697         [ -  + ]:       57020 :     if (need_projection)
     698                 :             :     {
     699                 :           0 :         TupleDesc   relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
     700                 :             : 
     701                 :             :         /* need an expression context to do the projection */
     702         [ #  # ]:           0 :         if (mtstate->ps.ps_ExprContext == NULL)
     703                 :           0 :             ExecAssignExprContext(estate, &mtstate->ps);
     704                 :             : 
     705                 :           0 :         resultRelInfo->ri_projectNew =
     706                 :           0 :             ExecBuildProjectionInfo(insertTargetList,
     707                 :             :                                     mtstate->ps.ps_ExprContext,
     708                 :             :                                     resultRelInfo->ri_newTupleSlot,
     709                 :             :                                     &mtstate->ps,
     710                 :             :                                     relDesc);
     711                 :             :     }
     712                 :             : 
     713                 :       57020 :     resultRelInfo->ri_projectNewInfoValid = true;
     714                 :       57020 : }
     715                 :             : 
     716                 :             : /*
     717                 :             :  * ExecInitUpdateProjection
     718                 :             :  *      Do one-time initialization of projection data for UPDATE tuples.
     719                 :             :  *
     720                 :             :  * UPDATE always needs a projection, because (1) there's always some junk
     721                 :             :  * attrs, and (2) we may need to merge values of not-updated columns from
     722                 :             :  * the old tuple into the final tuple.  In UPDATE, the tuple arriving from
     723                 :             :  * the subplan contains only new values for the changed columns, plus row
     724                 :             :  * identity info in the junk attrs.
     725                 :             :  *
     726                 :             :  * This is "one-time" for any given result rel, but we might touch more than
     727                 :             :  * one result rel in the course of an inherited UPDATE, and each one needs
     728                 :             :  * its own projection due to possible column order variation.
     729                 :             :  *
     730                 :             :  * This is also a convenient place to verify that the output of an UPDATE
     731                 :             :  * matches the target table (ExecBuildUpdateProjection does that).
     732                 :             :  */
     733                 :             : static void
     734                 :        8794 : ExecInitUpdateProjection(ModifyTableState *mtstate,
     735                 :             :                          ResultRelInfo *resultRelInfo)
     736                 :             : {
     737                 :        8794 :     ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
     738                 :        8794 :     Plan       *subplan = outerPlan(node);
     739                 :        8794 :     EState     *estate = mtstate->ps.state;
     740                 :        8794 :     TupleDesc   relDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
     741                 :             :     int         whichrel;
     742                 :             :     List       *updateColnos;
     743                 :             : 
     744                 :             :     /*
     745                 :             :      * Usually, mt_lastResultIndex matches the target rel.  If it happens not
     746                 :             :      * to, we can get the index the hard way with an integer division.
     747                 :             :      */
     748                 :        8794 :     whichrel = mtstate->mt_lastResultIndex;
     749         [ -  + ]:        8794 :     if (resultRelInfo != mtstate->resultRelInfo + whichrel)
     750                 :             :     {
     751                 :           0 :         whichrel = resultRelInfo - mtstate->resultRelInfo;
     752                 :             :         Assert(whichrel >= 0 && whichrel < mtstate->mt_nrels);
     753                 :             :     }
     754                 :             : 
     755                 :        8794 :     updateColnos = (List *) list_nth(mtstate->mt_updateColnosLists, whichrel);
     756                 :             : 
     757                 :             :     /*
     758                 :             :      * For UPDATE, we use the old tuple to fill up missing values in the tuple
     759                 :             :      * produced by the subplan to get the new tuple.  We need two slots, both
     760                 :             :      * matching the table's desired format.
     761                 :             :      */
     762                 :        8794 :     resultRelInfo->ri_oldTupleSlot =
     763                 :        8794 :         table_slot_create(resultRelInfo->ri_RelationDesc,
     764                 :             :                           &estate->es_tupleTable);
     765                 :        8794 :     resultRelInfo->ri_newTupleSlot =
     766                 :        8794 :         table_slot_create(resultRelInfo->ri_RelationDesc,
     767                 :             :                           &estate->es_tupleTable);
     768                 :             : 
     769                 :             :     /* need an expression context to do the projection */
     770         [ +  + ]:        8794 :     if (mtstate->ps.ps_ExprContext == NULL)
     771                 :        7442 :         ExecAssignExprContext(estate, &mtstate->ps);
     772                 :             : 
     773                 :        8794 :     resultRelInfo->ri_projectNew =
     774                 :        8794 :         ExecBuildUpdateProjection(subplan->targetlist,
     775                 :             :                                   false,    /* subplan did the evaluation */
     776                 :             :                                   updateColnos,
     777                 :             :                                   relDesc,
     778                 :             :                                   mtstate->ps.ps_ExprContext,
     779                 :             :                                   resultRelInfo->ri_newTupleSlot,
     780                 :             :                                   &mtstate->ps);
     781                 :             : 
     782                 :        8794 :     resultRelInfo->ri_projectNewInfoValid = true;
     783                 :        8794 : }
     784                 :             : 
     785                 :             : /*
     786                 :             :  * ExecGetInsertNewTuple
     787                 :             :  *      This prepares a "new" tuple ready to be inserted into given result
     788                 :             :  *      relation, by removing any junk columns of the plan's output tuple
     789                 :             :  *      and (if necessary) coercing the tuple to the right tuple format.
     790                 :             :  */
     791                 :             : static TupleTableSlot *
     792                 :     8077585 : ExecGetInsertNewTuple(ResultRelInfo *relinfo,
     793                 :             :                       TupleTableSlot *planSlot)
     794                 :             : {
     795                 :     8077585 :     ProjectionInfo *newProj = relinfo->ri_projectNew;
     796                 :             :     ExprContext *econtext;
     797                 :             : 
     798                 :             :     /*
     799                 :             :      * If there's no projection to be done, just make sure the slot is of the
     800                 :             :      * right type for the target rel.  If the planSlot is the right type we
     801                 :             :      * can use it as-is, else copy the data into ri_newTupleSlot.
     802                 :             :      */
     803         [ +  - ]:     8077585 :     if (newProj == NULL)
     804                 :             :     {
     805         [ +  + ]:     8077585 :         if (relinfo->ri_newTupleSlot->tts_ops != planSlot->tts_ops)
     806                 :             :         {
     807                 :     7564492 :             ExecCopySlot(relinfo->ri_newTupleSlot, planSlot);
     808                 :     7564492 :             return relinfo->ri_newTupleSlot;
     809                 :             :         }
     810                 :             :         else
     811                 :      513093 :             return planSlot;
     812                 :             :     }
     813                 :             : 
     814                 :             :     /*
     815                 :             :      * Else project; since the projection output slot is ri_newTupleSlot, this
     816                 :             :      * will also fix any slot-type problem.
     817                 :             :      *
     818                 :             :      * Note: currently, this is dead code, because INSERT cases don't receive
     819                 :             :      * any junk columns so there's never a projection to be done.
     820                 :             :      */
     821                 :           0 :     econtext = newProj->pi_exprContext;
     822                 :           0 :     econtext->ecxt_outertuple = planSlot;
     823                 :           0 :     return ExecProject(newProj);
     824                 :             : }
     825                 :             : 
     826                 :             : /*
     827                 :             :  * ExecGetUpdateNewTuple
     828                 :             :  *      This prepares a "new" tuple by combining an UPDATE subplan's output
     829                 :             :  *      tuple (which contains values of changed columns) with unchanged
     830                 :             :  *      columns taken from the old tuple.
     831                 :             :  *
     832                 :             :  * The subplan tuple might also contain junk columns, which are ignored.
     833                 :             :  * Note that the projection also ensures we have a slot of the right type.
     834                 :             :  */
     835                 :             : TupleTableSlot *
     836                 :     2209510 : ExecGetUpdateNewTuple(ResultRelInfo *relinfo,
     837                 :             :                       TupleTableSlot *planSlot,
     838                 :             :                       TupleTableSlot *oldSlot)
     839                 :             : {
     840                 :     2209510 :     ProjectionInfo *newProj = relinfo->ri_projectNew;
     841                 :             :     ExprContext *econtext;
     842                 :             : 
     843                 :             :     /* Use a few extra Asserts to protect against outside callers */
     844                 :             :     Assert(relinfo->ri_projectNewInfoValid);
     845                 :             :     Assert(planSlot != NULL && !TTS_EMPTY(planSlot));
     846                 :             :     Assert(oldSlot != NULL && !TTS_EMPTY(oldSlot));
     847                 :             : 
     848                 :     2209510 :     econtext = newProj->pi_exprContext;
     849                 :     2209510 :     econtext->ecxt_outertuple = planSlot;
     850                 :     2209510 :     econtext->ecxt_scantuple = oldSlot;
     851                 :     2209510 :     return ExecProject(newProj);
     852                 :             : }
     853                 :             : 
     854                 :             : /* ----------------------------------------------------------------
     855                 :             :  *      ExecInsert
     856                 :             :  *
     857                 :             :  *      For INSERT, we have to insert the tuple into the target relation
     858                 :             :  *      (or partition thereof) and insert appropriate tuples into the index
     859                 :             :  *      relations.
     860                 :             :  *
     861                 :             :  *      slot contains the new tuple value to be stored.
     862                 :             :  *
     863                 :             :  *      Returns RETURNING result if any, otherwise NULL.
     864                 :             :  *      *inserted_tuple is the tuple that's effectively inserted;
     865                 :             :  *      *insert_destrel is the relation where it was inserted.
     866                 :             :  *      These are only set on success.
     867                 :             :  *
     868                 :             :  *      This may change the currently active tuple conversion map in
     869                 :             :  *      mtstate->mt_transition_capture, so the callers must take care to
     870                 :             :  *      save the previous value to avoid losing track of it.
     871                 :             :  * ----------------------------------------------------------------
     872                 :             :  */
     873                 :             : static TupleTableSlot *
     874                 :     8080694 : ExecInsert(ModifyTableContext *context,
     875                 :             :            ResultRelInfo *resultRelInfo,
     876                 :             :            TupleTableSlot *slot,
     877                 :             :            bool canSetTag,
     878                 :             :            TupleTableSlot **inserted_tuple,
     879                 :             :            ResultRelInfo **insert_destrel)
     880                 :             : {
     881                 :     8080694 :     ModifyTableState *mtstate = context->mtstate;
     882                 :     8080694 :     EState     *estate = context->estate;
     883                 :             :     Relation    resultRelationDesc;
     884                 :     8080694 :     List       *recheckIndexes = NIL;
     885                 :     8080694 :     TupleTableSlot *planSlot = context->planSlot;
     886                 :     8080694 :     TupleTableSlot *result = NULL;
     887                 :             :     TransitionCaptureState *ar_insert_trig_tcs;
     888                 :     8080694 :     ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
     889                 :     8080694 :     OnConflictAction onconflict = node->onConflictAction;
     890                 :     8080694 :     PartitionTupleRouting *proute = mtstate->mt_partition_tuple_routing;
     891                 :             :     MemoryContext oldContext;
     892                 :             : 
     893                 :             :     /*
     894                 :             :      * If the input result relation is a partitioned table, find the leaf
     895                 :             :      * partition to insert the tuple into.
     896                 :             :      */
     897         [ +  + ]:     8080694 :     if (proute)
     898                 :             :     {
     899                 :             :         ResultRelInfo *partRelInfo;
     900                 :             : 
     901                 :      481064 :         slot = ExecPrepareTupleRouting(mtstate, estate, proute,
     902                 :             :                                        resultRelInfo, slot,
     903                 :             :                                        &partRelInfo);
     904                 :      480920 :         resultRelInfo = partRelInfo;
     905                 :             :     }
     906                 :             : 
     907                 :     8080550 :     ExecMaterializeSlot(slot);
     908                 :             : 
     909                 :     8080550 :     resultRelationDesc = resultRelInfo->ri_RelationDesc;
     910                 :             : 
     911                 :             :     /*
     912                 :             :      * Open the table's indexes, if we have not done so already, so that we
     913                 :             :      * can add new index entries for the inserted tuple.
     914                 :             :      */
     915         [ +  + ]:     8080550 :     if (resultRelationDesc->rd_rel->relhasindex &&
     916         [ +  + ]:     2548039 :         resultRelInfo->ri_IndexRelationDescs == NULL)
     917                 :       22417 :         ExecOpenIndices(resultRelInfo, onconflict != ONCONFLICT_NONE);
     918                 :             : 
     919                 :             :     /*
     920                 :             :      * BEFORE ROW INSERT Triggers.
     921                 :             :      *
     922                 :             :      * Note: We fire BEFORE ROW TRIGGERS for every attempted insertion in an
     923                 :             :      * INSERT ... ON CONFLICT statement.  We cannot check for constraint
     924                 :             :      * violations before firing these triggers, because they can change the
     925                 :             :      * values to insert.  Also, they can run arbitrary user-defined code with
     926                 :             :      * side-effects that we can't cancel by just not inserting the tuple.
     927                 :             :      */
     928         [ +  + ]:     8080550 :     if (resultRelInfo->ri_TrigDesc &&
     929         [ +  + ]:      454712 :         resultRelInfo->ri_TrigDesc->trig_insert_before_row)
     930                 :             :     {
     931                 :             :         /* Flush any pending inserts, so rows are visible to the triggers */
     932         [ +  + ]:        1434 :         if (estate->es_insert_pending_result_relations != NIL)
     933                 :           3 :             ExecPendingInserts(estate);
     934                 :             : 
     935         [ +  + ]:        1434 :         if (!ExecBRInsertTriggers(estate, resultRelInfo, slot))
     936                 :         131 :             return NULL;        /* "do nothing" */
     937                 :             :     }
     938                 :             : 
     939                 :             :     /* INSTEAD OF ROW INSERT Triggers */
     940         [ +  + ]:     8080357 :     if (resultRelInfo->ri_TrigDesc &&
     941         [ +  + ]:      454519 :         resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
     942                 :             :     {
     943         [ +  + ]:         111 :         if (!ExecIRInsertTriggers(estate, resultRelInfo, slot))
     944                 :           4 :             return NULL;        /* "do nothing" */
     945                 :             :     }
     946         [ +  + ]:     8080246 :     else if (resultRelInfo->ri_FdwRoutine)
     947                 :             :     {
     948                 :             :         /*
     949                 :             :          * GENERATED expressions might reference the tableoid column, so
     950                 :             :          * (re-)initialize tts_tableOid before evaluating them.
     951                 :             :          */
     952                 :        1010 :         slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
     953                 :             : 
     954                 :             :         /*
     955                 :             :          * Compute stored generated columns
     956                 :             :          */
     957         [ +  + ]:        1010 :         if (resultRelationDesc->rd_att->constr &&
     958         [ +  + ]:         179 :             resultRelationDesc->rd_att->constr->has_generated_stored)
     959                 :           4 :             ExecComputeStoredGenerated(resultRelInfo, estate, slot,
     960                 :             :                                        CMD_INSERT);
     961                 :             : 
     962                 :             :         /*
     963                 :             :          * If the FDW supports batching, and batching is requested, accumulate
     964                 :             :          * rows and insert them in batches. Otherwise use the per-row inserts.
     965                 :             :          */
     966         [ +  + ]:        1010 :         if (resultRelInfo->ri_BatchSize > 1)
     967                 :             :         {
     968                 :         145 :             bool        flushed = false;
     969                 :             : 
     970                 :             :             /*
     971                 :             :              * When we've reached the desired batch size, perform the
     972                 :             :              * insertion.
     973                 :             :              */
     974         [ +  + ]:         145 :             if (resultRelInfo->ri_NumSlots == resultRelInfo->ri_BatchSize)
     975                 :             :             {
     976                 :          10 :                 ExecBatchInsert(mtstate, resultRelInfo,
     977                 :             :                                 resultRelInfo->ri_Slots,
     978                 :             :                                 resultRelInfo->ri_PlanSlots,
     979                 :             :                                 resultRelInfo->ri_NumSlots,
     980                 :             :                                 estate, canSetTag);
     981                 :          10 :                 flushed = true;
     982                 :             :             }
     983                 :             : 
     984                 :         145 :             oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
     985                 :             : 
     986         [ +  + ]:         145 :             if (resultRelInfo->ri_Slots == NULL)
     987                 :             :             {
     988                 :          15 :                 resultRelInfo->ri_Slots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
     989                 :          15 :                 resultRelInfo->ri_PlanSlots = palloc_array(TupleTableSlot *, resultRelInfo->ri_BatchSize);
     990                 :             :             }
     991                 :             : 
     992                 :             :             /*
     993                 :             :              * Initialize the batch slots. We don't know how many slots will
     994                 :             :              * be needed, so we initialize them as the batch grows, and we
     995                 :             :              * keep them across batches. To mitigate an inefficiency in how
     996                 :             :              * resource owner handles objects with many references (as with
     997                 :             :              * many slots all referencing the same tuple descriptor) we copy
     998                 :             :              * the appropriate tuple descriptor for each slot.
     999                 :             :              */
    1000         [ +  + ]:         145 :             if (resultRelInfo->ri_NumSlots >= resultRelInfo->ri_NumSlotsInitialized)
    1001                 :             :             {
    1002                 :          72 :                 TupleDesc   tdesc = CreateTupleDescCopy(slot->tts_tupleDescriptor);
    1003                 :             :                 TupleDesc   plan_tdesc =
    1004                 :          72 :                     CreateTupleDescCopy(planSlot->tts_tupleDescriptor);
    1005                 :             : 
    1006                 :         144 :                 resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots] =
    1007                 :          72 :                     MakeSingleTupleTableSlot(tdesc, slot->tts_ops);
    1008                 :             : 
    1009                 :         144 :                 resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots] =
    1010                 :          72 :                     MakeSingleTupleTableSlot(plan_tdesc, planSlot->tts_ops);
    1011                 :             : 
    1012                 :             :                 /* remember how many batch slots we initialized */
    1013                 :          72 :                 resultRelInfo->ri_NumSlotsInitialized++;
    1014                 :             :             }
    1015                 :             : 
    1016                 :         145 :             ExecCopySlot(resultRelInfo->ri_Slots[resultRelInfo->ri_NumSlots],
    1017                 :             :                          slot);
    1018                 :             : 
    1019                 :         145 :             ExecCopySlot(resultRelInfo->ri_PlanSlots[resultRelInfo->ri_NumSlots],
    1020                 :             :                          planSlot);
    1021                 :             : 
    1022                 :             :             /*
    1023                 :             :              * If these are the first tuples stored in the buffers, add the
    1024                 :             :              * target rel and the mtstate to the
    1025                 :             :              * es_insert_pending_result_relations and
    1026                 :             :              * es_insert_pending_modifytables lists respectively, except in
    1027                 :             :              * the case where flushing was done above, in which case they
    1028                 :             :              * would already have been added to the lists, so no need to do
    1029                 :             :              * this.
    1030                 :             :              */
    1031   [ +  +  +  + ]:         145 :             if (resultRelInfo->ri_NumSlots == 0 && !flushed)
    1032                 :             :             {
    1033                 :             :                 Assert(!list_member_ptr(estate->es_insert_pending_result_relations,
    1034                 :             :                                         resultRelInfo));
    1035                 :          19 :                 estate->es_insert_pending_result_relations =
    1036                 :          19 :                     lappend(estate->es_insert_pending_result_relations,
    1037                 :             :                             resultRelInfo);
    1038                 :          19 :                 estate->es_insert_pending_modifytables =
    1039                 :          19 :                     lappend(estate->es_insert_pending_modifytables, mtstate);
    1040                 :             :             }
    1041                 :             :             Assert(list_member_ptr(estate->es_insert_pending_result_relations,
    1042                 :             :                                    resultRelInfo));
    1043                 :             : 
    1044                 :         145 :             resultRelInfo->ri_NumSlots++;
    1045                 :             : 
    1046                 :         145 :             MemoryContextSwitchTo(oldContext);
    1047                 :             : 
    1048                 :         145 :             return NULL;
    1049                 :             :         }
    1050                 :             : 
    1051                 :             :         /*
    1052                 :             :          * insert into foreign table: let the FDW do it
    1053                 :             :          */
    1054                 :         865 :         slot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
    1055                 :             :                                                                resultRelInfo,
    1056                 :             :                                                                slot,
    1057                 :             :                                                                planSlot);
    1058                 :             : 
    1059         [ +  + ]:         862 :         if (slot == NULL)       /* "do nothing" */
    1060                 :           2 :             return NULL;
    1061                 :             : 
    1062                 :             :         /*
    1063                 :             :          * AFTER ROW Triggers or RETURNING expressions might reference the
    1064                 :             :          * tableoid column, so (re-)initialize tts_tableOid before evaluating
    1065                 :             :          * them.  (This covers the case where the FDW replaced the slot.)
    1066                 :             :          */
    1067                 :         860 :         slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
    1068                 :             :     }
    1069                 :             :     else
    1070                 :             :     {
    1071                 :             :         WCOKind     wco_kind;
    1072                 :             : 
    1073                 :             :         /*
    1074                 :             :          * Constraints and GENERATED expressions might reference the tableoid
    1075                 :             :          * column, so (re-)initialize tts_tableOid before evaluating them.
    1076                 :             :          */
    1077                 :     8079236 :         slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
    1078                 :             : 
    1079                 :             :         /*
    1080                 :             :          * Compute stored generated columns
    1081                 :             :          */
    1082         [ +  + ]:     8079236 :         if (resultRelationDesc->rd_att->constr &&
    1083         [ +  + ]:     2542716 :             resultRelationDesc->rd_att->constr->has_generated_stored)
    1084                 :        1012 :             ExecComputeStoredGenerated(resultRelInfo, estate, slot,
    1085                 :             :                                        CMD_INSERT);
    1086                 :             : 
    1087                 :             :         /*
    1088                 :             :          * Check any RLS WITH CHECK policies.
    1089                 :             :          *
    1090                 :             :          * Normally we should check INSERT policies. But if the insert is the
    1091                 :             :          * result of a partition key update that moved the tuple to a new
    1092                 :             :          * partition, we should instead check UPDATE policies, because we are
    1093                 :             :          * executing policies defined on the target table, and not those
    1094                 :             :          * defined on the child partitions.
    1095                 :             :          *
    1096                 :             :          * If we're running MERGE, we refer to the action that we're executing
    1097                 :             :          * to know if we're doing an INSERT or UPDATE to a partition table.
    1098                 :             :          */
    1099         [ +  + ]:     8079216 :         if (mtstate->operation == CMD_UPDATE)
    1100                 :         549 :             wco_kind = WCO_RLS_UPDATE_CHECK;
    1101         [ +  + ]:     8078667 :         else if (mtstate->operation == CMD_MERGE)
    1102                 :        1181 :             wco_kind = (mtstate->mt_merge_action->mas_action->commandType == CMD_UPDATE) ?
    1103         [ +  + ]:        1181 :                 WCO_RLS_UPDATE_CHECK : WCO_RLS_INSERT_CHECK;
    1104                 :             :         else
    1105                 :     8077486 :             wco_kind = WCO_RLS_INSERT_CHECK;
    1106                 :             : 
    1107                 :             :         /*
    1108                 :             :          * ExecWithCheckOptions() will skip any WCOs which are not of the kind
    1109                 :             :          * we are looking for at this point.
    1110                 :             :          */
    1111         [ +  + ]:     8079216 :         if (resultRelInfo->ri_WithCheckOptions != NIL)
    1112                 :         538 :             ExecWithCheckOptions(wco_kind, resultRelInfo, slot, estate);
    1113                 :             : 
    1114                 :             :         /*
    1115                 :             :          * Check the constraints of the tuple.
    1116                 :             :          */
    1117         [ +  + ]:     8079080 :         if (resultRelationDesc->rd_att->constr)
    1118                 :     2542624 :             ExecConstraints(resultRelInfo, slot, estate);
    1119                 :             : 
    1120                 :             :         /*
    1121                 :             :          * Also check the tuple against the partition constraint, if there is
    1122                 :             :          * one; except that if we got here via tuple-routing, we don't need to
    1123                 :             :          * if there's no BR trigger defined on the partition.
    1124                 :             :          */
    1125         [ +  + ]:     8078563 :         if (resultRelationDesc->rd_rel->relispartition &&
    1126         [ +  + ]:      482418 :             (resultRelInfo->ri_RootResultRelInfo == NULL ||
    1127         [ +  + ]:      480560 :              (resultRelInfo->ri_TrigDesc &&
    1128         [ +  + ]:        1113 :               resultRelInfo->ri_TrigDesc->trig_insert_before_row)))
    1129                 :        1996 :             ExecPartitionCheck(resultRelInfo, slot, estate, true);
    1130                 :             : 
    1131   [ +  +  +  - ]:     8078451 :         if (onconflict != ONCONFLICT_NONE && resultRelInfo->ri_NumIndices > 0)
    1132                 :        2216 :         {
    1133                 :             :             /* Perform a speculative insertion. */
    1134                 :             :             uint32      specToken;
    1135                 :             :             ItemPointerData conflictTid;
    1136                 :             :             ItemPointerData invalidItemPtr;
    1137                 :             :             bool        specConflict;
    1138                 :             :             List       *arbiterIndexes;
    1139                 :             : 
    1140                 :        5313 :             ItemPointerSetInvalid(&invalidItemPtr);
    1141                 :        5313 :             arbiterIndexes = resultRelInfo->ri_onConflictArbiterIndexes;
    1142                 :             : 
    1143                 :             :             /*
    1144                 :             :              * Do a non-conclusive check for conflicts first.
    1145                 :             :              *
    1146                 :             :              * We're not holding any locks yet, so this doesn't guarantee that
    1147                 :             :              * the later insert won't conflict.  But it avoids leaving behind
    1148                 :             :              * a lot of canceled speculative insertions, if you run a lot of
    1149                 :             :              * INSERT ON CONFLICT statements that do conflict.
    1150                 :             :              *
    1151                 :             :              * We loop back here if we find a conflict below, either during
    1152                 :             :              * the pre-check, or when we re-check after inserting the tuple
    1153                 :             :              * speculatively.  Better allow interrupts in case some bug makes
    1154                 :             :              * this an infinite loop.
    1155                 :             :              */
    1156                 :          14 :     vlock:
    1157         [ -  + ]:        5327 :             CHECK_FOR_INTERRUPTS();
    1158                 :        5327 :             specConflict = false;
    1159         [ +  + ]:        5327 :             if (!ExecCheckIndexConstraints(resultRelInfo, slot, estate,
    1160                 :             :                                            &conflictTid, &invalidItemPtr,
    1161                 :             :                                            arbiterIndexes))
    1162                 :             :             {
    1163                 :             :                 /* committed conflict tuple found */
    1164         [ +  + ]:        3092 :                 if (onconflict == ONCONFLICT_UPDATE)
    1165                 :             :                 {
    1166                 :             :                     /*
    1167                 :             :                      * In case of ON CONFLICT DO UPDATE, execute the UPDATE
    1168                 :             :                      * part.  Be prepared to retry if the UPDATE fails because
    1169                 :             :                      * of another concurrent UPDATE/DELETE to the conflict
    1170                 :             :                      * tuple.
    1171                 :             :                      */
    1172                 :        2761 :                     TupleTableSlot *returning = NULL;
    1173                 :             : 
    1174         [ +  + ]:        2761 :                     if (ExecOnConflictUpdate(context, resultRelInfo,
    1175                 :             :                                              &conflictTid, slot, canSetTag,
    1176                 :             :                                              &returning))
    1177                 :             :                     {
    1178         [ -  + ]:        2706 :                         InstrCountTuples2(&mtstate->ps, 1);
    1179                 :        2706 :                         return returning;
    1180                 :             :                     }
    1181                 :             :                     else
    1182                 :           3 :                         goto vlock;
    1183                 :             :                 }
    1184         [ +  + ]:         331 :                 else if (onconflict == ONCONFLICT_SELECT)
    1185                 :             :                 {
    1186                 :             :                     /*
    1187                 :             :                      * In case of ON CONFLICT DO SELECT, optionally lock the
    1188                 :             :                      * conflicting tuple, fetch it and project RETURNING on
    1189                 :             :                      * it. Be prepared to retry if locking fails because of a
    1190                 :             :                      * concurrent UPDATE/DELETE to the conflict tuple.
    1191                 :             :                      */
    1192                 :         192 :                     TupleTableSlot *returning = NULL;
    1193                 :             : 
    1194         [ +  - ]:         192 :                     if (ExecOnConflictSelect(context, resultRelInfo,
    1195                 :             :                                              &conflictTid, slot, canSetTag,
    1196                 :             :                                              &returning))
    1197                 :             :                     {
    1198         [ -  + ]:         176 :                         InstrCountTuples2(&mtstate->ps, 1);
    1199                 :         176 :                         return returning;
    1200                 :             :                     }
    1201                 :             :                     else
    1202                 :           0 :                         goto vlock;
    1203                 :             :                 }
    1204                 :             :                 else
    1205                 :             :                 {
    1206                 :             :                     /*
    1207                 :             :                      * In case of ON CONFLICT DO NOTHING, do nothing. However,
    1208                 :             :                      * verify that the tuple is visible to the executor's MVCC
    1209                 :             :                      * snapshot at higher isolation levels.
    1210                 :             :                      *
    1211                 :             :                      * Using ExecGetReturningSlot() to store the tuple for the
    1212                 :             :                      * recheck isn't that pretty, but we can't trivially use
    1213                 :             :                      * the input slot, because it might not be of a compatible
    1214                 :             :                      * type. As there's no conflicting usage of
    1215                 :             :                      * ExecGetReturningSlot() in the DO NOTHING case...
    1216                 :             :                      */
    1217                 :             :                     Assert(onconflict == ONCONFLICT_NOTHING);
    1218                 :         139 :                     ExecCheckTIDVisible(estate, resultRelInfo, &conflictTid,
    1219                 :             :                                         ExecGetReturningSlot(estate, resultRelInfo));
    1220         [ -  + ]:         129 :                     InstrCountTuples2(&mtstate->ps, 1);
    1221                 :         129 :                     return NULL;
    1222                 :             :                 }
    1223                 :             :             }
    1224                 :             : 
    1225                 :             :             /*
    1226                 :             :              * Before we start insertion proper, acquire our "speculative
    1227                 :             :              * insertion lock".  Others can use that to wait for us to decide
    1228                 :             :              * if we're going to go ahead with the insertion, instead of
    1229                 :             :              * waiting for the whole transaction to complete.
    1230                 :             :              */
    1231                 :        2231 :             INJECTION_POINT("exec-insert-before-insert-speculative", NULL);
    1232                 :        2231 :             specToken = SpeculativeInsertionLockAcquire(GetCurrentTransactionId());
    1233                 :             : 
    1234                 :             :             /* insert the tuple, with the speculative token */
    1235                 :        2231 :             table_tuple_insert_speculative(resultRelationDesc, slot,
    1236                 :             :                                            estate->es_output_cid,
    1237                 :             :                                            0,
    1238                 :             :                                            NULL,
    1239                 :             :                                            specToken);
    1240                 :             : 
    1241                 :             :             /* insert index entries for tuple */
    1242                 :        2231 :             recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
    1243                 :             :                                                    estate, EIIT_NO_DUPE_ERROR,
    1244                 :             :                                                    slot, arbiterIndexes,
    1245                 :             :                                                    &specConflict);
    1246                 :             : 
    1247                 :             :             /* adjust the tuple's state accordingly */
    1248                 :        2227 :             table_tuple_complete_speculative(resultRelationDesc, slot,
    1249                 :        2227 :                                              specToken, !specConflict);
    1250                 :             : 
    1251                 :             :             /*
    1252                 :             :              * Wake up anyone waiting for our decision.  They will re-check
    1253                 :             :              * the tuple, see that it's no longer speculative, and wait on our
    1254                 :             :              * XID as if this was a regularly inserted tuple all along.  Or if
    1255                 :             :              * we killed the tuple, they will see it's dead, and proceed as if
    1256                 :             :              * the tuple never existed.
    1257                 :             :              */
    1258                 :        2227 :             SpeculativeInsertionLockRelease(GetCurrentTransactionId());
    1259                 :             : 
    1260                 :             :             /*
    1261                 :             :              * If there was a conflict, start from the beginning.  We'll do
    1262                 :             :              * the pre-check again, which will now find the conflicting tuple
    1263                 :             :              * (unless it aborts before we get there).
    1264                 :             :              */
    1265         [ +  + ]:        2227 :             if (specConflict)
    1266                 :             :             {
    1267                 :          11 :                 list_free(recheckIndexes);
    1268                 :          11 :                 goto vlock;
    1269                 :             :             }
    1270                 :             : 
    1271                 :             :             /* Since there was no insertion conflict, we're done */
    1272                 :             :         }
    1273                 :             :         else
    1274                 :             :         {
    1275                 :             :             /* insert the tuple normally */
    1276                 :     8073138 :             table_tuple_insert(resultRelationDesc, slot,
    1277                 :             :                                estate->es_output_cid,
    1278                 :             :                                0, NULL);
    1279                 :             : 
    1280                 :             :             /* insert index entries for tuple */
    1281         [ +  + ]:     8073117 :             if (resultRelInfo->ri_NumIndices > 0)
    1282                 :     2542343 :                 recheckIndexes = ExecInsertIndexTuples(resultRelInfo, estate,
    1283                 :             :                                                        0, slot, NIL,
    1284                 :             :                                                        NULL);
    1285                 :             :         }
    1286                 :             :     }
    1287                 :             : 
    1288         [ +  + ]:     8075913 :     if (canSetTag)
    1289                 :     8073898 :         (estate->es_processed)++;
    1290                 :             : 
    1291                 :             :     /*
    1292                 :             :      * If this insert is the result of a partition key update that moved the
    1293                 :             :      * tuple to a new partition, put this row into the transition NEW TABLE,
    1294                 :             :      * if there is one. We need to do this separately for DELETE and INSERT
    1295                 :             :      * because they happen on different tables.
    1296                 :             :      */
    1297                 :     8075913 :     ar_insert_trig_tcs = mtstate->mt_transition_capture;
    1298   [ +  +  +  + ]:     8075913 :     if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture
    1299         [ +  + ]:          36 :         && mtstate->mt_transition_capture->tcs_update_new_table)
    1300                 :             :     {
    1301                 :          32 :         ExecARUpdateTriggers(estate, resultRelInfo,
    1302                 :             :                              NULL, NULL,
    1303                 :             :                              NULL,
    1304                 :             :                              NULL,
    1305                 :             :                              slot,
    1306                 :             :                              NULL,
    1307                 :          32 :                              mtstate->mt_transition_capture,
    1308                 :             :                              false);
    1309                 :             : 
    1310                 :             :         /*
    1311                 :             :          * We've already captured the NEW TABLE row, so make sure any AR
    1312                 :             :          * INSERT trigger fired below doesn't capture it again.
    1313                 :             :          */
    1314                 :          32 :         ar_insert_trig_tcs = NULL;
    1315                 :             :     }
    1316                 :             : 
    1317                 :             :     /* AFTER ROW INSERT Triggers */
    1318                 :     8075913 :     ExecARInsertTriggers(estate, resultRelInfo, slot, recheckIndexes,
    1319                 :             :                          ar_insert_trig_tcs);
    1320                 :             : 
    1321                 :     8075912 :     list_free(recheckIndexes);
    1322                 :             : 
    1323                 :             :     /*
    1324                 :             :      * Check any WITH CHECK OPTION constraints from parent views.  We are
    1325                 :             :      * required to do this after testing all constraints and uniqueness
    1326                 :             :      * violations per the SQL spec, so we do it after actually inserting the
    1327                 :             :      * record into the heap and all indexes.
    1328                 :             :      *
    1329                 :             :      * ExecWithCheckOptions will elog(ERROR) if a violation is found, so the
    1330                 :             :      * tuple will never be seen, if it violates the WITH CHECK OPTION.
    1331                 :             :      *
    1332                 :             :      * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
    1333                 :             :      * are looking for at this point.
    1334                 :             :      */
    1335         [ +  + ]:     8075912 :     if (resultRelInfo->ri_WithCheckOptions != NIL)
    1336                 :         350 :         ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
    1337                 :             : 
    1338                 :             :     /*
    1339                 :             :      * Process RETURNING if present.
    1340                 :             :      *
    1341                 :             :      * If this is an UPDATE/DELETE ... FOR PORTION OF, we do not return the
    1342                 :             :      * leftover rows inserted by ExecForPortionOfLeftovers().  Note that we
    1343                 :             :      * must check mtstate->operation here, because we *do* want to process the
    1344                 :             :      * newly inserted row of a cross-partition UPDATE with a FOR PORTION OF
    1345                 :             :      * clause (ExecCrossPartitionUpdate() leaves mtstate->operation set to
    1346                 :             :      * CMD_UPDATE, whereas ExecForPortionOfLeftovers() sets it to CMD_INSERT).
    1347                 :             :      */
    1348         [ +  + ]:     8075808 :     if (resultRelInfo->ri_projectReturning &&
    1349   [ +  +  +  + ]:        2876 :         !(node->forPortionOf && mtstate->operation == CMD_INSERT))
    1350                 :             :     {
    1351                 :        2828 :         TupleTableSlot *oldSlot = NULL;
    1352                 :             : 
    1353                 :             :         /*
    1354                 :             :          * If this is part of a cross-partition UPDATE, and the RETURNING list
    1355                 :             :          * refers to any OLD columns, ExecDelete() will have saved the tuple
    1356                 :             :          * deleted from the original partition, which we must use here to
    1357                 :             :          * compute the OLD column values.  Otherwise, all OLD column values
    1358                 :             :          * will be NULL.
    1359                 :             :          */
    1360         [ +  + ]:        2828 :         if (context->cpDeletedSlot)
    1361                 :             :         {
    1362                 :             :             TupleConversionMap *tupconv_map;
    1363                 :             : 
    1364                 :             :             /*
    1365                 :             :              * Convert the OLD tuple to the new partition's format/slot, if
    1366                 :             :              * needed.  Note that ExecDelete() already converted it to the
    1367                 :             :              * root's partition's format/slot.
    1368                 :             :              */
    1369                 :          30 :             oldSlot = context->cpDeletedSlot;
    1370                 :          30 :             tupconv_map = ExecGetRootToChildMap(resultRelInfo, estate);
    1371         [ +  + ]:          30 :             if (tupconv_map != NULL)
    1372                 :             :             {
    1373                 :          10 :                 oldSlot = execute_attr_map_slot(tupconv_map->attrMap,
    1374                 :             :                                                 oldSlot,
    1375                 :             :                                                 ExecGetReturningSlot(estate,
    1376                 :             :                                                                      resultRelInfo));
    1377                 :             : 
    1378                 :          10 :                 oldSlot->tts_tableOid = context->cpDeletedSlot->tts_tableOid;
    1379                 :          10 :                 ItemPointerCopy(&context->cpDeletedSlot->tts_tid, &oldSlot->tts_tid);
    1380                 :             :             }
    1381                 :             :         }
    1382                 :             : 
    1383                 :        2828 :         result = ExecProcessReturning(context, resultRelInfo, false,
    1384                 :             :                                       oldSlot, slot, planSlot);
    1385                 :             : 
    1386                 :             :         /*
    1387                 :             :          * For a cross-partition UPDATE, release the old tuple, first making
    1388                 :             :          * sure that the result slot has a local copy of any pass-by-reference
    1389                 :             :          * values.
    1390                 :             :          */
    1391         [ +  + ]:        2820 :         if (context->cpDeletedSlot)
    1392                 :             :         {
    1393                 :          30 :             ExecMaterializeSlot(result);
    1394                 :          30 :             ExecClearTuple(oldSlot);
    1395         [ +  + ]:          30 :             if (context->cpDeletedSlot != oldSlot)
    1396                 :          10 :                 ExecClearTuple(context->cpDeletedSlot);
    1397                 :          30 :             context->cpDeletedSlot = NULL;
    1398                 :             :         }
    1399                 :             :     }
    1400                 :             : 
    1401         [ +  + ]:     8075800 :     if (inserted_tuple)
    1402                 :         565 :         *inserted_tuple = slot;
    1403         [ +  + ]:     8075800 :     if (insert_destrel)
    1404                 :         565 :         *insert_destrel = resultRelInfo;
    1405                 :             : 
    1406                 :     8075800 :     return result;
    1407                 :             : }
    1408                 :             : 
    1409                 :             : /* ----------------------------------------------------------------
    1410                 :             :  *      ExecForPortionOfLeftovers
    1411                 :             :  *
    1412                 :             :  *      Insert tuples for the untouched portion of a row in a FOR
    1413                 :             :  *      PORTION OF UPDATE/DELETE
    1414                 :             :  * ----------------------------------------------------------------
    1415                 :             :  */
    1416                 :             : static void
    1417                 :         909 : ExecForPortionOfLeftovers(ModifyTableContext *context,
    1418                 :             :                           EState *estate,
    1419                 :             :                           ResultRelInfo *resultRelInfo,
    1420                 :             :                           ItemPointer tupleid)
    1421                 :             : {
    1422                 :         909 :     ModifyTableState *mtstate = context->mtstate;
    1423                 :         909 :     ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
    1424                 :         909 :     ForPortionOfExpr *forPortionOf = (ForPortionOfExpr *) node->forPortionOf;
    1425                 :             :     Datum       oldRange;
    1426                 :             :     TypeCacheEntry *typcache;
    1427                 :             :     ForPortionOfState *fpoState;
    1428                 :             :     TupleTableSlot *oldtupleSlot;
    1429                 :             :     TupleTableSlot *leftoverSlot;
    1430                 :         909 :     TupleConversionMap *map = NULL;
    1431                 :         909 :     HeapTuple   oldtuple = NULL;
    1432                 :             :     CmdType     oldOperation;
    1433                 :             :     TransitionCaptureState *oldTcs;
    1434                 :             :     FmgrInfo    flinfo;
    1435                 :             :     PgStat_FunctionCallUsage fcusage;
    1436                 :             :     ReturnSetInfo rsi;
    1437                 :         909 :     bool        didInit = false;
    1438                 :         909 :     bool        shouldFree = false;
    1439                 :         909 :     ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
    1440                 :         909 :     bool        partitionRouting =
    1441         [ +  - ]:        1818 :         rootRelInfo &&
    1442         [ +  + ]:         909 :         rootRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
    1443                 :             : 
    1444                 :         909 :     LOCAL_FCINFO(fcinfo, 2);
    1445                 :             : 
    1446                 :         909 :     fpoState = resultRelInfo->ri_forPortionOf;
    1447                 :         909 :     oldtupleSlot = fpoState->fp_Existing;
    1448                 :         909 :     leftoverSlot = fpoState->fp_Leftover;
    1449                 :             : 
    1450                 :             :     /*
    1451                 :             :      * Get the old pre-UPDATE/DELETE tuple. We will use its range to compute
    1452                 :             :      * untouched parts of history, and if necessary we will insert copies with
    1453                 :             :      * truncated start/end times.
    1454                 :             :      *
    1455                 :             :      * We have already locked the tuple in ExecUpdate/ExecDelete, and it has
    1456                 :             :      * passed EvalPlanQual. This ensures that concurrent updates in READ
    1457                 :             :      * COMMITTED can't insert conflicting temporal leftovers.
    1458                 :             :      *
    1459                 :             :      * It does *not* protect against concurrent update/deletes overlooking
    1460                 :             :      * each others' leftovers though. See our isolation tests for details
    1461                 :             :      * about that and a viable workaround.
    1462                 :             :      */
    1463         [ -  + ]:         909 :     if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc, tupleid, SnapshotAny, oldtupleSlot))
    1464         [ #  # ]:           0 :         elog(ERROR, "failed to fetch tuple for FOR PORTION OF");
    1465                 :             : 
    1466                 :         909 :     slot_getallattrs(oldtupleSlot);
    1467                 :             : 
    1468                 :             :     /* Get the old range of the record being updated/deleted. */
    1469         [ -  + ]:         909 :     if (oldtupleSlot->tts_isnull[fpoState->fp_rangeAttno - 1])
    1470         [ #  # ]:           0 :         elog(ERROR, "found a NULL range in a temporal table");
    1471                 :         909 :     oldRange = oldtupleSlot->tts_values[fpoState->fp_rangeAttno - 1];
    1472                 :             : 
    1473                 :             :     /*
    1474                 :             :      * Get the range's type cache entry. This is worth caching for the whole
    1475                 :             :      * UPDATE/DELETE as range functions do.
    1476                 :             :      */
    1477                 :             : 
    1478                 :         909 :     typcache = fpoState->fp_leftoverstypcache;
    1479         [ +  + ]:         909 :     if (typcache == NULL)
    1480                 :             :     {
    1481                 :         770 :         typcache = lookup_type_cache(forPortionOf->rangeType, 0);
    1482                 :         770 :         fpoState->fp_leftoverstypcache = typcache;
    1483                 :             :     }
    1484                 :             : 
    1485                 :             :     /*
    1486                 :             :      * Get the ranges to the left/right of the targeted range. We call a SETOF
    1487                 :             :      * support function and insert as many temporal leftovers as it gives us.
    1488                 :             :      * Although rangetypes have 0/1/2 leftovers, multiranges have 0/1, and
    1489                 :             :      * other types may have more.
    1490                 :             :      */
    1491                 :             : 
    1492                 :         909 :     fmgr_info(forPortionOf->withoutPortionProc, &flinfo);
    1493                 :         909 :     rsi.type = T_ReturnSetInfo;
    1494                 :         909 :     rsi.econtext = mtstate->ps.ps_ExprContext;
    1495                 :         909 :     rsi.expectedDesc = NULL;
    1496                 :         909 :     rsi.allowedModes = (int) (SFRM_ValuePerCall);
    1497                 :         909 :     rsi.returnMode = SFRM_ValuePerCall;
    1498                 :             :     /* isDone is filled below */
    1499                 :         909 :     rsi.setResult = NULL;
    1500                 :         909 :     rsi.setDesc = NULL;
    1501                 :             : 
    1502                 :         909 :     InitFunctionCallInfoData(*fcinfo, &flinfo, 2, InvalidOid, NULL, (Node *) &rsi);
    1503                 :         909 :     fcinfo->args[0].value = oldRange;
    1504                 :         909 :     fcinfo->args[0].isnull = false;
    1505                 :         909 :     fcinfo->args[1].value = fpoState->fp_targetRange;
    1506                 :         909 :     fcinfo->args[1].isnull = false;
    1507                 :             : 
    1508                 :             :     /*
    1509                 :             :      * For partitioned tables, we must read leftovers with the tuple
    1510                 :             :      * descriptor of the child table, but insert into the root table to enable
    1511                 :             :      * tuple routing. So leftoverSlot is configured with the root's tuple
    1512                 :             :      * descriptor. But for traditional table inheritance, we don't need tuple
    1513                 :             :      * routing and just insert directly into the child table to preserve
    1514                 :             :      * child-specific columns. In that case, leftoverSlot uses the child's
    1515                 :             :      * (resultRelInfo) tuple descriptor.
    1516                 :             :      */
    1517         [ +  + ]:         909 :     if (partitionRouting)
    1518                 :             :     {
    1519                 :          66 :         map = ExecGetChildToRootMap(resultRelInfo);
    1520                 :          66 :         resultRelInfo = resultRelInfo->ri_RootResultRelInfo;
    1521                 :             :     }
    1522                 :             : 
    1523                 :             :     /*
    1524                 :             :      * Insert a leftover for each value returned by the without_portion helper
    1525                 :             :      * function
    1526                 :             :      */
    1527                 :             :     while (true)
    1528                 :        1187 :     {
    1529                 :             :         Datum       leftover;
    1530                 :             : 
    1531                 :             :         /* Call the function one time */
    1532                 :        2096 :         pgstat_init_function_usage(fcinfo, &fcusage);
    1533                 :             : 
    1534                 :        2096 :         fcinfo->isnull = false;
    1535                 :        2096 :         rsi.isDone = ExprSingleResult;
    1536                 :        2096 :         leftover = FunctionCallInvoke(fcinfo);
    1537                 :             : 
    1538                 :        2096 :         pgstat_end_function_usage(&fcusage,
    1539                 :        2096 :                                   rsi.isDone != ExprMultipleResult);
    1540                 :             : 
    1541         [ -  + ]:        2096 :         if (rsi.returnMode != SFRM_ValuePerCall)
    1542         [ #  # ]:           0 :             elog(ERROR, "without_portion function violated function call protocol");
    1543                 :             : 
    1544                 :             :         /* Are we done? */
    1545         [ +  + ]:        2096 :         if (rsi.isDone == ExprEndResult)
    1546                 :         857 :             break;
    1547                 :             : 
    1548         [ -  + ]:        1239 :         if (fcinfo->isnull)
    1549         [ #  # ]:           0 :             elog(ERROR, "got a null from without_portion function");
    1550                 :             : 
    1551                 :             :         /*
    1552                 :             :          * Does the new Datum violate domain checks? Row-level CHECK
    1553                 :             :          * constraints are validated by ExecInsert, so we don't need to do
    1554                 :             :          * anything here for those.
    1555                 :             :          */
    1556         [ +  + ]:        1239 :         if (forPortionOf->isDomain)
    1557                 :          80 :             domain_check(leftover, false, forPortionOf->rangeVar->vartype, NULL, NULL);
    1558                 :             : 
    1559         [ +  + ]:        1223 :         if (!didInit)
    1560                 :             :         {
    1561                 :             :             /*
    1562                 :             :              * Make a copy of the pre-UPDATE row. Then we'll overwrite the
    1563                 :             :              * range column below. Only partitioned targets need conversion to
    1564                 :             :              * the root table's format, because they reinsert through the root
    1565                 :             :              * relation for tuple routing.
    1566                 :             :              */
    1567         [ +  + ]:         789 :             if (map != NULL)
    1568                 :             :             {
    1569                 :          16 :                 leftoverSlot = execute_attr_map_slot(map->attrMap,
    1570                 :             :                                                      oldtupleSlot,
    1571                 :             :                                                      leftoverSlot);
    1572                 :             :             }
    1573                 :             :             else
    1574                 :             :             {
    1575                 :         773 :                 oldtuple = ExecFetchSlotHeapTuple(oldtupleSlot, false, &shouldFree);
    1576                 :         773 :                 ExecForceStoreHeapTuple(oldtuple, leftoverSlot, false);
    1577                 :             :             }
    1578                 :             : 
    1579                 :             :             /*
    1580                 :             :              * Save some mtstate things so we can restore them below. XXX:
    1581                 :             :              * Should we create our own ModifyTableState instead?
    1582                 :             :              */
    1583                 :         789 :             oldOperation = mtstate->operation;
    1584                 :         789 :             mtstate->operation = CMD_INSERT;
    1585                 :         789 :             oldTcs = mtstate->mt_transition_capture;
    1586                 :             : 
    1587                 :         789 :             didInit = true;
    1588                 :             :         }
    1589                 :             :         else
    1590                 :             :         {
    1591                 :             :             /*
    1592                 :             :              * Re-copy the original row into leftoverSlot because ExecInsert
    1593                 :             :              * might pass leftoverSlot to BEFORE ROW INSERT triggers, which
    1594                 :             :              * can modify the slot contents.
    1595                 :             :              */
    1596         [ +  + ]:         434 :             if (map != NULL)
    1597                 :          16 :                 execute_attr_map_slot(map->attrMap, oldtupleSlot, leftoverSlot);
    1598                 :             :             else
    1599                 :         418 :                 ExecForceStoreHeapTuple(oldtuple, leftoverSlot, false);
    1600                 :             :         }
    1601                 :             : 
    1602                 :        1223 :         leftoverSlot->tts_values[resultRelInfo->ri_forPortionOf->fp_rangeAttno - 1] = leftover;
    1603                 :        1223 :         leftoverSlot->tts_isnull[resultRelInfo->ri_forPortionOf->fp_rangeAttno - 1] = false;
    1604                 :        1223 :         ExecMaterializeSlot(leftoverSlot);
    1605                 :             : 
    1606                 :             :         /*
    1607                 :             :          * The standard says that each temporal leftover should execute its
    1608                 :             :          * own INSERT statement, firing all statement and row triggers, but
    1609                 :             :          * skipping insert permission checks. Therefore we give each insert
    1610                 :             :          * its own transition table. If we just push & pop a new trigger level
    1611                 :             :          * for each insert, we get exactly what we need.
    1612                 :             :          *
    1613                 :             :          * We have to make sure that the inserts don't add to the ROW_COUNT
    1614                 :             :          * diagnostic or the command tag, so we pass false for canSetTag.
    1615                 :             :          */
    1616                 :        1223 :         AfterTriggerBeginQuery();
    1617                 :        1223 :         ExecSetupTransitionCaptureState(mtstate, estate);
    1618                 :        1223 :         fireBSTriggers(mtstate);
    1619                 :        1223 :         ExecInsert(context, resultRelInfo, leftoverSlot, false, NULL, NULL);
    1620                 :        1187 :         fireASTriggers(mtstate);
    1621                 :        1187 :         AfterTriggerEndQuery(estate);
    1622                 :             :     }
    1623                 :             : 
    1624         [ +  + ]:         857 :     if (didInit)
    1625                 :             :     {
    1626                 :         753 :         mtstate->operation = oldOperation;
    1627                 :         753 :         mtstate->mt_transition_capture = oldTcs;
    1628                 :             : 
    1629         [ -  + ]:         753 :         if (shouldFree)
    1630                 :           0 :             heap_freetuple(oldtuple);
    1631                 :             :     }
    1632                 :         857 : }
    1633                 :             : 
    1634                 :             : /* ----------------------------------------------------------------
    1635                 :             :  *      ExecBatchInsert
    1636                 :             :  *
    1637                 :             :  *      Insert multiple tuples in an efficient way.
    1638                 :             :  *      Currently, this handles inserting into a foreign table without
    1639                 :             :  *      RETURNING clause.
    1640                 :             :  * ----------------------------------------------------------------
    1641                 :             :  */
    1642                 :             : static void
    1643                 :          29 : ExecBatchInsert(ModifyTableState *mtstate,
    1644                 :             :                 ResultRelInfo *resultRelInfo,
    1645                 :             :                 TupleTableSlot **slots,
    1646                 :             :                 TupleTableSlot **planSlots,
    1647                 :             :                 int numSlots,
    1648                 :             :                 EState *estate,
    1649                 :             :                 bool canSetTag)
    1650                 :             : {
    1651                 :             :     int         i;
    1652                 :          29 :     int         numInserted = numSlots;
    1653                 :          29 :     TupleTableSlot *slot = NULL;
    1654                 :             :     TupleTableSlot **rslots;
    1655                 :             : 
    1656                 :             :     /*
    1657                 :             :      * insert into foreign table: let the FDW do it
    1658                 :             :      */
    1659                 :          29 :     rslots = resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
    1660                 :             :                                                                   resultRelInfo,
    1661                 :             :                                                                   slots,
    1662                 :             :                                                                   planSlots,
    1663                 :             :                                                                   &numInserted);
    1664                 :             : 
    1665         [ +  + ]:         173 :     for (i = 0; i < numInserted; i++)
    1666                 :             :     {
    1667                 :         145 :         slot = rslots[i];
    1668                 :             : 
    1669                 :             :         /*
    1670                 :             :          * AFTER ROW Triggers might reference the tableoid column, so
    1671                 :             :          * (re-)initialize tts_tableOid before evaluating them.
    1672                 :             :          */
    1673                 :         145 :         slot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
    1674                 :             : 
    1675                 :             :         /* AFTER ROW INSERT Triggers */
    1676                 :         145 :         ExecARInsertTriggers(estate, resultRelInfo, slot, NIL,
    1677                 :         145 :                              mtstate->mt_transition_capture);
    1678                 :             : 
    1679                 :             :         /*
    1680                 :             :          * Check any WITH CHECK OPTION constraints from parent views.  See the
    1681                 :             :          * comment in ExecInsert.
    1682                 :             :          */
    1683         [ -  + ]:         144 :         if (resultRelInfo->ri_WithCheckOptions != NIL)
    1684                 :           0 :             ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo, slot, estate);
    1685                 :             :     }
    1686                 :             : 
    1687   [ +  -  +  - ]:          28 :     if (canSetTag && numInserted > 0)
    1688                 :          28 :         estate->es_processed += numInserted;
    1689                 :             : 
    1690                 :             :     /* Clean up all the slots, ready for the next batch */
    1691         [ +  + ]:         172 :     for (i = 0; i < numSlots; i++)
    1692                 :             :     {
    1693                 :         144 :         ExecClearTuple(slots[i]);
    1694                 :         144 :         ExecClearTuple(planSlots[i]);
    1695                 :             :     }
    1696                 :          28 :     resultRelInfo->ri_NumSlots = 0;
    1697                 :          28 : }
    1698                 :             : 
    1699                 :             : /*
    1700                 :             :  * ExecPendingInserts -- flushes all pending inserts to the foreign tables
    1701                 :             :  */
    1702                 :             : static void
    1703                 :          18 : ExecPendingInserts(EState *estate)
    1704                 :             : {
    1705                 :             :     ListCell   *l1,
    1706                 :             :                *l2;
    1707                 :             : 
    1708   [ +  -  +  +  :          36 :     forboth(l1, estate->es_insert_pending_result_relations,
          +  -  +  +  +  
             +  +  -  +  
                      + ]
    1709                 :             :             l2, estate->es_insert_pending_modifytables)
    1710                 :             :     {
    1711                 :          19 :         ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l1);
    1712                 :          19 :         ModifyTableState *mtstate = (ModifyTableState *) lfirst(l2);
    1713                 :             : 
    1714                 :             :         Assert(mtstate);
    1715                 :          19 :         ExecBatchInsert(mtstate, resultRelInfo,
    1716                 :             :                         resultRelInfo->ri_Slots,
    1717                 :             :                         resultRelInfo->ri_PlanSlots,
    1718                 :             :                         resultRelInfo->ri_NumSlots,
    1719                 :          19 :                         estate, mtstate->canSetTag);
    1720                 :             :     }
    1721                 :             : 
    1722                 :          17 :     list_free(estate->es_insert_pending_result_relations);
    1723                 :          17 :     list_free(estate->es_insert_pending_modifytables);
    1724                 :          17 :     estate->es_insert_pending_result_relations = NIL;
    1725                 :          17 :     estate->es_insert_pending_modifytables = NIL;
    1726                 :          17 : }
    1727                 :             : 
    1728                 :             : /*
    1729                 :             :  * ExecDeletePrologue -- subroutine for ExecDelete
    1730                 :             :  *
    1731                 :             :  * Prepare executor state for DELETE.  Actually, the only thing we have to do
    1732                 :             :  * here is execute BEFORE ROW triggers.  We return false if one of them makes
    1733                 :             :  * the delete a no-op; otherwise, return true.
    1734                 :             :  */
    1735                 :             : static bool
    1736                 :     1044035 : ExecDeletePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    1737                 :             :                    ItemPointer tupleid, HeapTuple oldtuple,
    1738                 :             :                    TupleTableSlot **epqreturnslot, TM_Result *result)
    1739                 :             : {
    1740         [ +  + ]:     1044035 :     if (result)
    1741                 :        1070 :         *result = TM_Ok;
    1742                 :             : 
    1743                 :             :     /* BEFORE ROW DELETE triggers */
    1744         [ +  + ]:     1044035 :     if (resultRelInfo->ri_TrigDesc &&
    1745         [ +  + ]:        4707 :         resultRelInfo->ri_TrigDesc->trig_delete_before_row)
    1746                 :             :     {
    1747                 :             :         /* Flush any pending inserts, so rows are visible to the triggers */
    1748         [ +  + ]:         218 :         if (context->estate->es_insert_pending_result_relations != NIL)
    1749                 :           1 :             ExecPendingInserts(context->estate);
    1750                 :             : 
    1751                 :         208 :         return ExecBRDeleteTriggers(context->estate, context->epqstate,
    1752                 :             :                                     resultRelInfo, tupleid, oldtuple,
    1753                 :             :                                     epqreturnslot, result, &context->tmfd,
    1754                 :         218 :                                     context->mtstate->operation == CMD_MERGE);
    1755                 :             :     }
    1756                 :             : 
    1757                 :     1043817 :     return true;
    1758                 :             : }
    1759                 :             : 
    1760                 :             : /*
    1761                 :             :  * ExecDeleteAct -- subroutine for ExecDelete
    1762                 :             :  *
    1763                 :             :  * Actually delete the tuple from a plain table.
    1764                 :             :  *
    1765                 :             :  * Caller is in charge of doing EvalPlanQual as necessary
    1766                 :             :  */
    1767                 :             : static TM_Result
    1768                 :     1043929 : ExecDeleteAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    1769                 :             :               ItemPointer tupleid, bool changingPart)
    1770                 :             : {
    1771                 :     1043929 :     EState     *estate = context->estate;
    1772                 :     1043929 :     uint32      options = 0;
    1773                 :             : 
    1774         [ +  + ]:     1043929 :     if (changingPart)
    1775                 :         697 :         options |= TABLE_DELETE_CHANGING_PARTITION;
    1776                 :             : 
    1777                 :     1043929 :     return table_tuple_delete(resultRelInfo->ri_RelationDesc, tupleid,
    1778                 :             :                               estate->es_output_cid,
    1779                 :             :                               options,
    1780                 :             :                               estate->es_snapshot,
    1781                 :             :                               estate->es_crosscheck_snapshot,
    1782                 :             :                               true /* wait for commit */ ,
    1783                 :             :                               &context->tmfd);
    1784                 :             : }
    1785                 :             : 
    1786                 :             : /*
    1787                 :             :  * ExecDeleteEpilogue -- subroutine for ExecDelete
    1788                 :             :  *
    1789                 :             :  * Closing steps of tuple deletion; this invokes AFTER FOR EACH ROW triggers,
    1790                 :             :  * including the UPDATE triggers if the deletion is being done as part of a
    1791                 :             :  * cross-partition tuple move. It also inserts temporal leftovers from a
    1792                 :             :  * DELETE FOR PORTION OF.
    1793                 :             :  */
    1794                 :             : static void
    1795                 :     1043867 : ExecDeleteEpilogue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    1796                 :             :                    ItemPointer tupleid, HeapTuple oldtuple, bool changingPart)
    1797                 :             : {
    1798                 :     1043867 :     ModifyTableState *mtstate = context->mtstate;
    1799                 :     1043867 :     EState     *estate = context->estate;
    1800                 :             :     TransitionCaptureState *ar_delete_trig_tcs;
    1801                 :             : 
    1802                 :             :     /*
    1803                 :             :      * If this delete is the result of a partition key update that moved the
    1804                 :             :      * tuple to a new partition, put this row into the transition OLD TABLE,
    1805                 :             :      * if there is one. We need to do this separately for DELETE and INSERT
    1806                 :             :      * because they happen on different tables.
    1807                 :             :      */
    1808                 :     1043867 :     ar_delete_trig_tcs = mtstate->mt_transition_capture;
    1809   [ +  +  +  + ]:     1043867 :     if (mtstate->operation == CMD_UPDATE && mtstate->mt_transition_capture &&
    1810         [ +  + ]:          36 :         mtstate->mt_transition_capture->tcs_update_old_table)
    1811                 :             :     {
    1812                 :          32 :         ExecARUpdateTriggers(estate, resultRelInfo,
    1813                 :             :                              NULL, NULL,
    1814                 :             :                              tupleid, oldtuple,
    1815                 :          32 :                              NULL, NULL, mtstate->mt_transition_capture,
    1816                 :             :                              false);
    1817                 :             : 
    1818                 :             :         /*
    1819                 :             :          * We've already captured the OLD TABLE row, so make sure any AR
    1820                 :             :          * DELETE trigger fired below doesn't capture it again.
    1821                 :             :          */
    1822                 :          32 :         ar_delete_trig_tcs = NULL;
    1823                 :             :     }
    1824                 :             : 
    1825                 :             :     /* Compute temporal leftovers in FOR PORTION OF */
    1826         [ +  + ]:     1043867 :     if (((ModifyTable *) context->mtstate->ps.plan)->forPortionOf)
    1827                 :         406 :         ExecForPortionOfLeftovers(context, estate, resultRelInfo, tupleid);
    1828                 :             : 
    1829                 :             :     /* AFTER ROW DELETE Triggers */
    1830                 :     1043843 :     ExecARDeleteTriggers(estate, resultRelInfo, tupleid, oldtuple,
    1831                 :             :                          ar_delete_trig_tcs, changingPart);
    1832                 :     1043841 : }
    1833                 :             : 
    1834                 :             : /* ----------------------------------------------------------------
    1835                 :             :  *      ExecDelete
    1836                 :             :  *
    1837                 :             :  *      DELETE is like UPDATE, except that we delete the tuple and no
    1838                 :             :  *      index modifications are needed.
    1839                 :             :  *
    1840                 :             :  *      When deleting from a table, tupleid identifies the tuple to delete and
    1841                 :             :  *      oldtuple is NULL.  When deleting through a view INSTEAD OF trigger,
    1842                 :             :  *      oldtuple is passed to the triggers and identifies what to delete, and
    1843                 :             :  *      tupleid is invalid.  When deleting from a foreign table, tupleid is
    1844                 :             :  *      invalid; the FDW has to figure out which row to delete using data from
    1845                 :             :  *      the planSlot.  oldtuple is passed to foreign table triggers; it is
    1846                 :             :  *      NULL when the foreign table has no relevant triggers.  We use
    1847                 :             :  *      tupleDeleted to indicate whether the tuple is actually deleted,
    1848                 :             :  *      callers can use it to decide whether to continue the operation.  When
    1849                 :             :  *      this DELETE is a part of an UPDATE of partition-key, then the slot
    1850                 :             :  *      returned by EvalPlanQual() is passed back using output parameter
    1851                 :             :  *      epqreturnslot.
    1852                 :             :  *
    1853                 :             :  *      Returns RETURNING result if any, otherwise NULL.
    1854                 :             :  * ----------------------------------------------------------------
    1855                 :             :  */
    1856                 :             : static TupleTableSlot *
    1857                 :     1043684 : ExecDelete(ModifyTableContext *context,
    1858                 :             :            ResultRelInfo *resultRelInfo,
    1859                 :             :            ItemPointer tupleid,
    1860                 :             :            HeapTuple oldtuple,
    1861                 :             :            bool processReturning,
    1862                 :             :            bool changingPart,
    1863                 :             :            bool canSetTag,
    1864                 :             :            TM_Result *tmresult,
    1865                 :             :            bool *tupleDeleted,
    1866                 :             :            TupleTableSlot **epqreturnslot)
    1867                 :             : {
    1868                 :     1043684 :     EState     *estate = context->estate;
    1869                 :     1043684 :     Relation    resultRelationDesc = resultRelInfo->ri_RelationDesc;
    1870                 :     1043684 :     TupleTableSlot *slot = NULL;
    1871                 :             :     TM_Result   result;
    1872                 :             :     bool        saveOld;
    1873                 :             : 
    1874         [ +  + ]:     1043684 :     if (tupleDeleted)
    1875                 :         719 :         *tupleDeleted = false;
    1876                 :             : 
    1877                 :             :     /*
    1878                 :             :      * Prepare for the delete.  This includes BEFORE ROW triggers, so we're
    1879                 :             :      * done if it says we are.
    1880                 :             :      */
    1881         [ +  + ]:     1043684 :     if (!ExecDeletePrologue(context, resultRelInfo, tupleid, oldtuple,
    1882                 :             :                             epqreturnslot, tmresult))
    1883                 :          33 :         return NULL;
    1884                 :             : 
    1885                 :             :     /* INSTEAD OF ROW DELETE Triggers */
    1886         [ +  + ]:     1043641 :     if (resultRelInfo->ri_TrigDesc &&
    1887         [ +  + ]:        4619 :         resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
    1888                 :          31 :     {
    1889                 :             :         bool        dodelete;
    1890                 :             : 
    1891                 :             :         Assert(oldtuple != NULL);
    1892                 :          35 :         dodelete = ExecIRDeleteTriggers(estate, resultRelInfo, oldtuple);
    1893                 :             : 
    1894         [ +  + ]:          35 :         if (!dodelete)          /* "do nothing" */
    1895                 :           4 :             return NULL;
    1896                 :             :     }
    1897         [ +  + ]:     1043606 :     else if (resultRelInfo->ri_FdwRoutine)
    1898                 :             :     {
    1899                 :             :         /*
    1900                 :             :          * delete from foreign table: let the FDW do it
    1901                 :             :          *
    1902                 :             :          * We offer the returning slot as a place to store RETURNING data,
    1903                 :             :          * although the FDW can return some other slot if it wants.
    1904                 :             :          */
    1905                 :          23 :         slot = ExecGetReturningSlot(estate, resultRelInfo);
    1906                 :          23 :         slot = resultRelInfo->ri_FdwRoutine->ExecForeignDelete(estate,
    1907                 :             :                                                                resultRelInfo,
    1908                 :             :                                                                slot,
    1909                 :             :                                                                context->planSlot);
    1910                 :             : 
    1911         [ -  + ]:          23 :         if (slot == NULL)       /* "do nothing" */
    1912                 :           0 :             return NULL;
    1913                 :             : 
    1914                 :             :         /*
    1915                 :             :          * RETURNING expressions might reference the tableoid column, so
    1916                 :             :          * (re)initialize tts_tableOid before evaluating them.
    1917                 :             :          */
    1918         [ +  + ]:          23 :         if (TTS_EMPTY(slot))
    1919                 :           5 :             ExecStoreAllNullTuple(slot);
    1920                 :             : 
    1921                 :          23 :         slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
    1922                 :             :     }
    1923                 :             :     else
    1924                 :             :     {
    1925                 :             :         /*
    1926                 :             :          * delete the tuple
    1927                 :             :          *
    1928                 :             :          * Note: if context->estate->es_crosscheck_snapshot isn't
    1929                 :             :          * InvalidSnapshot, we check that the row to be deleted is visible to
    1930                 :             :          * that snapshot, and throw a can't-serialize error if not. This is a
    1931                 :             :          * special-case behavior needed for referential integrity updates in
    1932                 :             :          * transaction-snapshot mode transactions.
    1933                 :             :          */
    1934                 :     1043583 : ldelete:
    1935                 :     1043589 :         result = ExecDeleteAct(context, resultRelInfo, tupleid, changingPart);
    1936                 :             : 
    1937         [ +  + ]:     1043571 :         if (tmresult)
    1938                 :         697 :             *tmresult = result;
    1939                 :             : 
    1940   [ +  +  +  +  :     1043571 :         switch (result)
                      - ]
    1941                 :             :         {
    1942                 :          28 :             case TM_SelfModified:
    1943                 :             : 
    1944                 :             :                 /*
    1945                 :             :                  * The target tuple was already updated or deleted by the
    1946                 :             :                  * current command, or by a later command in the current
    1947                 :             :                  * transaction.  The former case is possible in a join DELETE
    1948                 :             :                  * where multiple tuples join to the same target tuple. This
    1949                 :             :                  * is somewhat questionable, but Postgres has always allowed
    1950                 :             :                  * it: we just ignore additional deletion attempts.
    1951                 :             :                  *
    1952                 :             :                  * The latter case arises if the tuple is modified by a
    1953                 :             :                  * command in a BEFORE trigger, or perhaps by a command in a
    1954                 :             :                  * volatile function used in the query.  In such situations we
    1955                 :             :                  * should not ignore the deletion, but it is equally unsafe to
    1956                 :             :                  * proceed.  We don't want to discard the original DELETE
    1957                 :             :                  * while keeping the triggered actions based on its deletion;
    1958                 :             :                  * and it would be no better to allow the original DELETE
    1959                 :             :                  * while discarding updates that it triggered.  The row update
    1960                 :             :                  * carries some information that might be important according
    1961                 :             :                  * to business rules; so throwing an error is the only safe
    1962                 :             :                  * course.
    1963                 :             :                  *
    1964                 :             :                  * If a trigger actually intends this type of interaction, it
    1965                 :             :                  * can re-execute the DELETE and then return NULL to cancel
    1966                 :             :                  * the outer delete.
    1967                 :             :                  */
    1968         [ +  + ]:          28 :                 if (context->tmfd.cmax != estate->es_output_cid)
    1969         [ +  - ]:           4 :                     ereport(ERROR,
    1970                 :             :                             (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    1971                 :             :                              errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
    1972                 :             :                              errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    1973                 :             : 
    1974                 :             :                 /* Else, already deleted by self; nothing to do */
    1975                 :          24 :                 return NULL;
    1976                 :             : 
    1977                 :     1043480 :             case TM_Ok:
    1978                 :     1043480 :                 break;
    1979                 :             : 
    1980                 :          48 :             case TM_Updated:
    1981                 :             :                 {
    1982                 :             :                     TupleTableSlot *inputslot;
    1983                 :             :                     TupleTableSlot *epqslot;
    1984                 :             : 
    1985         [ +  + ]:          48 :                     if (IsolationUsesXactSnapshot())
    1986         [ +  - ]:          10 :                         ereport(ERROR,
    1987                 :             :                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    1988                 :             :                                  errmsg("could not serialize access due to concurrent update")));
    1989                 :             : 
    1990                 :             :                     /*
    1991                 :             :                      * Already know that we're going to need to do EPQ, so
    1992                 :             :                      * fetch tuple directly into the right slot.
    1993                 :             :                      */
    1994                 :          38 :                     EvalPlanQualBegin(context->epqstate);
    1995                 :          38 :                     inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
    1996                 :             :                                                  resultRelInfo->ri_RangeTableIndex);
    1997                 :             : 
    1998                 :          38 :                     result = table_tuple_lock(resultRelationDesc, tupleid,
    1999                 :             :                                               estate->es_snapshot,
    2000                 :             :                                               inputslot, estate->es_output_cid,
    2001                 :             :                                               LockTupleExclusive, LockWaitBlock,
    2002                 :             :                                               TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
    2003                 :             :                                               &context->tmfd);
    2004                 :             : 
    2005   [ +  +  +  - ]:          34 :                     switch (result)
    2006                 :             :                     {
    2007                 :          31 :                         case TM_Ok:
    2008                 :             :                             Assert(context->tmfd.traversed);
    2009                 :          31 :                             epqslot = EvalPlanQual(context->epqstate,
    2010                 :             :                                                    resultRelationDesc,
    2011                 :             :                                                    resultRelInfo->ri_RangeTableIndex,
    2012                 :             :                                                    inputslot);
    2013   [ +  -  +  + ]:          31 :                             if (TupIsNull(epqslot))
    2014                 :             :                                 /* Tuple not passing quals anymore, exiting... */
    2015                 :          16 :                                 return NULL;
    2016                 :             : 
    2017                 :             :                             /*
    2018                 :             :                              * If requested, skip delete and pass back the
    2019                 :             :                              * updated row.
    2020                 :             :                              */
    2021         [ +  + ]:          15 :                             if (epqreturnslot)
    2022                 :             :                             {
    2023                 :           9 :                                 *epqreturnslot = epqslot;
    2024                 :           9 :                                 return NULL;
    2025                 :             :                             }
    2026                 :             :                             else
    2027                 :           6 :                                 goto ldelete;
    2028                 :             : 
    2029                 :           2 :                         case TM_SelfModified:
    2030                 :             : 
    2031                 :             :                             /*
    2032                 :             :                              * This can be reached when following an update
    2033                 :             :                              * chain from a tuple updated by another session,
    2034                 :             :                              * reaching a tuple that was already updated in
    2035                 :             :                              * this transaction. If previously updated by this
    2036                 :             :                              * command, ignore the delete, otherwise error
    2037                 :             :                              * out.
    2038                 :             :                              *
    2039                 :             :                              * See also TM_SelfModified response to
    2040                 :             :                              * table_tuple_delete() above.
    2041                 :             :                              */
    2042         [ +  + ]:           2 :                             if (context->tmfd.cmax != estate->es_output_cid)
    2043         [ +  - ]:           1 :                                 ereport(ERROR,
    2044                 :             :                                         (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    2045                 :             :                                          errmsg("tuple to be deleted was already modified by an operation triggered by the current command"),
    2046                 :             :                                          errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    2047                 :           1 :                             return NULL;
    2048                 :             : 
    2049                 :           1 :                         case TM_Deleted:
    2050                 :             :                             /* tuple already deleted; nothing to do */
    2051                 :           1 :                             return NULL;
    2052                 :             : 
    2053                 :           0 :                         default:
    2054                 :             : 
    2055                 :             :                             /*
    2056                 :             :                              * TM_Invisible should be impossible because we're
    2057                 :             :                              * waiting for updated row versions, and would
    2058                 :             :                              * already have errored out if the first version
    2059                 :             :                              * is invisible.
    2060                 :             :                              *
    2061                 :             :                              * TM_Updated should be impossible, because we're
    2062                 :             :                              * locking the latest version via
    2063                 :             :                              * TUPLE_LOCK_FLAG_FIND_LAST_VERSION.
    2064                 :             :                              */
    2065         [ #  # ]:           0 :                             elog(ERROR, "unexpected table_tuple_lock status: %u",
    2066                 :             :                                  result);
    2067                 :             :                             return NULL;
    2068                 :             :                     }
    2069                 :             : 
    2070                 :             :                     Assert(false);
    2071                 :             :                     break;
    2072                 :             :                 }
    2073                 :             : 
    2074                 :          15 :             case TM_Deleted:
    2075         [ +  + ]:          15 :                 if (IsolationUsesXactSnapshot())
    2076         [ +  - ]:           9 :                     ereport(ERROR,
    2077                 :             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    2078                 :             :                              errmsg("could not serialize access due to concurrent delete")));
    2079                 :             :                 /* tuple already deleted; nothing to do */
    2080                 :           6 :                 return NULL;
    2081                 :             : 
    2082                 :           0 :             default:
    2083         [ #  # ]:           0 :                 elog(ERROR, "unrecognized table_tuple_delete status: %u",
    2084                 :             :                      result);
    2085                 :             :                 return NULL;
    2086                 :             :         }
    2087                 :             : 
    2088                 :             :         /*
    2089                 :             :          * Note: Normally one would think that we have to delete index tuples
    2090                 :             :          * associated with the heap tuple now...
    2091                 :             :          *
    2092                 :             :          * ... but in POSTGRES, we have no need to do this because VACUUM will
    2093                 :             :          * take care of it later.  We can't delete index tuples immediately
    2094                 :             :          * anyway, since the tuple is still visible to other transactions.
    2095                 :             :          */
    2096                 :             :     }
    2097                 :             : 
    2098         [ +  + ]:     1043534 :     if (canSetTag)
    2099                 :     1042701 :         (estate->es_processed)++;
    2100                 :             : 
    2101                 :             :     /* Tell caller that the delete actually happened. */
    2102         [ +  + ]:     1043534 :     if (tupleDeleted)
    2103                 :         666 :         *tupleDeleted = true;
    2104                 :             : 
    2105                 :     1043534 :     ExecDeleteEpilogue(context, resultRelInfo, tupleid, oldtuple, changingPart);
    2106                 :             : 
    2107                 :             :     /*
    2108                 :             :      * Process RETURNING if present and if requested.
    2109                 :             :      *
    2110                 :             :      * If this is part of a cross-partition UPDATE, and the RETURNING list
    2111                 :             :      * refers to any OLD column values, save the old tuple here for later
    2112                 :             :      * processing of the RETURNING list by ExecInsert().
    2113                 :             :      */
    2114   [ +  +  +  + ]:     1043607 :     saveOld = changingPart && resultRelInfo->ri_projectReturning &&
    2115         [ +  + ]:          99 :         resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD;
    2116                 :             : 
    2117   [ +  +  +  +  :     1043508 :     if (resultRelInfo->ri_projectReturning && (processReturning || saveOld))
                   +  + ]
    2118                 :             :     {
    2119                 :             :         /*
    2120                 :             :          * We have to put the target tuple into a slot, which means first we
    2121                 :             :          * gotta fetch it.  We can use the trigger tuple slot.
    2122                 :             :          */
    2123                 :             :         TupleTableSlot *rslot;
    2124                 :             : 
    2125         [ +  + ]:         628 :         if (resultRelInfo->ri_FdwRoutine)
    2126                 :             :         {
    2127                 :             :             /* FDW must have provided a slot containing the deleted row */
    2128                 :             :             Assert(!TupIsNull(slot));
    2129                 :             :         }
    2130                 :             :         else
    2131                 :             :         {
    2132                 :         621 :             slot = ExecGetReturningSlot(estate, resultRelInfo);
    2133         [ +  + ]:         621 :             if (oldtuple != NULL)
    2134                 :             :             {
    2135                 :          16 :                 ExecForceStoreHeapTuple(oldtuple, slot, false);
    2136                 :             :             }
    2137                 :             :             else
    2138                 :             :             {
    2139         [ -  + ]:         605 :                 if (!table_tuple_fetch_row_version(resultRelationDesc, tupleid,
    2140                 :             :                                                    SnapshotAny, slot))
    2141         [ #  # ]:           0 :                     elog(ERROR, "failed to fetch deleted tuple for DELETE RETURNING");
    2142                 :             :             }
    2143                 :             :         }
    2144                 :             : 
    2145                 :             :         /*
    2146                 :             :          * If required, save the old tuple for later processing of the
    2147                 :             :          * RETURNING list by ExecInsert().
    2148                 :             :          */
    2149         [ +  + ]:         628 :         if (saveOld)
    2150                 :             :         {
    2151                 :             :             TupleConversionMap *tupconv_map;
    2152                 :             : 
    2153                 :             :             /*
    2154                 :             :              * Convert the tuple into the root partition's format/slot, if
    2155                 :             :              * needed.  ExecInsert() will then convert it to the new
    2156                 :             :              * partition's format/slot, if necessary.
    2157                 :             :              */
    2158                 :          30 :             tupconv_map = ExecGetChildToRootMap(resultRelInfo);
    2159         [ +  + ]:          30 :             if (tupconv_map != NULL)
    2160                 :             :             {
    2161                 :          12 :                 ResultRelInfo *rootRelInfo = context->mtstate->rootResultRelInfo;
    2162                 :          12 :                 TupleTableSlot *oldSlot = slot;
    2163                 :             : 
    2164                 :          12 :                 slot = execute_attr_map_slot(tupconv_map->attrMap,
    2165                 :             :                                              slot,
    2166                 :             :                                              ExecGetReturningSlot(estate,
    2167                 :             :                                                                   rootRelInfo));
    2168                 :             : 
    2169                 :          12 :                 slot->tts_tableOid = oldSlot->tts_tableOid;
    2170                 :          12 :                 ItemPointerCopy(&oldSlot->tts_tid, &slot->tts_tid);
    2171                 :             :             }
    2172                 :             : 
    2173                 :          30 :             context->cpDeletedSlot = slot;
    2174                 :             : 
    2175                 :          30 :             return NULL;
    2176                 :             :         }
    2177                 :             : 
    2178                 :         598 :         rslot = ExecProcessReturning(context, resultRelInfo, true,
    2179                 :             :                                      slot, NULL, context->planSlot);
    2180                 :             : 
    2181                 :             :         /*
    2182                 :             :          * Before releasing the target tuple again, make sure rslot has a
    2183                 :             :          * local copy of any pass-by-reference values.
    2184                 :             :          */
    2185                 :         598 :         ExecMaterializeSlot(rslot);
    2186                 :             : 
    2187                 :         598 :         ExecClearTuple(slot);
    2188                 :             : 
    2189                 :         598 :         return rslot;
    2190                 :             :     }
    2191                 :             : 
    2192                 :     1042880 :     return NULL;
    2193                 :             : }
    2194                 :             : 
    2195                 :             : /*
    2196                 :             :  * ExecCrossPartitionUpdate --- Move an updated tuple to another partition.
    2197                 :             :  *
    2198                 :             :  * This works by first deleting the old tuple from the current partition,
    2199                 :             :  * followed by inserting the new tuple into the root parent table, that is,
    2200                 :             :  * mtstate->rootResultRelInfo.  It will be re-routed from there to the
    2201                 :             :  * correct partition.
    2202                 :             :  *
    2203                 :             :  * Returns true if the tuple has been successfully moved, or if it's found
    2204                 :             :  * that the tuple was concurrently deleted so there's nothing more to do
    2205                 :             :  * for the caller.
    2206                 :             :  *
    2207                 :             :  * False is returned if the tuple we're trying to move is found to have been
    2208                 :             :  * concurrently updated.  In that case, the caller must check if the updated
    2209                 :             :  * tuple that's returned in *retry_slot still needs to be re-routed, and call
    2210                 :             :  * this function again or perform a regular update accordingly.  For MERGE,
    2211                 :             :  * the updated tuple is not returned in *retry_slot; it has its own retry
    2212                 :             :  * logic.
    2213                 :             :  */
    2214                 :             : static bool
    2215                 :         751 : ExecCrossPartitionUpdate(ModifyTableContext *context,
    2216                 :             :                          ResultRelInfo *resultRelInfo,
    2217                 :             :                          ItemPointer tupleid, HeapTuple oldtuple,
    2218                 :             :                          TupleTableSlot *slot,
    2219                 :             :                          bool canSetTag,
    2220                 :             :                          UpdateContext *updateCxt,
    2221                 :             :                          TM_Result *tmresult,
    2222                 :             :                          TupleTableSlot **retry_slot,
    2223                 :             :                          TupleTableSlot **inserted_tuple,
    2224                 :             :                          ResultRelInfo **insert_destrel)
    2225                 :             : {
    2226                 :         751 :     ModifyTableState *mtstate = context->mtstate;
    2227                 :         751 :     EState     *estate = mtstate->ps.state;
    2228                 :             :     TupleConversionMap *tupconv_map;
    2229                 :             :     bool        tuple_deleted;
    2230                 :         751 :     TupleTableSlot *epqslot = NULL;
    2231                 :             : 
    2232                 :         751 :     context->cpDeletedSlot = NULL;
    2233                 :         751 :     context->cpUpdateReturningSlot = NULL;
    2234                 :         751 :     *retry_slot = NULL;
    2235                 :             : 
    2236                 :             :     /*
    2237                 :             :      * Disallow an INSERT ON CONFLICT DO UPDATE that causes the original row
    2238                 :             :      * to migrate to a different partition.  Maybe this can be implemented
    2239                 :             :      * some day, but it seems a fringe feature with little redeeming value.
    2240                 :             :      */
    2241         [ -  + ]:         751 :     if (((ModifyTable *) mtstate->ps.plan)->onConflictAction == ONCONFLICT_UPDATE)
    2242         [ #  # ]:           0 :         ereport(ERROR,
    2243                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2244                 :             :                  errmsg("invalid ON UPDATE specification"),
    2245                 :             :                  errdetail("The result tuple would appear in a different partition than the original tuple.")));
    2246                 :             : 
    2247                 :             :     /*
    2248                 :             :      * When an UPDATE is run directly on a leaf partition, simply fail with a
    2249                 :             :      * partition constraint violation error.
    2250                 :             :      */
    2251         [ +  + ]:         751 :     if (resultRelInfo == mtstate->rootResultRelInfo)
    2252                 :          32 :         ExecPartitionCheckEmitError(resultRelInfo, slot, estate);
    2253                 :             : 
    2254                 :             :     /*
    2255                 :             :      * Initialize tuple routing info if not already done. Note whatever we do
    2256                 :             :      * here must be done in ExecInitModifyTable for FOR PORTION OF as well.
    2257                 :             :      */
    2258         [ +  + ]:         719 :     if (mtstate->mt_partition_tuple_routing == NULL)
    2259                 :             :     {
    2260                 :         440 :         Relation    rootRel = mtstate->rootResultRelInfo->ri_RelationDesc;
    2261                 :             :         MemoryContext oldcxt;
    2262                 :             : 
    2263                 :             :         /* Things built here have to last for the query duration. */
    2264                 :         440 :         oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
    2265                 :             : 
    2266                 :         440 :         mtstate->mt_partition_tuple_routing =
    2267                 :         440 :             ExecSetupPartitionTupleRouting(estate, rootRel);
    2268                 :             : 
    2269                 :             :         /*
    2270                 :             :          * Before a partition's tuple can be re-routed, it must first be
    2271                 :             :          * converted to the root's format, so we'll need a slot for storing
    2272                 :             :          * such tuples.
    2273                 :             :          */
    2274                 :             :         Assert(mtstate->mt_root_tuple_slot == NULL);
    2275                 :         440 :         mtstate->mt_root_tuple_slot = table_slot_create(rootRel, NULL);
    2276                 :             : 
    2277                 :         440 :         MemoryContextSwitchTo(oldcxt);
    2278                 :             :     }
    2279                 :             : 
    2280                 :             :     /*
    2281                 :             :      * Row movement, part 1.  Delete the tuple, but skip RETURNING processing.
    2282                 :             :      * We want to return rows from INSERT.
    2283                 :             :      */
    2284                 :         719 :     ExecDelete(context, resultRelInfo,
    2285                 :             :                tupleid, oldtuple,
    2286                 :             :                false,           /* processReturning */
    2287                 :             :                true,            /* changingPart */
    2288                 :             :                false,           /* canSetTag */
    2289                 :             :                tmresult, &tuple_deleted, &epqslot);
    2290                 :             : 
    2291                 :             :     /*
    2292                 :             :      * For some reason if DELETE didn't happen (e.g. trigger prevented it, or
    2293                 :             :      * it was already deleted by self, or it was concurrently deleted by
    2294                 :             :      * another transaction), then we should skip the insert as well;
    2295                 :             :      * otherwise, an UPDATE could cause an increase in the total number of
    2296                 :             :      * rows across all partitions, which is clearly wrong.
    2297                 :             :      *
    2298                 :             :      * For a normal UPDATE, the case where the tuple has been the subject of a
    2299                 :             :      * concurrent UPDATE or DELETE would be handled by the EvalPlanQual
    2300                 :             :      * machinery, but for an UPDATE that we've translated into a DELETE from
    2301                 :             :      * this partition and an INSERT into some other partition, that's not
    2302                 :             :      * available, because CTID chains can't span relation boundaries.  We
    2303                 :             :      * mimic the semantics to a limited extent by skipping the INSERT if the
    2304                 :             :      * DELETE fails to find a tuple.  This ensures that two concurrent
    2305                 :             :      * attempts to UPDATE the same tuple at the same time can't turn one tuple
    2306                 :             :      * into two, and that an UPDATE of a just-deleted tuple can't resurrect
    2307                 :             :      * it.
    2308                 :             :      */
    2309         [ +  + ]:         716 :     if (!tuple_deleted)
    2310                 :             :     {
    2311                 :             :         /*
    2312                 :             :          * epqslot will be typically NULL.  But when ExecDelete() finds that
    2313                 :             :          * another transaction has concurrently updated the same row, it
    2314                 :             :          * re-fetches the row, skips the delete, and epqslot is set to the
    2315                 :             :          * re-fetched tuple slot.  In that case, we need to do all the checks
    2316                 :             :          * again.  For MERGE, we leave everything to the caller (it must do
    2317                 :             :          * additional rechecking, and might end up executing a different
    2318                 :             :          * action entirely).
    2319                 :             :          */
    2320         [ +  + ]:          50 :         if (mtstate->operation == CMD_MERGE)
    2321                 :          24 :             return *tmresult == TM_Ok;
    2322   [ +  +  -  + ]:          26 :         else if (TupIsNull(epqslot))
    2323                 :          23 :             return true;
    2324                 :             :         else
    2325                 :             :         {
    2326                 :             :             /* Fetch the most recent version of old tuple. */
    2327                 :             :             TupleTableSlot *oldSlot;
    2328                 :             : 
    2329                 :             :             /* ... but first, make sure ri_oldTupleSlot is initialized. */
    2330         [ -  + ]:           3 :             if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
    2331                 :           0 :                 ExecInitUpdateProjection(mtstate, resultRelInfo);
    2332                 :           3 :             oldSlot = resultRelInfo->ri_oldTupleSlot;
    2333         [ -  + ]:           3 :             if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
    2334                 :             :                                                tupleid,
    2335                 :             :                                                SnapshotAny,
    2336                 :             :                                                oldSlot))
    2337         [ #  # ]:           0 :                 elog(ERROR, "failed to fetch tuple being updated");
    2338                 :             :             /* and project the new tuple to retry the UPDATE with */
    2339                 :           3 :             *retry_slot = ExecGetUpdateNewTuple(resultRelInfo, epqslot,
    2340                 :             :                                                 oldSlot);
    2341                 :           3 :             return false;
    2342                 :             :         }
    2343                 :             :     }
    2344                 :             : 
    2345                 :             :     /*
    2346                 :             :      * resultRelInfo is one of the per-relation resultRelInfos.  So we should
    2347                 :             :      * convert the tuple into root's tuple descriptor if needed, since
    2348                 :             :      * ExecInsert() starts the search from root.
    2349                 :             :      */
    2350                 :         666 :     tupconv_map = ExecGetChildToRootMap(resultRelInfo);
    2351         [ +  + ]:         666 :     if (tupconv_map != NULL)
    2352                 :         217 :         slot = execute_attr_map_slot(tupconv_map->attrMap,
    2353                 :             :                                      slot,
    2354                 :             :                                      mtstate->mt_root_tuple_slot);
    2355                 :             : 
    2356                 :             :     /* Tuple routing starts from the root table. */
    2357                 :         583 :     context->cpUpdateReturningSlot =
    2358                 :         666 :         ExecInsert(context, mtstate->rootResultRelInfo, slot, canSetTag,
    2359                 :             :                    inserted_tuple, insert_destrel);
    2360                 :             : 
    2361                 :             :     /*
    2362                 :             :      * Reset the transition state that may possibly have been written by
    2363                 :             :      * INSERT.
    2364                 :             :      */
    2365         [ +  + ]:         583 :     if (mtstate->mt_transition_capture)
    2366                 :          36 :         mtstate->mt_transition_capture->tcs_original_insert_tuple = NULL;
    2367                 :             : 
    2368                 :             :     /* We're done moving. */
    2369                 :         583 :     return true;
    2370                 :             : }
    2371                 :             : 
    2372                 :             : /*
    2373                 :             :  * ExecUpdatePrologue -- subroutine for ExecUpdate
    2374                 :             :  *
    2375                 :             :  * Prepare executor state for UPDATE.  This includes running BEFORE ROW
    2376                 :             :  * triggers.  We return false if one of them makes the update a no-op;
    2377                 :             :  * otherwise, return true.
    2378                 :             :  */
    2379                 :             : static bool
    2380                 :     2213570 : ExecUpdatePrologue(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    2381                 :             :                    ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
    2382                 :             :                    TM_Result *result)
    2383                 :             : {
    2384                 :     2213570 :     Relation    resultRelationDesc = resultRelInfo->ri_RelationDesc;
    2385                 :             : 
    2386         [ +  + ]:     2213570 :     if (result)
    2387                 :        1416 :         *result = TM_Ok;
    2388                 :             : 
    2389                 :     2213570 :     ExecMaterializeSlot(slot);
    2390                 :             : 
    2391                 :             :     /*
    2392                 :             :      * Open the table's indexes, if we have not done so already, so that we
    2393                 :             :      * can add new index entries for the updated tuple.
    2394                 :             :      */
    2395         [ +  + ]:     2213570 :     if (resultRelationDesc->rd_rel->relhasindex &&
    2396         [ +  + ]:      146428 :         resultRelInfo->ri_IndexRelationDescs == NULL)
    2397                 :        5796 :         ExecOpenIndices(resultRelInfo, false);
    2398                 :             : 
    2399                 :             :     /* BEFORE ROW UPDATE triggers */
    2400         [ +  + ]:     2213570 :     if (resultRelInfo->ri_TrigDesc &&
    2401         [ +  + ]:        4020 :         resultRelInfo->ri_TrigDesc->trig_update_before_row)
    2402                 :             :     {
    2403                 :             :         /* Flush any pending inserts, so rows are visible to the triggers */
    2404         [ +  + ]:        1584 :         if (context->estate->es_insert_pending_result_relations != NIL)
    2405                 :           1 :             ExecPendingInserts(context->estate);
    2406                 :             : 
    2407                 :        1572 :         return ExecBRUpdateTriggers(context->estate, context->epqstate,
    2408                 :             :                                     resultRelInfo, tupleid, oldtuple, slot,
    2409                 :             :                                     result, &context->tmfd,
    2410                 :        1584 :                                     context->mtstate->operation == CMD_MERGE);
    2411                 :             :     }
    2412                 :             : 
    2413                 :     2211986 :     return true;
    2414                 :             : }
    2415                 :             : 
    2416                 :             : /*
    2417                 :             :  * ExecUpdatePrepareSlot -- subroutine for ExecUpdateAct
    2418                 :             :  *
    2419                 :             :  * Apply the final modifications to the tuple slot before the update.
    2420                 :             :  * (This is split out because we also need it in the foreign-table code path.)
    2421                 :             :  */
    2422                 :             : static void
    2423                 :     2213384 : ExecUpdatePrepareSlot(ResultRelInfo *resultRelInfo,
    2424                 :             :                       TupleTableSlot *slot,
    2425                 :             :                       EState *estate)
    2426                 :             : {
    2427                 :     2213384 :     Relation    resultRelationDesc = resultRelInfo->ri_RelationDesc;
    2428                 :             : 
    2429                 :             :     /*
    2430                 :             :      * Constraints and GENERATED expressions might reference the tableoid
    2431                 :             :      * column, so (re-)initialize tts_tableOid before evaluating them.
    2432                 :             :      */
    2433                 :     2213384 :     slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
    2434                 :             : 
    2435                 :             :     /*
    2436                 :             :      * Compute stored generated columns
    2437                 :             :      */
    2438         [ +  + ]:     2213384 :     if (resultRelationDesc->rd_att->constr &&
    2439         [ +  + ]:      123478 :         resultRelationDesc->rd_att->constr->has_generated_stored)
    2440                 :         206 :         ExecComputeStoredGenerated(resultRelInfo, estate, slot,
    2441                 :             :                                    CMD_UPDATE);
    2442                 :     2213384 : }
    2443                 :             : 
    2444                 :             : /*
    2445                 :             :  * ExecUpdateAct -- subroutine for ExecUpdate
    2446                 :             :  *
    2447                 :             :  * Actually update the tuple, when operating on a plain table.  If the
    2448                 :             :  * table is a partition, and the command was called referencing an ancestor
    2449                 :             :  * partitioned table, this routine migrates the resulting tuple to another
    2450                 :             :  * partition.
    2451                 :             :  *
    2452                 :             :  * The caller is in charge of keeping indexes current as necessary.  The
    2453                 :             :  * caller is also in charge of doing EvalPlanQual if the tuple is found to
    2454                 :             :  * be concurrently updated.  However, in case of a cross-partition update,
    2455                 :             :  * this routine does it.
    2456                 :             :  */
    2457                 :             : static TM_Result
    2458                 :     2213284 : ExecUpdateAct(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    2459                 :             :               ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *slot,
    2460                 :             :               bool canSetTag, UpdateContext *updateCxt)
    2461                 :             : {
    2462                 :     2213284 :     EState     *estate = context->estate;
    2463                 :     2213284 :     Relation    resultRelationDesc = resultRelInfo->ri_RelationDesc;
    2464                 :             :     bool        partition_constraint_failed;
    2465                 :             :     TM_Result   result;
    2466                 :             : 
    2467                 :     2213284 :     updateCxt->crossPartUpdate = false;
    2468                 :             : 
    2469                 :             :     /*
    2470                 :             :      * If we move the tuple to a new partition, we loop back here to recompute
    2471                 :             :      * GENERATED values (which are allowed to be different across partitions)
    2472                 :             :      * and recheck any RLS policies and constraints.  We do not fire any
    2473                 :             :      * BEFORE triggers of the new partition, however.
    2474                 :             :      */
    2475                 :     2213287 : lreplace:
    2476                 :             :     /* Fill in GENERATEd columns */
    2477                 :     2213287 :     ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
    2478                 :             : 
    2479                 :             :     /* ensure slot is independent, consider e.g. EPQ */
    2480                 :     2213287 :     ExecMaterializeSlot(slot);
    2481                 :             : 
    2482                 :             :     /*
    2483                 :             :      * If partition constraint fails, this row might get moved to another
    2484                 :             :      * partition, in which case we should check the RLS CHECK policy just
    2485                 :             :      * before inserting into the new partition, rather than doing it here.
    2486                 :             :      * This is because a trigger on that partition might again change the row.
    2487                 :             :      * So skip the WCO checks if the partition constraint fails.
    2488                 :             :      */
    2489                 :     2213287 :     partition_constraint_failed =
    2490         [ +  + ]:     2215128 :         resultRelationDesc->rd_rel->relispartition &&
    2491         [ +  + ]:        1841 :         !ExecPartitionCheck(resultRelInfo, slot, estate, false);
    2492                 :             : 
    2493                 :             :     /* Check any RLS UPDATE WITH CHECK policies */
    2494         [ +  + ]:     2213287 :     if (!partition_constraint_failed &&
    2495         [ +  + ]:     2212536 :         resultRelInfo->ri_WithCheckOptions != NIL)
    2496                 :             :     {
    2497                 :             :         /*
    2498                 :             :          * ExecWithCheckOptions() will skip any WCOs which are not of the kind
    2499                 :             :          * we are looking for at this point.
    2500                 :             :          */
    2501                 :         376 :         ExecWithCheckOptions(WCO_RLS_UPDATE_CHECK,
    2502                 :             :                              resultRelInfo, slot, estate);
    2503                 :             :     }
    2504                 :             : 
    2505                 :             :     /*
    2506                 :             :      * If a partition check failed, try to move the row into the right
    2507                 :             :      * partition.
    2508                 :             :      */
    2509         [ +  + ]:     2213251 :     if (partition_constraint_failed)
    2510                 :             :     {
    2511                 :             :         TupleTableSlot *inserted_tuple,
    2512                 :             :                    *retry_slot;
    2513                 :         751 :         ResultRelInfo *insert_destrel = NULL;
    2514                 :             : 
    2515                 :             :         /*
    2516                 :             :          * ExecCrossPartitionUpdate will first DELETE the row from the
    2517                 :             :          * partition it's currently in and then insert it back into the root
    2518                 :             :          * table, which will re-route it to the correct partition.  However,
    2519                 :             :          * if the tuple has been concurrently updated, a retry is needed.
    2520                 :             :          */
    2521         [ +  + ]:         751 :         if (ExecCrossPartitionUpdate(context, resultRelInfo,
    2522                 :             :                                      tupleid, oldtuple, slot,
    2523                 :             :                                      canSetTag, updateCxt,
    2524                 :             :                                      &result,
    2525                 :             :                                      &retry_slot,
    2526                 :             :                                      &inserted_tuple,
    2527                 :             :                                      &insert_destrel))
    2528                 :             :         {
    2529                 :             :             /* success! */
    2530                 :         622 :             updateCxt->crossPartUpdate = true;
    2531                 :             : 
    2532                 :             :             /*
    2533                 :             :              * If the partitioned table being updated is referenced in foreign
    2534                 :             :              * keys, queue up trigger events to check that none of them were
    2535                 :             :              * violated.  No special treatment is needed in
    2536                 :             :              * non-cross-partition update situations, because the leaf
    2537                 :             :              * partition's AR update triggers will take care of that.  During
    2538                 :             :              * cross-partition updates implemented as delete on the source
    2539                 :             :              * partition followed by insert on the destination partition,
    2540                 :             :              * AR-UPDATE triggers of the root table (that is, the table
    2541                 :             :              * mentioned in the query) must be fired.
    2542                 :             :              *
    2543                 :             :              * NULL insert_destrel means that the move failed to occur, that
    2544                 :             :              * is, the update failed, so no need to anything in that case.
    2545                 :             :              */
    2546         [ +  + ]:         622 :             if (insert_destrel &&
    2547         [ +  + ]:         565 :                 resultRelInfo->ri_TrigDesc &&
    2548         [ +  + ]:         242 :                 resultRelInfo->ri_TrigDesc->trig_update_after_row)
    2549                 :         202 :                 ExecCrossPartitionUpdateForeignKey(context,
    2550                 :             :                                                    resultRelInfo,
    2551                 :             :                                                    insert_destrel,
    2552                 :             :                                                    tupleid, slot,
    2553                 :             :                                                    inserted_tuple);
    2554                 :             : 
    2555                 :         626 :             return TM_Ok;
    2556                 :             :         }
    2557                 :             : 
    2558                 :             :         /*
    2559                 :             :          * No luck, a retry is needed.  If running MERGE, we do not do so
    2560                 :             :          * here; instead let it handle that on its own rules.
    2561                 :             :          */
    2562         [ +  + ]:          11 :         if (context->mtstate->operation == CMD_MERGE)
    2563                 :           8 :             return result;
    2564                 :             : 
    2565                 :             :         /*
    2566                 :             :          * ExecCrossPartitionUpdate installed an updated version of the new
    2567                 :             :          * tuple in the retry slot; start over.
    2568                 :             :          */
    2569                 :           3 :         slot = retry_slot;
    2570                 :           3 :         goto lreplace;
    2571                 :             :     }
    2572                 :             : 
    2573                 :             :     /*
    2574                 :             :      * Check the constraints of the tuple.  We've already checked the
    2575                 :             :      * partition constraint above; however, we must still ensure the tuple
    2576                 :             :      * passes all other constraints, so we will call ExecConstraints() and
    2577                 :             :      * have it validate all remaining checks.
    2578                 :             :      */
    2579         [ +  + ]:     2212500 :     if (resultRelationDesc->rd_att->constr)
    2580                 :      123072 :         ExecConstraints(resultRelInfo, slot, estate);
    2581                 :             : 
    2582                 :             :     /*
    2583                 :             :      * replace the heap tuple
    2584                 :             :      *
    2585                 :             :      * Note: if es_crosscheck_snapshot isn't InvalidSnapshot, we check that
    2586                 :             :      * the row to be updated is visible to that snapshot, and throw a
    2587                 :             :      * can't-serialize error if not. This is a special-case behavior needed
    2588                 :             :      * for referential integrity updates in transaction-snapshot mode
    2589                 :             :      * transactions.
    2590                 :             :      */
    2591                 :     2212444 :     result = table_tuple_update(resultRelationDesc, tupleid, slot,
    2592                 :             :                                 estate->es_output_cid,
    2593                 :             :                                 0,
    2594                 :             :                                 estate->es_snapshot,
    2595                 :             :                                 estate->es_crosscheck_snapshot,
    2596                 :             :                                 true /* wait for commit */ ,
    2597                 :             :                                 &context->tmfd, &updateCxt->lockmode,
    2598                 :             :                                 &updateCxt->updateIndexes);
    2599                 :             : 
    2600                 :     2212432 :     return result;
    2601                 :             : }
    2602                 :             : 
    2603                 :             : /*
    2604                 :             :  * ExecUpdateEpilogue -- subroutine for ExecUpdate
    2605                 :             :  *
    2606                 :             :  * Closing steps of updating a tuple.  Must be called if ExecUpdateAct
    2607                 :             :  * returns indicating that the tuple was updated. It also inserts temporal
    2608                 :             :  * leftovers from an UPDATE FOR PORTION OF.
    2609                 :             :  */
    2610                 :             : static void
    2611                 :     2212433 : ExecUpdateEpilogue(ModifyTableContext *context, UpdateContext *updateCxt,
    2612                 :             :                    ResultRelInfo *resultRelInfo, ItemPointer tupleid,
    2613                 :             :                    HeapTuple oldtuple, TupleTableSlot *slot)
    2614                 :             : {
    2615                 :     2212433 :     ModifyTableState *mtstate = context->mtstate;
    2616                 :     2212433 :     List       *recheckIndexes = NIL;
    2617                 :             : 
    2618                 :             :     /* insert index entries for tuple if necessary */
    2619   [ +  +  +  + ]:     2212433 :     if (resultRelInfo->ri_NumIndices > 0 && (updateCxt->updateIndexes != TU_None))
    2620                 :             :     {
    2621                 :      115755 :         uint32      flags = EIIT_IS_UPDATE;
    2622                 :             : 
    2623         [ +  + ]:      115755 :         if (updateCxt->updateIndexes == TU_Summarizing)
    2624                 :        2188 :             flags |= EIIT_ONLY_SUMMARIZING;
    2625                 :      115755 :         recheckIndexes = ExecInsertIndexTuples(resultRelInfo, context->estate,
    2626                 :             :                                                flags, slot, NIL,
    2627                 :             :                                                NULL);
    2628                 :             :     }
    2629                 :             : 
    2630                 :             :     /* Compute temporal leftovers in FOR PORTION OF */
    2631         [ +  + ]:     2212373 :     if (((ModifyTable *) context->mtstate->ps.plan)->forPortionOf)
    2632                 :         503 :         ExecForPortionOfLeftovers(context, context->estate, resultRelInfo, tupleid);
    2633                 :             : 
    2634                 :             :     /* AFTER ROW UPDATE Triggers */
    2635                 :     2212345 :     ExecARUpdateTriggers(context->estate, resultRelInfo,
    2636                 :             :                          NULL, NULL,
    2637                 :             :                          tupleid, oldtuple, slot,
    2638                 :             :                          recheckIndexes,
    2639         [ +  + ]:     2212345 :                          mtstate->operation == CMD_INSERT ?
    2640                 :             :                          mtstate->mt_oc_transition_capture :
    2641                 :             :                          mtstate->mt_transition_capture,
    2642                 :             :                          false);
    2643                 :             : 
    2644                 :     2212343 :     list_free(recheckIndexes);
    2645                 :             : 
    2646                 :             :     /*
    2647                 :             :      * Check any WITH CHECK OPTION constraints from parent views.  We are
    2648                 :             :      * required to do this after testing all constraints and uniqueness
    2649                 :             :      * violations per the SQL spec, so we do it after actually updating the
    2650                 :             :      * record in the heap and all indexes.
    2651                 :             :      *
    2652                 :             :      * ExecWithCheckOptions() will skip any WCOs which are not of the kind we
    2653                 :             :      * are looking for at this point.
    2654                 :             :      */
    2655         [ +  + ]:     2212343 :     if (resultRelInfo->ri_WithCheckOptions != NIL)
    2656                 :         349 :         ExecWithCheckOptions(WCO_VIEW_CHECK, resultRelInfo,
    2657                 :             :                              slot, context->estate);
    2658                 :     2212289 : }
    2659                 :             : 
    2660                 :             : /*
    2661                 :             :  * Queues up an update event using the target root partitioned table's
    2662                 :             :  * trigger to check that a cross-partition update hasn't broken any foreign
    2663                 :             :  * keys pointing into it.
    2664                 :             :  */
    2665                 :             : static void
    2666                 :         202 : ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context,
    2667                 :             :                                    ResultRelInfo *sourcePartInfo,
    2668                 :             :                                    ResultRelInfo *destPartInfo,
    2669                 :             :                                    ItemPointer tupleid,
    2670                 :             :                                    TupleTableSlot *oldslot,
    2671                 :             :                                    TupleTableSlot *newslot)
    2672                 :             : {
    2673                 :             :     ListCell   *lc;
    2674                 :             :     ResultRelInfo *rootRelInfo;
    2675                 :             :     List       *ancestorRels;
    2676                 :             : 
    2677                 :         202 :     rootRelInfo = sourcePartInfo->ri_RootResultRelInfo;
    2678                 :         202 :     ancestorRels = ExecGetAncestorResultRels(context->estate, sourcePartInfo);
    2679                 :             : 
    2680                 :             :     /*
    2681                 :             :      * For any foreign keys that point directly into a non-root ancestors of
    2682                 :             :      * the source partition, we can in theory fire an update event to enforce
    2683                 :             :      * those constraints using their triggers, if we could tell that both the
    2684                 :             :      * source and the destination partitions are under the same ancestor. But
    2685                 :             :      * for now, we simply report an error that those cannot be enforced.
    2686                 :             :      */
    2687   [ +  -  +  +  :         440 :     foreach(lc, ancestorRels)
                   +  + ]
    2688                 :             :     {
    2689                 :         242 :         ResultRelInfo *rInfo = lfirst(lc);
    2690                 :         242 :         TriggerDesc *trigdesc = rInfo->ri_TrigDesc;
    2691                 :         242 :         bool        has_noncloned_fkey = false;
    2692                 :             : 
    2693                 :             :         /* Root ancestor's triggers will be processed. */
    2694         [ +  + ]:         242 :         if (rInfo == rootRelInfo)
    2695                 :         198 :             continue;
    2696                 :             : 
    2697   [ +  -  +  - ]:          44 :         if (trigdesc && trigdesc->trig_update_after_row)
    2698                 :             :         {
    2699         [ +  + ]:         152 :             for (int i = 0; i < trigdesc->numtriggers; i++)
    2700                 :             :             {
    2701                 :         112 :                 Trigger    *trig = &trigdesc->triggers[i];
    2702                 :             : 
    2703   [ +  +  +  - ]:         116 :                 if (!trig->tgisclone &&
    2704                 :           4 :                     RI_FKey_trigger_type(trig->tgfoid) == RI_TRIGGER_PK)
    2705                 :             :                 {
    2706                 :           4 :                     has_noncloned_fkey = true;
    2707                 :           4 :                     break;
    2708                 :             :                 }
    2709                 :             :             }
    2710                 :             :         }
    2711                 :             : 
    2712         [ +  + ]:          44 :         if (has_noncloned_fkey)
    2713         [ +  - ]:           4 :             ereport(ERROR,
    2714                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2715                 :             :                      errmsg("cannot move tuple across partitions when a non-root ancestor of the source partition is directly referenced in a foreign key"),
    2716                 :             :                      errdetail("A foreign key points to ancestor \"%s\" but not the root ancestor \"%s\".",
    2717                 :             :                                RelationGetRelationName(rInfo->ri_RelationDesc),
    2718                 :             :                                RelationGetRelationName(rootRelInfo->ri_RelationDesc)),
    2719                 :             :                      errhint("Consider defining the foreign key on table \"%s\".",
    2720                 :             :                              RelationGetRelationName(rootRelInfo->ri_RelationDesc))));
    2721                 :             :     }
    2722                 :             : 
    2723                 :             :     /* Perform the root table's triggers. */
    2724                 :         198 :     ExecARUpdateTriggers(context->estate,
    2725                 :             :                          rootRelInfo, sourcePartInfo, destPartInfo,
    2726                 :             :                          tupleid, NULL, newslot, NIL, NULL, true);
    2727                 :         198 : }
    2728                 :             : 
    2729                 :             : /* ----------------------------------------------------------------
    2730                 :             :  *      ExecUpdate
    2731                 :             :  *
    2732                 :             :  *      note: we can't run UPDATE queries with transactions
    2733                 :             :  *      off because UPDATEs are actually INSERTs and our
    2734                 :             :  *      scan will mistakenly loop forever, updating the tuple
    2735                 :             :  *      it just inserted..  This should be fixed but until it
    2736                 :             :  *      is, we don't want to get stuck in an infinite loop
    2737                 :             :  *      which corrupts your database..
    2738                 :             :  *
    2739                 :             :  *      When updating a table, tupleid identifies the tuple to update and
    2740                 :             :  *      oldtuple is NULL.  When updating through a view INSTEAD OF trigger,
    2741                 :             :  *      oldtuple is passed to the triggers and identifies what to update, and
    2742                 :             :  *      tupleid is invalid.  When updating a foreign table, tupleid is
    2743                 :             :  *      invalid; the FDW has to figure out which row to update using data from
    2744                 :             :  *      the planSlot.  oldtuple is passed to foreign table triggers; it is
    2745                 :             :  *      NULL when the foreign table has no relevant triggers.
    2746                 :             :  *
    2747                 :             :  *      oldSlot contains the old tuple value.
    2748                 :             :  *      slot contains the new tuple value to be stored.
    2749                 :             :  *      planSlot is the output of the ModifyTable's subplan; we use it
    2750                 :             :  *      to access values from other input tables (for RETURNING),
    2751                 :             :  *      row-ID junk columns, etc.
    2752                 :             :  *
    2753                 :             :  *      Returns RETURNING result if any, otherwise NULL.  On exit, if tupleid
    2754                 :             :  *      had identified the tuple to update, it will identify the tuple
    2755                 :             :  *      actually updated after EvalPlanQual.
    2756                 :             :  * ----------------------------------------------------------------
    2757                 :             :  */
    2758                 :             : static TupleTableSlot *
    2759                 :     2212154 : ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    2760                 :             :            ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot,
    2761                 :             :            TupleTableSlot *slot, bool canSetTag)
    2762                 :             : {
    2763                 :     2212154 :     EState     *estate = context->estate;
    2764                 :     2212154 :     Relation    resultRelationDesc = resultRelInfo->ri_RelationDesc;
    2765                 :     2212154 :     UpdateContext updateCxt = {0};
    2766                 :             :     TM_Result   result;
    2767                 :             : 
    2768                 :             :     /*
    2769                 :             :      * abort the operation if not running transactions
    2770                 :             :      */
    2771         [ -  + ]:     2212154 :     if (IsBootstrapProcessingMode())
    2772         [ #  # ]:           0 :         elog(ERROR, "cannot UPDATE during bootstrap");
    2773                 :             : 
    2774                 :             :     /*
    2775                 :             :      * Prepare for the update.  This includes BEFORE ROW triggers, so we're
    2776                 :             :      * done if it says we are.
    2777                 :             :      */
    2778                 :     2212154 :     context->tmfd.traversed = false;
    2779         [ +  + ]:     2212154 :     if (!ExecUpdatePrologue(context, resultRelInfo, tupleid, oldtuple, slot, NULL))
    2780                 :          85 :         return NULL;
    2781                 :             : 
    2782                 :             :     /*
    2783                 :             :      * If the target tuple was concurrently updated, the trigger code will
    2784                 :             :      * have done EPQ and updated tupleid, following the update chain.  In this
    2785                 :             :      * case, we must fetch the most recent version of old tuple for the
    2786                 :             :      * benefit of RETURNING.  Technically, we could get away with not doing
    2787                 :             :      * this, if there is no RETURNING clause, or it doesn't refer to OLD, but
    2788                 :             :      * it seems preferable to always ensure that the contents of oldSlot are
    2789                 :             :      * correct.
    2790                 :             :      */
    2791         [ +  + ]:     2212057 :     if (context->tmfd.traversed)
    2792                 :             :     {
    2793         [ -  + ]:           3 :         if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
    2794                 :             :                                            tupleid,
    2795                 :             :                                            SnapshotAny,
    2796                 :             :                                            oldSlot))
    2797         [ #  # ]:           0 :             elog(ERROR, "failed to re-fetch tuple updated during trigger execution");
    2798                 :             :     }
    2799                 :             : 
    2800                 :             :     /* INSTEAD OF ROW UPDATE Triggers */
    2801         [ +  + ]:     2212057 :     if (resultRelInfo->ri_TrigDesc &&
    2802         [ +  + ]:        3681 :         resultRelInfo->ri_TrigDesc->trig_update_instead_row)
    2803                 :             :     {
    2804         [ +  + ]:          83 :         if (!ExecIRUpdateTriggers(estate, resultRelInfo,
    2805                 :             :                                   oldtuple, slot))
    2806                 :          12 :             return NULL;        /* "do nothing" */
    2807                 :             :     }
    2808         [ +  + ]:     2211974 :     else if (resultRelInfo->ri_FdwRoutine)
    2809                 :             :     {
    2810                 :             :         /* Fill in GENERATEd columns */
    2811                 :          97 :         ExecUpdatePrepareSlot(resultRelInfo, slot, estate);
    2812                 :             : 
    2813                 :             :         /*
    2814                 :             :          * update in foreign table: let the FDW do it
    2815                 :             :          */
    2816                 :          97 :         slot = resultRelInfo->ri_FdwRoutine->ExecForeignUpdate(estate,
    2817                 :             :                                                                resultRelInfo,
    2818                 :             :                                                                slot,
    2819                 :             :                                                                context->planSlot);
    2820                 :             : 
    2821         [ +  + ]:          97 :         if (slot == NULL)       /* "do nothing" */
    2822                 :           1 :             return NULL;
    2823                 :             : 
    2824                 :             :         /*
    2825                 :             :          * AFTER ROW Triggers or RETURNING expressions might reference the
    2826                 :             :          * tableoid column, so (re-)initialize tts_tableOid before evaluating
    2827                 :             :          * them.  (This covers the case where the FDW replaced the slot.)
    2828                 :             :          */
    2829                 :          96 :         slot->tts_tableOid = RelationGetRelid(resultRelationDesc);
    2830                 :             :     }
    2831                 :             :     else
    2832                 :             :     {
    2833                 :             :         ItemPointerData lockedtid;
    2834                 :             : 
    2835                 :             :         /*
    2836                 :             :          * If we generate a new candidate tuple after EvalPlanQual testing, we
    2837                 :             :          * must loop back here to try again.  (We don't need to redo triggers,
    2838                 :             :          * however.  If there are any BEFORE triggers then trigger.c will have
    2839                 :             :          * done table_tuple_lock to lock the correct tuple, so there's no need
    2840                 :             :          * to do them again.)
    2841                 :             :          */
    2842                 :     2211877 : redo_act:
    2843                 :     2211932 :         lockedtid = *tupleid;
    2844                 :     2211932 :         result = ExecUpdateAct(context, resultRelInfo, tupleid, oldtuple, slot,
    2845                 :             :                                canSetTag, &updateCxt);
    2846                 :             : 
    2847                 :             :         /*
    2848                 :             :          * If ExecUpdateAct reports that a cross-partition update was done,
    2849                 :             :          * then the RETURNING tuple (if any) has been projected and there's
    2850                 :             :          * nothing else for us to do.
    2851                 :             :          */
    2852         [ +  + ]:     2211721 :         if (updateCxt.crossPartUpdate)
    2853                 :         616 :             return context->cpUpdateReturningSlot;
    2854                 :             : 
    2855   [ +  +  +  +  :     2211192 :         switch (result)
                      - ]
    2856                 :             :         {
    2857                 :          60 :             case TM_SelfModified:
    2858                 :             : 
    2859                 :             :                 /*
    2860                 :             :                  * The target tuple was already updated or deleted by the
    2861                 :             :                  * current command, or by a later command in the current
    2862                 :             :                  * transaction.  The former case is possible in a join UPDATE
    2863                 :             :                  * where multiple tuples join to the same target tuple. This
    2864                 :             :                  * is pretty questionable, but Postgres has always allowed it:
    2865                 :             :                  * we just execute the first update action and ignore
    2866                 :             :                  * additional update attempts.
    2867                 :             :                  *
    2868                 :             :                  * The latter case arises if the tuple is modified by a
    2869                 :             :                  * command in a BEFORE trigger, or perhaps by a command in a
    2870                 :             :                  * volatile function used in the query.  In such situations we
    2871                 :             :                  * should not ignore the update, but it is equally unsafe to
    2872                 :             :                  * proceed.  We don't want to discard the original UPDATE
    2873                 :             :                  * while keeping the triggered actions based on it; and we
    2874                 :             :                  * have no principled way to merge this update with the
    2875                 :             :                  * previous ones.  So throwing an error is the only safe
    2876                 :             :                  * course.
    2877                 :             :                  *
    2878                 :             :                  * If a trigger actually intends this type of interaction, it
    2879                 :             :                  * can re-execute the UPDATE (assuming it can figure out how)
    2880                 :             :                  * and then return NULL to cancel the outer update.
    2881                 :             :                  */
    2882         [ +  + ]:          60 :                 if (context->tmfd.cmax != estate->es_output_cid)
    2883         [ +  - ]:           4 :                     ereport(ERROR,
    2884                 :             :                             (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    2885                 :             :                              errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
    2886                 :             :                              errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    2887                 :             : 
    2888                 :             :                 /* Else, already updated by self; nothing to do */
    2889                 :          56 :                 return NULL;
    2890                 :             : 
    2891                 :     2211023 :             case TM_Ok:
    2892                 :     2211023 :                 break;
    2893                 :             : 
    2894                 :          93 :             case TM_Updated:
    2895                 :             :                 {
    2896                 :             :                     TupleTableSlot *inputslot;
    2897                 :             :                     TupleTableSlot *epqslot;
    2898                 :             : 
    2899         [ +  + ]:          93 :                     if (IsolationUsesXactSnapshot())
    2900         [ +  - ]:          11 :                         ereport(ERROR,
    2901                 :             :                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    2902                 :             :                                  errmsg("could not serialize access due to concurrent update")));
    2903                 :             : 
    2904                 :             :                     /*
    2905                 :             :                      * Already know that we're going to need to do EPQ, so
    2906                 :             :                      * fetch tuple directly into the right slot.
    2907                 :             :                      */
    2908                 :          82 :                     inputslot = EvalPlanQualSlot(context->epqstate, resultRelationDesc,
    2909                 :             :                                                  resultRelInfo->ri_RangeTableIndex);
    2910                 :             : 
    2911                 :          82 :                     result = table_tuple_lock(resultRelationDesc, tupleid,
    2912                 :             :                                               estate->es_snapshot,
    2913                 :             :                                               inputslot, estate->es_output_cid,
    2914                 :             :                                               updateCxt.lockmode, LockWaitBlock,
    2915                 :             :                                               TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
    2916                 :             :                                               &context->tmfd);
    2917                 :             : 
    2918   [ +  +  +  - ]:          80 :                     switch (result)
    2919                 :             :                     {
    2920                 :          75 :                         case TM_Ok:
    2921                 :             :                             Assert(context->tmfd.traversed);
    2922                 :             : 
    2923                 :          75 :                             epqslot = EvalPlanQual(context->epqstate,
    2924                 :             :                                                    resultRelationDesc,
    2925                 :             :                                                    resultRelInfo->ri_RangeTableIndex,
    2926                 :             :                                                    inputslot);
    2927   [ +  +  +  + ]:          75 :                             if (TupIsNull(epqslot))
    2928                 :             :                                 /* Tuple not passing quals anymore, exiting... */
    2929                 :          20 :                                 return NULL;
    2930                 :             : 
    2931                 :             :                             /* Make sure ri_oldTupleSlot is initialized. */
    2932         [ -  + ]:          55 :                             if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
    2933                 :           0 :                                 ExecInitUpdateProjection(context->mtstate,
    2934                 :             :                                                          resultRelInfo);
    2935                 :             : 
    2936         [ +  + ]:          55 :                             if (resultRelInfo->ri_needLockTagTuple)
    2937                 :             :                             {
    2938                 :           1 :                                 UnlockTuple(resultRelationDesc,
    2939                 :             :                                             &lockedtid, InplaceUpdateTupleLock);
    2940                 :           1 :                                 LockTuple(resultRelationDesc,
    2941                 :             :                                           tupleid, InplaceUpdateTupleLock);
    2942                 :             :                             }
    2943                 :             : 
    2944                 :             :                             /* Fetch the most recent version of old tuple. */
    2945                 :          55 :                             oldSlot = resultRelInfo->ri_oldTupleSlot;
    2946         [ -  + ]:          55 :                             if (!table_tuple_fetch_row_version(resultRelationDesc,
    2947                 :             :                                                                tupleid,
    2948                 :             :                                                                SnapshotAny,
    2949                 :             :                                                                oldSlot))
    2950         [ #  # ]:           0 :                                 elog(ERROR, "failed to fetch tuple being updated");
    2951                 :          55 :                             slot = ExecGetUpdateNewTuple(resultRelInfo,
    2952                 :             :                                                          epqslot, oldSlot);
    2953                 :          55 :                             goto redo_act;
    2954                 :             : 
    2955                 :           1 :                         case TM_Deleted:
    2956                 :             :                             /* tuple already deleted; nothing to do */
    2957                 :           1 :                             return NULL;
    2958                 :             : 
    2959                 :           4 :                         case TM_SelfModified:
    2960                 :             : 
    2961                 :             :                             /*
    2962                 :             :                              * This can be reached when following an update
    2963                 :             :                              * chain from a tuple updated by another session,
    2964                 :             :                              * reaching a tuple that was already updated in
    2965                 :             :                              * this transaction. If previously modified by
    2966                 :             :                              * this command, ignore the redundant update,
    2967                 :             :                              * otherwise error out.
    2968                 :             :                              *
    2969                 :             :                              * See also TM_SelfModified response to
    2970                 :             :                              * table_tuple_update() above.
    2971                 :             :                              */
    2972         [ +  + ]:           4 :                             if (context->tmfd.cmax != estate->es_output_cid)
    2973         [ +  - ]:           1 :                                 ereport(ERROR,
    2974                 :             :                                         (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    2975                 :             :                                          errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
    2976                 :             :                                          errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    2977                 :           3 :                             return NULL;
    2978                 :             : 
    2979                 :           0 :                         default:
    2980                 :             :                             /* see table_tuple_lock call in ExecDelete() */
    2981         [ #  # ]:           0 :                             elog(ERROR, "unexpected table_tuple_lock status: %u",
    2982                 :             :                                  result);
    2983                 :             :                             return NULL;
    2984                 :             :                     }
    2985                 :             :                 }
    2986                 :             : 
    2987                 :             :                 break;
    2988                 :             : 
    2989                 :          16 :             case TM_Deleted:
    2990         [ +  + ]:          16 :                 if (IsolationUsesXactSnapshot())
    2991         [ +  - ]:           9 :                     ereport(ERROR,
    2992                 :             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    2993                 :             :                              errmsg("could not serialize access due to concurrent delete")));
    2994                 :             :                 /* tuple already deleted; nothing to do */
    2995                 :           7 :                 return NULL;
    2996                 :             : 
    2997                 :           0 :             default:
    2998         [ #  # ]:           0 :                 elog(ERROR, "unrecognized table_tuple_update status: %u",
    2999                 :             :                      result);
    3000                 :             :                 return NULL;
    3001                 :             :         }
    3002                 :             :     }
    3003                 :             : 
    3004         [ +  + ]:     2211182 :     if (canSetTag)
    3005                 :     2210765 :         (estate->es_processed)++;
    3006                 :             : 
    3007                 :     2211182 :     ExecUpdateEpilogue(context, &updateCxt, resultRelInfo, tupleid, oldtuple,
    3008                 :             :                        slot);
    3009                 :             : 
    3010                 :             :     /* Process RETURNING if present */
    3011         [ +  + ]:     2211046 :     if (resultRelInfo->ri_projectReturning)
    3012                 :        1522 :         return ExecProcessReturning(context, resultRelInfo, false,
    3013                 :             :                                     oldSlot, slot, context->planSlot);
    3014                 :             : 
    3015                 :     2209524 :     return NULL;
    3016                 :             : }
    3017                 :             : 
    3018                 :             : /*
    3019                 :             :  * ExecOnConflictLockRow --- lock the row for ON CONFLICT DO SELECT/UPDATE
    3020                 :             :  *
    3021                 :             :  * Try to lock tuple for update as part of speculative insertion for ON
    3022                 :             :  * CONFLICT DO UPDATE or ON CONFLICT DO SELECT FOR UPDATE/SHARE.
    3023                 :             :  *
    3024                 :             :  * Returns true if the row is successfully locked, or false if the caller must
    3025                 :             :  * retry the INSERT from scratch.
    3026                 :             :  */
    3027                 :             : static bool
    3028                 :        2831 : ExecOnConflictLockRow(ModifyTableContext *context,
    3029                 :             :                       TupleTableSlot *existing,
    3030                 :             :                       ItemPointer conflictTid,
    3031                 :             :                       Relation relation,
    3032                 :             :                       LockTupleMode lockmode,
    3033                 :             :                       bool isUpdate)
    3034                 :             : {
    3035                 :             :     TM_FailureData tmfd;
    3036                 :             :     TM_Result   test;
    3037                 :             :     Datum       xminDatum;
    3038                 :             :     TransactionId xmin;
    3039                 :             :     bool        isnull;
    3040                 :             : 
    3041                 :             :     /*
    3042                 :             :      * Lock tuple with lockmode.  Don't follow updates when tuple cannot be
    3043                 :             :      * locked without doing so.  A row locking conflict here means our
    3044                 :             :      * previous conclusion that the tuple is conclusively committed is not
    3045                 :             :      * true anymore.
    3046                 :             :      */
    3047                 :        2831 :     test = table_tuple_lock(relation, conflictTid,
    3048                 :        2831 :                             context->estate->es_snapshot,
    3049                 :        2831 :                             existing, context->estate->es_output_cid,
    3050                 :             :                             lockmode, LockWaitBlock, 0,
    3051                 :             :                             &tmfd);
    3052   [ +  +  -  +  :        2831 :     switch (test)
                   +  - ]
    3053                 :             :     {
    3054                 :        2800 :         case TM_Ok:
    3055                 :             :             /* success! */
    3056                 :        2800 :             break;
    3057                 :             : 
    3058                 :          28 :         case TM_Invisible:
    3059                 :             : 
    3060                 :             :             /*
    3061                 :             :              * This can occur when a just inserted tuple is updated again in
    3062                 :             :              * the same command. E.g. because multiple rows with the same
    3063                 :             :              * conflicting key values are inserted.
    3064                 :             :              *
    3065                 :             :              * This is somewhat similar to the ExecUpdate() TM_SelfModified
    3066                 :             :              * case.  We do not want to proceed because it would lead to the
    3067                 :             :              * same row being updated a second time in some unspecified order,
    3068                 :             :              * and in contrast to plain UPDATEs there's no historical behavior
    3069                 :             :              * to break.
    3070                 :             :              *
    3071                 :             :              * It is the user's responsibility to prevent this situation from
    3072                 :             :              * occurring.  These problems are why the SQL standard similarly
    3073                 :             :              * specifies that for SQL MERGE, an exception must be raised in
    3074                 :             :              * the event of an attempt to update the same row twice.
    3075                 :             :              */
    3076                 :          28 :             xminDatum = slot_getsysattr(existing,
    3077                 :             :                                         MinTransactionIdAttributeNumber,
    3078                 :             :                                         &isnull);
    3079                 :             :             Assert(!isnull);
    3080                 :          28 :             xmin = DatumGetTransactionId(xminDatum);
    3081                 :             : 
    3082         [ +  - ]:          28 :             if (TransactionIdIsCurrentTransactionId(xmin))
    3083   [ +  -  +  + ]:          28 :                 ereport(ERROR,
    3084                 :             :                         (errcode(ERRCODE_CARDINALITY_VIOLATION),
    3085                 :             :                 /* translator: %s is a SQL command name */
    3086                 :             :                          errmsg("%s command cannot affect row a second time",
    3087                 :             :                                 isUpdate ? "ON CONFLICT DO UPDATE" : "ON CONFLICT DO SELECT"),
    3088                 :             :                          errhint("Ensure that no rows proposed for insertion within the same command have duplicate constrained values.")));
    3089                 :             : 
    3090                 :             :             /* This shouldn't happen */
    3091         [ #  # ]:           0 :             elog(ERROR, "attempted to lock invisible tuple");
    3092                 :             :             break;
    3093                 :             : 
    3094                 :           0 :         case TM_SelfModified:
    3095                 :             : 
    3096                 :             :             /*
    3097                 :             :              * This state should never be reached. As a dirty snapshot is used
    3098                 :             :              * to find conflicting tuples, speculative insertion wouldn't have
    3099                 :             :              * seen this row to conflict with.
    3100                 :             :              */
    3101         [ #  # ]:           0 :             elog(ERROR, "unexpected self-updated tuple");
    3102                 :             :             break;
    3103                 :             : 
    3104                 :           2 :         case TM_Updated:
    3105         [ -  + ]:           2 :             if (IsolationUsesXactSnapshot())
    3106         [ #  # ]:           0 :                 ereport(ERROR,
    3107                 :             :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3108                 :             :                          errmsg("could not serialize access due to concurrent update")));
    3109                 :             : 
    3110                 :             :             /*
    3111                 :             :              * Tell caller to try again from the very start.
    3112                 :             :              *
    3113                 :             :              * It does not make sense to use the usual EvalPlanQual() style
    3114                 :             :              * loop here, as the new version of the row might not conflict
    3115                 :             :              * anymore, or the conflicting tuple has actually been deleted.
    3116                 :             :              */
    3117                 :           2 :             ExecClearTuple(existing);
    3118                 :           2 :             return false;
    3119                 :             : 
    3120                 :           1 :         case TM_Deleted:
    3121         [ -  + ]:           1 :             if (IsolationUsesXactSnapshot())
    3122         [ #  # ]:           0 :                 ereport(ERROR,
    3123                 :             :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3124                 :             :                          errmsg("could not serialize access due to concurrent delete")));
    3125                 :             : 
    3126                 :             :             /* see TM_Updated case */
    3127                 :           1 :             ExecClearTuple(existing);
    3128                 :           1 :             return false;
    3129                 :             : 
    3130                 :           0 :         default:
    3131         [ #  # ]:           0 :             elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
    3132                 :             :     }
    3133                 :             : 
    3134                 :             :     /* Success, the tuple is locked. */
    3135                 :        2800 :     return true;
    3136                 :             : }
    3137                 :             : 
    3138                 :             : /*
    3139                 :             :  * ExecOnConflictUpdate --- execute UPDATE of INSERT ON CONFLICT DO UPDATE
    3140                 :             :  *
    3141                 :             :  * Try to lock tuple for update as part of speculative insertion.  If
    3142                 :             :  * a qual originating from ON CONFLICT DO UPDATE is satisfied, update
    3143                 :             :  * (but still lock row, even though it may not satisfy estate's
    3144                 :             :  * snapshot).
    3145                 :             :  *
    3146                 :             :  * Returns true if we're done (with or without an update), or false if
    3147                 :             :  * the caller must retry the INSERT from scratch.
    3148                 :             :  */
    3149                 :             : static bool
    3150                 :        2761 : ExecOnConflictUpdate(ModifyTableContext *context,
    3151                 :             :                      ResultRelInfo *resultRelInfo,
    3152                 :             :                      ItemPointer conflictTid,
    3153                 :             :                      TupleTableSlot *excludedSlot,
    3154                 :             :                      bool canSetTag,
    3155                 :             :                      TupleTableSlot **returning)
    3156                 :             : {
    3157                 :        2761 :     ModifyTableState *mtstate = context->mtstate;
    3158                 :        2761 :     ExprContext *econtext = mtstate->ps.ps_ExprContext;
    3159                 :        2761 :     Relation    relation = resultRelInfo->ri_RelationDesc;
    3160                 :        2761 :     ExprState  *onConflictSetWhere = resultRelInfo->ri_onConflict->oc_WhereClause;
    3161                 :        2761 :     TupleTableSlot *existing = resultRelInfo->ri_onConflict->oc_Existing;
    3162                 :             :     LockTupleMode lockmode;
    3163                 :             : 
    3164                 :             :     /*
    3165                 :             :      * Parse analysis should have blocked ON CONFLICT for all system
    3166                 :             :      * relations, which includes these.  There's no fundamental obstacle to
    3167                 :             :      * supporting this; we'd just need to handle LOCKTAG_TUPLE like the other
    3168                 :             :      * ExecUpdate() caller.
    3169                 :             :      */
    3170                 :             :     Assert(!resultRelInfo->ri_needLockTagTuple);
    3171                 :             : 
    3172                 :             :     /* Determine lock mode to use */
    3173                 :        2761 :     lockmode = ExecUpdateLockMode(context->estate, resultRelInfo);
    3174                 :             : 
    3175                 :             :     /* Lock tuple for update */
    3176         [ +  + ]:        2761 :     if (!ExecOnConflictLockRow(context, existing, conflictTid,
    3177                 :             :                                resultRelInfo->ri_RelationDesc, lockmode, true))
    3178                 :           3 :         return false;
    3179                 :             : 
    3180                 :             :     /*
    3181                 :             :      * Verify that the tuple is visible to our MVCC snapshot if the current
    3182                 :             :      * isolation level mandates that.
    3183                 :             :      *
    3184                 :             :      * It's not sufficient to rely on the check within ExecUpdate() as e.g.
    3185                 :             :      * CONFLICT ... WHERE clause may prevent us from reaching that.
    3186                 :             :      *
    3187                 :             :      * This means we only ever continue when a new command in the current
    3188                 :             :      * transaction could see the row, even though in READ COMMITTED mode the
    3189                 :             :      * tuple will not be visible according to the current statement's
    3190                 :             :      * snapshot.  This is in line with the way UPDATE deals with newer tuple
    3191                 :             :      * versions.
    3192                 :             :      */
    3193                 :        2742 :     ExecCheckTupleVisible(context->estate, relation, existing);
    3194                 :             : 
    3195                 :             :     /*
    3196                 :             :      * Make tuple and any needed join variables available to ExecQual and
    3197                 :             :      * ExecProject.  The EXCLUDED tuple is installed in ecxt_innertuple, while
    3198                 :             :      * the target's existing tuple is installed in the scantuple.  EXCLUDED
    3199                 :             :      * has been made to reference INNER_VAR in setrefs.c, but there is no
    3200                 :             :      * other redirection.
    3201                 :             :      */
    3202                 :        2742 :     econtext->ecxt_scantuple = existing;
    3203                 :        2742 :     econtext->ecxt_innertuple = excludedSlot;
    3204                 :        2742 :     econtext->ecxt_outertuple = NULL;
    3205                 :             : 
    3206         [ +  + ]:        2742 :     if (!ExecQual(onConflictSetWhere, econtext))
    3207                 :             :     {
    3208                 :          21 :         ExecClearTuple(existing);   /* see return below */
    3209         [ -  + ]:          21 :         InstrCountFiltered1(&mtstate->ps, 1);
    3210                 :          21 :         return true;            /* done with the tuple */
    3211                 :             :     }
    3212                 :             : 
    3213         [ +  + ]:        2721 :     if (resultRelInfo->ri_WithCheckOptions != NIL)
    3214                 :             :     {
    3215                 :             :         /*
    3216                 :             :          * Check target's existing tuple against UPDATE-applicable USING
    3217                 :             :          * security barrier quals (if any), enforced here as RLS checks/WCOs.
    3218                 :             :          *
    3219                 :             :          * The rewriter creates UPDATE RLS checks/WCOs for UPDATE security
    3220                 :             :          * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK.
    3221                 :             :          * Since SELECT permission on the target table is always required for
    3222                 :             :          * INSERT ... ON CONFLICT DO UPDATE, the rewriter also adds SELECT RLS
    3223                 :             :          * checks/WCOs for SELECT security quals, using WCOs of the same kind,
    3224                 :             :          * and this check enforces them too.
    3225                 :             :          *
    3226                 :             :          * The rewriter will also have associated UPDATE-applicable straight
    3227                 :             :          * RLS checks/WCOs for the benefit of the ExecUpdate() call that
    3228                 :             :          * follows.  INSERTs and UPDATEs naturally have mutually exclusive WCO
    3229                 :             :          * kinds, so there is no danger of spurious over-enforcement in the
    3230                 :             :          * INSERT or UPDATE path.
    3231                 :             :          */
    3232                 :          48 :         ExecWithCheckOptions(WCO_RLS_CONFLICT_CHECK, resultRelInfo,
    3233                 :             :                              existing,
    3234                 :             :                              mtstate->ps.state);
    3235                 :             :     }
    3236                 :             : 
    3237                 :             :     /* Project the new tuple version */
    3238                 :        2705 :     ExecProject(resultRelInfo->ri_onConflict->oc_ProjInfo);
    3239                 :             : 
    3240                 :             :     /*
    3241                 :             :      * Note that it is possible that the target tuple has been modified in
    3242                 :             :      * this session, after the above table_tuple_lock. We choose to not error
    3243                 :             :      * out in that case, in line with ExecUpdate's treatment of similar cases.
    3244                 :             :      * This can happen if an UPDATE is triggered from within ExecQual(),
    3245                 :             :      * ExecWithCheckOptions() or ExecProject() above, e.g. by selecting from a
    3246                 :             :      * wCTE in the ON CONFLICT's SET.
    3247                 :             :      */
    3248                 :             : 
    3249                 :             :     /* Execute UPDATE with projection */
    3250                 :        5390 :     *returning = ExecUpdate(context, resultRelInfo,
    3251                 :             :                             conflictTid, NULL, existing,
    3252                 :        2705 :                             resultRelInfo->ri_onConflict->oc_ProjSlot,
    3253                 :             :                             canSetTag);
    3254                 :             : 
    3255                 :             :     /*
    3256                 :             :      * Clear out existing tuple, as there might not be another conflict among
    3257                 :             :      * the next input rows. Don't want to hold resources till the end of the
    3258                 :             :      * query.  First though, make sure that the returning slot, if any, has a
    3259                 :             :      * local copy of any OLD pass-by-reference values, if it refers to any OLD
    3260                 :             :      * columns.
    3261                 :             :      */
    3262         [ +  + ]:        2685 :     if (*returning != NULL &&
    3263         [ +  + ]:         174 :         resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD)
    3264                 :          12 :         ExecMaterializeSlot(*returning);
    3265                 :             : 
    3266                 :        2685 :     ExecClearTuple(existing);
    3267                 :             : 
    3268                 :        2685 :     return true;
    3269                 :             : }
    3270                 :             : 
    3271                 :             : /*
    3272                 :             :  * ExecOnConflictSelect --- execute SELECT of INSERT ON CONFLICT DO SELECT
    3273                 :             :  *
    3274                 :             :  * If SELECT FOR UPDATE/SHARE is specified, try to lock tuple as part of
    3275                 :             :  * speculative insertion.  If a qual originating from ON CONFLICT DO SELECT is
    3276                 :             :  * satisfied, select (but still lock row, even though it may not satisfy
    3277                 :             :  * estate's snapshot).
    3278                 :             :  *
    3279                 :             :  * Returns true if we're done (with or without a select), or false if the
    3280                 :             :  * caller must retry the INSERT from scratch.
    3281                 :             :  */
    3282                 :             : static bool
    3283                 :         192 : ExecOnConflictSelect(ModifyTableContext *context,
    3284                 :             :                      ResultRelInfo *resultRelInfo,
    3285                 :             :                      ItemPointer conflictTid,
    3286                 :             :                      TupleTableSlot *excludedSlot,
    3287                 :             :                      bool canSetTag,
    3288                 :             :                      TupleTableSlot **returning)
    3289                 :             : {
    3290                 :         192 :     ModifyTableState *mtstate = context->mtstate;
    3291                 :         192 :     ExprContext *econtext = mtstate->ps.ps_ExprContext;
    3292                 :         192 :     Relation    relation = resultRelInfo->ri_RelationDesc;
    3293                 :         192 :     ExprState  *onConflictSelectWhere = resultRelInfo->ri_onConflict->oc_WhereClause;
    3294                 :         192 :     TupleTableSlot *existing = resultRelInfo->ri_onConflict->oc_Existing;
    3295                 :         192 :     LockClauseStrength lockStrength = resultRelInfo->ri_onConflict->oc_LockStrength;
    3296                 :             : 
    3297                 :             :     /*
    3298                 :             :      * Parse analysis should have blocked ON CONFLICT for all system
    3299                 :             :      * relations, which includes these.  There's no fundamental obstacle to
    3300                 :             :      * supporting this; we'd just need to handle LOCKTAG_TUPLE appropriately.
    3301                 :             :      */
    3302                 :             :     Assert(!resultRelInfo->ri_needLockTagTuple);
    3303                 :             : 
    3304                 :             :     /* Fetch/lock existing tuple, according to the requested lock strength */
    3305         [ +  + ]:         192 :     if (lockStrength == LCS_NONE)
    3306                 :             :     {
    3307         [ -  + ]:         122 :         if (!table_tuple_fetch_row_version(relation,
    3308                 :             :                                            conflictTid,
    3309                 :             :                                            SnapshotAny,
    3310                 :             :                                            existing))
    3311         [ #  # ]:           0 :             elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
    3312                 :             :     }
    3313                 :             :     else
    3314                 :             :     {
    3315                 :             :         LockTupleMode lockmode;
    3316                 :             : 
    3317   [ +  +  +  +  :          70 :         switch (lockStrength)
                      - ]
    3318                 :             :         {
    3319                 :           1 :             case LCS_FORKEYSHARE:
    3320                 :           1 :                 lockmode = LockTupleKeyShare;
    3321                 :           1 :                 break;
    3322                 :           1 :             case LCS_FORSHARE:
    3323                 :           1 :                 lockmode = LockTupleShare;
    3324                 :           1 :                 break;
    3325                 :           1 :             case LCS_FORNOKEYUPDATE:
    3326                 :           1 :                 lockmode = LockTupleNoKeyExclusive;
    3327                 :           1 :                 break;
    3328                 :          67 :             case LCS_FORUPDATE:
    3329                 :          67 :                 lockmode = LockTupleExclusive;
    3330                 :          67 :                 break;
    3331                 :           0 :             default:
    3332         [ #  # ]:           0 :                 elog(ERROR, "Unexpected lock strength %d", (int) lockStrength);
    3333                 :             :         }
    3334                 :             : 
    3335         [ -  + ]:          70 :         if (!ExecOnConflictLockRow(context, existing, conflictTid,
    3336                 :             :                                    resultRelInfo->ri_RelationDesc, lockmode, false))
    3337                 :           0 :             return false;
    3338                 :             :     }
    3339                 :             : 
    3340                 :             :     /*
    3341                 :             :      * Verify that the tuple is visible to our MVCC snapshot if the current
    3342                 :             :      * isolation level mandates that.  See comments in ExecOnConflictUpdate().
    3343                 :             :      */
    3344                 :         180 :     ExecCheckTupleVisible(context->estate, relation, existing);
    3345                 :             : 
    3346                 :             :     /*
    3347                 :             :      * Make tuple and any needed join variables available to ExecQual.  The
    3348                 :             :      * EXCLUDED tuple is installed in ecxt_innertuple, while the target's
    3349                 :             :      * existing tuple is installed in the scantuple.  EXCLUDED has been made
    3350                 :             :      * to reference INNER_VAR in setrefs.c, but there is no other redirection.
    3351                 :             :      */
    3352                 :         180 :     econtext->ecxt_scantuple = existing;
    3353                 :         180 :     econtext->ecxt_innertuple = excludedSlot;
    3354                 :         180 :     econtext->ecxt_outertuple = NULL;
    3355                 :             : 
    3356         [ +  + ]:         180 :     if (!ExecQual(onConflictSelectWhere, econtext))
    3357                 :             :     {
    3358                 :          24 :         ExecClearTuple(existing);   /* see return below */
    3359         [ -  + ]:          24 :         InstrCountFiltered1(&mtstate->ps, 1);
    3360                 :          24 :         return true;            /* done with the tuple */
    3361                 :             :     }
    3362                 :             : 
    3363         [ +  + ]:         156 :     if (resultRelInfo->ri_WithCheckOptions != NIL)
    3364                 :             :     {
    3365                 :             :         /*
    3366                 :             :          * Check target's existing tuple against SELECT-applicable USING
    3367                 :             :          * security barrier quals (if any), enforced here as RLS checks/WCOs.
    3368                 :             :          *
    3369                 :             :          * The rewriter creates WCOs from the USING quals of SELECT policies,
    3370                 :             :          * and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK.  If FOR
    3371                 :             :          * UPDATE/SHARE was specified, UPDATE permissions are required on the
    3372                 :             :          * target table, and the rewriter also adds WCOs built from the USING
    3373                 :             :          * quals of UPDATE policies, using WCOs of the same kind, and this
    3374                 :             :          * check enforces them too.
    3375                 :             :          */
    3376                 :          24 :         ExecWithCheckOptions(WCO_RLS_CONFLICT_CHECK, resultRelInfo,
    3377                 :             :                              existing,
    3378                 :             :                              mtstate->ps.state);
    3379                 :             :     }
    3380                 :             : 
    3381                 :             :     /* RETURNING is required for DO SELECT */
    3382                 :             :     Assert(resultRelInfo->ri_projectReturning);
    3383                 :             : 
    3384                 :         152 :     *returning = ExecProcessReturning(context, resultRelInfo, false,
    3385                 :             :                                       existing, existing, context->planSlot);
    3386                 :             : 
    3387         [ +  - ]:         152 :     if (canSetTag)
    3388                 :         152 :         context->estate->es_processed++;
    3389                 :             : 
    3390                 :             :     /*
    3391                 :             :      * Before releasing the existing tuple, make sure that the returning slot
    3392                 :             :      * has a local copy of any pass-by-reference values.
    3393                 :             :      */
    3394                 :         152 :     ExecMaterializeSlot(*returning);
    3395                 :             : 
    3396                 :             :     /*
    3397                 :             :      * Clear out existing tuple, as there might not be another conflict among
    3398                 :             :      * the next input rows. Don't want to hold resources till the end of the
    3399                 :             :      * query.
    3400                 :             :      */
    3401                 :         152 :     ExecClearTuple(existing);
    3402                 :             : 
    3403                 :         152 :     return true;
    3404                 :             : }
    3405                 :             : 
    3406                 :             : /*
    3407                 :             :  * Perform MERGE.
    3408                 :             :  */
    3409                 :             : static TupleTableSlot *
    3410                 :       10441 : ExecMerge(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    3411                 :             :           ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag)
    3412                 :             : {
    3413                 :       10441 :     TupleTableSlot *rslot = NULL;
    3414                 :             :     bool        matched;
    3415                 :             : 
    3416                 :             :     /*-----
    3417                 :             :      * If we are dealing with a WHEN MATCHED case, tupleid or oldtuple is
    3418                 :             :      * valid, depending on whether the result relation is a table or a view.
    3419                 :             :      * We execute the first action for which the additional WHEN MATCHED AND
    3420                 :             :      * quals pass.  If an action without quals is found, that action is
    3421                 :             :      * executed.
    3422                 :             :      *
    3423                 :             :      * Similarly, in the WHEN NOT MATCHED BY SOURCE case, tupleid or oldtuple
    3424                 :             :      * is valid, and we look at the given WHEN NOT MATCHED BY SOURCE actions
    3425                 :             :      * in sequence until one passes.  This is almost identical to the WHEN
    3426                 :             :      * MATCHED case, and both cases are handled by ExecMergeMatched().
    3427                 :             :      *
    3428                 :             :      * Finally, in the WHEN NOT MATCHED [BY TARGET] case, both tupleid and
    3429                 :             :      * oldtuple are invalid, and we look at the given WHEN NOT MATCHED [BY
    3430                 :             :      * TARGET] actions in sequence until one passes.
    3431                 :             :      *
    3432                 :             :      * Things get interesting in case of concurrent update/delete of the
    3433                 :             :      * target tuple. Such concurrent update/delete is detected while we are
    3434                 :             :      * executing a WHEN MATCHED or WHEN NOT MATCHED BY SOURCE action.
    3435                 :             :      *
    3436                 :             :      * A concurrent update can:
    3437                 :             :      *
    3438                 :             :      * 1. modify the target tuple so that the results from checking any
    3439                 :             :      *    additional quals attached to WHEN MATCHED or WHEN NOT MATCHED BY
    3440                 :             :      *    SOURCE actions potentially change, but the result from the join
    3441                 :             :      *    quals does not change.
    3442                 :             :      *
    3443                 :             :      *    In this case, we are still dealing with the same kind of match
    3444                 :             :      *    (MATCHED or NOT MATCHED BY SOURCE).  We recheck the same list of
    3445                 :             :      *    actions from the start and choose the first one that satisfies the
    3446                 :             :      *    new target tuple.
    3447                 :             :      *
    3448                 :             :      * 2. modify the target tuple in the WHEN MATCHED case so that the join
    3449                 :             :      *    quals no longer pass and hence the source and target tuples no
    3450                 :             :      *    longer match.
    3451                 :             :      *
    3452                 :             :      *    In this case, we are now dealing with a NOT MATCHED case, and we
    3453                 :             :      *    process both WHEN NOT MATCHED BY SOURCE and WHEN NOT MATCHED [BY
    3454                 :             :      *    TARGET] actions.  First ExecMergeMatched() processes the list of
    3455                 :             :      *    WHEN NOT MATCHED BY SOURCE actions in sequence until one passes,
    3456                 :             :      *    then ExecMergeNotMatched() processes any WHEN NOT MATCHED [BY
    3457                 :             :      *    TARGET] actions in sequence until one passes.  Thus we may execute
    3458                 :             :      *    two actions; one of each kind.
    3459                 :             :      *
    3460                 :             :      * Thus we support concurrent updates that turn MATCHED candidate rows
    3461                 :             :      * into NOT MATCHED rows.  However, we do not attempt to support cases
    3462                 :             :      * that would turn NOT MATCHED rows into MATCHED rows, or which would
    3463                 :             :      * cause a target row to match a different source row.
    3464                 :             :      *
    3465                 :             :      * A concurrent delete changes a WHEN MATCHED case to WHEN NOT MATCHED
    3466                 :             :      * [BY TARGET].
    3467                 :             :      *
    3468                 :             :      * ExecMergeMatched() takes care of following the update chain and
    3469                 :             :      * re-finding the qualifying WHEN MATCHED or WHEN NOT MATCHED BY SOURCE
    3470                 :             :      * action, as long as the target tuple still exists. If the target tuple
    3471                 :             :      * gets deleted or a concurrent update causes the join quals to fail, it
    3472                 :             :      * returns a matched status of false and we call ExecMergeNotMatched().
    3473                 :             :      * Given that ExecMergeMatched() always makes progress by following the
    3474                 :             :      * update chain and we never switch from ExecMergeNotMatched() to
    3475                 :             :      * ExecMergeMatched(), there is no risk of a livelock.
    3476                 :             :      */
    3477   [ +  +  +  + ]:       10441 :     matched = tupleid != NULL || oldtuple != NULL;
    3478         [ +  + ]:       10441 :     if (matched)
    3479                 :        8650 :         rslot = ExecMergeMatched(context, resultRelInfo, tupleid, oldtuple,
    3480                 :             :                                  canSetTag, &matched);
    3481                 :             : 
    3482                 :             :     /*
    3483                 :             :      * Deal with the NOT MATCHED case (either a NOT MATCHED tuple from the
    3484                 :             :      * join, or a previously MATCHED tuple for which ExecMergeMatched() set
    3485                 :             :      * "matched" to false, indicating that it no longer matches).
    3486                 :             :      */
    3487         [ +  + ]:       10379 :     if (!matched)
    3488                 :             :     {
    3489                 :             :         /*
    3490                 :             :          * If a concurrent update turned a MATCHED case into a NOT MATCHED
    3491                 :             :          * case, and we have both WHEN NOT MATCHED BY SOURCE and WHEN NOT
    3492                 :             :          * MATCHED [BY TARGET] actions, and there is a RETURNING clause,
    3493                 :             :          * ExecMergeMatched() may have already executed a WHEN NOT MATCHED BY
    3494                 :             :          * SOURCE action, and computed the row to return.  If so, we cannot
    3495                 :             :          * execute a WHEN NOT MATCHED [BY TARGET] action now, so mark it as
    3496                 :             :          * pending (to be processed on the next call to ExecModifyTable()).
    3497                 :             :          * Otherwise, just process the action now.
    3498                 :             :          */
    3499         [ +  + ]:        1800 :         if (rslot == NULL)
    3500                 :        1798 :             rslot = ExecMergeNotMatched(context, resultRelInfo, canSetTag);
    3501                 :             :         else
    3502                 :           2 :             context->mtstate->mt_merge_pending_not_matched = context->planSlot;
    3503                 :             :     }
    3504                 :             : 
    3505                 :       10340 :     return rslot;
    3506                 :             : }
    3507                 :             : 
    3508                 :             : /*
    3509                 :             :  * Check and execute the first qualifying MATCHED or NOT MATCHED BY SOURCE
    3510                 :             :  * action, depending on whether the join quals are satisfied.  If the target
    3511                 :             :  * relation is a table, the current target tuple is identified by tupleid.
    3512                 :             :  * Otherwise, if the target relation is a view, oldtuple is the current target
    3513                 :             :  * tuple from the view.
    3514                 :             :  *
    3515                 :             :  * We start from the first WHEN MATCHED or WHEN NOT MATCHED BY SOURCE action
    3516                 :             :  * and check if the WHEN quals pass, if any. If the WHEN quals for the first
    3517                 :             :  * action do not pass, we check the second, then the third and so on. If we
    3518                 :             :  * reach the end without finding a qualifying action, we return NULL.
    3519                 :             :  * Otherwise, we execute the qualifying action and return its RETURNING
    3520                 :             :  * result, if any, or NULL.
    3521                 :             :  *
    3522                 :             :  * On entry, "*matched" is assumed to be true.  If a concurrent update or
    3523                 :             :  * delete is detected that causes the join quals to no longer pass, we set it
    3524                 :             :  * to false, indicating that the caller should process any NOT MATCHED [BY
    3525                 :             :  * TARGET] actions.
    3526                 :             :  *
    3527                 :             :  * After a concurrent update, we restart from the first action to look for a
    3528                 :             :  * new qualifying action to execute. If the join quals originally passed, and
    3529                 :             :  * the concurrent update caused them to no longer pass, then we switch from
    3530                 :             :  * the MATCHED to the NOT MATCHED BY SOURCE list of actions before restarting
    3531                 :             :  * (and setting "*matched" to false).  As a result we may execute a WHEN NOT
    3532                 :             :  * MATCHED BY SOURCE action, and set "*matched" to false, causing the caller
    3533                 :             :  * to also execute a WHEN NOT MATCHED [BY TARGET] action.
    3534                 :             :  */
    3535                 :             : static TupleTableSlot *
    3536                 :        8650 : ExecMergeMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    3537                 :             :                  ItemPointer tupleid, HeapTuple oldtuple, bool canSetTag,
    3538                 :             :                  bool *matched)
    3539                 :             : {
    3540                 :        8650 :     ModifyTableState *mtstate = context->mtstate;
    3541                 :        8650 :     List      **mergeActions = resultRelInfo->ri_MergeActions;
    3542                 :             :     ItemPointerData lockedtid;
    3543                 :             :     List       *actionStates;
    3544                 :        8650 :     TupleTableSlot *newslot = NULL;
    3545                 :        8650 :     TupleTableSlot *rslot = NULL;
    3546                 :        8650 :     EState     *estate = context->estate;
    3547                 :        8650 :     ExprContext *econtext = mtstate->ps.ps_ExprContext;
    3548                 :             :     bool        isNull;
    3549                 :        8650 :     EPQState   *epqstate = &mtstate->mt_epqstate;
    3550                 :             :     ListCell   *l;
    3551                 :             : 
    3552                 :             :     /* Expect matched to be true on entry */
    3553                 :             :     Assert(*matched);
    3554                 :             : 
    3555                 :             :     /*
    3556                 :             :      * If there are no WHEN MATCHED or WHEN NOT MATCHED BY SOURCE actions, we
    3557                 :             :      * are done.
    3558                 :             :      */
    3559         [ +  + ]:        8650 :     if (mergeActions[MERGE_WHEN_MATCHED] == NIL &&
    3560         [ +  + ]:         780 :         mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] == NIL)
    3561                 :         332 :         return NULL;
    3562                 :             : 
    3563                 :             :     /*
    3564                 :             :      * Make tuple and any needed join variables available to ExecQual and
    3565                 :             :      * ExecProject. The target's existing tuple is installed in the scantuple.
    3566                 :             :      * This target relation's slot is required only in the case of a MATCHED
    3567                 :             :      * or NOT MATCHED BY SOURCE tuple and UPDATE/DELETE actions.
    3568                 :             :      */
    3569                 :        8318 :     econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
    3570                 :        8318 :     econtext->ecxt_innertuple = context->planSlot;
    3571                 :        8318 :     econtext->ecxt_outertuple = NULL;
    3572                 :             : 
    3573                 :             :     /*
    3574                 :             :      * This routine is only invoked for matched target rows, so we should
    3575                 :             :      * either have the tupleid of the target row, or an old tuple from the
    3576                 :             :      * target wholerow junk attr.
    3577                 :             :      */
    3578                 :             :     Assert(tupleid != NULL || oldtuple != NULL);
    3579                 :        8318 :     ItemPointerSetInvalid(&lockedtid);
    3580         [ +  + ]:        8318 :     if (oldtuple != NULL)
    3581                 :             :     {
    3582                 :             :         Assert(!resultRelInfo->ri_needLockTagTuple);
    3583                 :          64 :         ExecForceStoreHeapTuple(oldtuple, resultRelInfo->ri_oldTupleSlot,
    3584                 :             :                                 false);
    3585                 :             :     }
    3586                 :             :     else
    3587                 :             :     {
    3588         [ +  + ]:        8254 :         if (resultRelInfo->ri_needLockTagTuple)
    3589                 :             :         {
    3590                 :             :             /*
    3591                 :             :              * This locks even for CMD_DELETE, for CMD_NOTHING, and for tuples
    3592                 :             :              * that don't match mas_whenqual.  MERGE on system catalogs is a
    3593                 :             :              * minor use case, so don't bother optimizing those.
    3594                 :             :              */
    3595                 :        5634 :             LockTuple(resultRelInfo->ri_RelationDesc, tupleid,
    3596                 :             :                       InplaceUpdateTupleLock);
    3597                 :        5634 :             lockedtid = *tupleid;
    3598                 :             :         }
    3599         [ -  + ]:        8254 :         if (!table_tuple_fetch_row_version(resultRelInfo->ri_RelationDesc,
    3600                 :             :                                            tupleid,
    3601                 :             :                                            SnapshotAny,
    3602                 :             :                                            resultRelInfo->ri_oldTupleSlot))
    3603         [ #  # ]:           0 :             elog(ERROR, "failed to fetch the target tuple");
    3604                 :             :     }
    3605                 :             : 
    3606                 :             :     /*
    3607                 :             :      * Test the join condition.  If it's satisfied, perform a MATCHED action.
    3608                 :             :      * Otherwise, perform a NOT MATCHED BY SOURCE action.
    3609                 :             :      *
    3610                 :             :      * Note that this join condition will be NULL if there are no NOT MATCHED
    3611                 :             :      * BY SOURCE actions --- see transform_MERGE_to_join().  In that case, we
    3612                 :             :      * need only consider MATCHED actions here.
    3613                 :             :      */
    3614         [ +  + ]:        8318 :     if (ExecQual(resultRelInfo->ri_MergeJoinCondition, econtext))
    3615                 :        8196 :         actionStates = mergeActions[MERGE_WHEN_MATCHED];
    3616                 :             :     else
    3617                 :         122 :         actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
    3618                 :             : 
    3619                 :        8318 : lmerge_matched:
    3620                 :             : 
    3621   [ +  +  +  +  :       14984 :     foreach(l, actionStates)
                   +  + ]
    3622                 :             :     {
    3623                 :        8426 :         MergeActionState *relaction = (MergeActionState *) lfirst(l);
    3624                 :        8426 :         CmdType     commandType = relaction->mas_action->commandType;
    3625                 :             :         TM_Result   result;
    3626                 :        8426 :         UpdateContext updateCxt = {0};
    3627                 :             : 
    3628                 :             :         /*
    3629                 :             :          * Test condition, if any.
    3630                 :             :          *
    3631                 :             :          * In the absence of any condition, we perform the action
    3632                 :             :          * unconditionally (no need to check separately since ExecQual() will
    3633                 :             :          * return true if there are no conditions to evaluate).
    3634                 :             :          */
    3635         [ +  + ]:        8426 :         if (!ExecQual(relaction->mas_whenqual, econtext))
    3636                 :        6623 :             continue;
    3637                 :             : 
    3638                 :             :         /*
    3639                 :             :          * Check if the existing target tuple meets the USING checks of
    3640                 :             :          * UPDATE/DELETE RLS policies. If those checks fail, we throw an
    3641                 :             :          * error.
    3642                 :             :          *
    3643                 :             :          * The WITH CHECK quals for UPDATE RLS policies are applied in
    3644                 :             :          * ExecUpdateAct() and hence we need not do anything special to handle
    3645                 :             :          * them.
    3646                 :             :          *
    3647                 :             :          * NOTE: We must do this after WHEN quals are evaluated, so that we
    3648                 :             :          * check policies only when they matter.
    3649                 :             :          */
    3650   [ +  +  +  + ]:        1803 :         if (resultRelInfo->ri_WithCheckOptions && commandType != CMD_NOTHING)
    3651                 :             :         {
    3652                 :          76 :             ExecWithCheckOptions(commandType == CMD_UPDATE ?
    3653                 :             :                                  WCO_RLS_MERGE_UPDATE_CHECK : WCO_RLS_MERGE_DELETE_CHECK,
    3654                 :             :                                  resultRelInfo,
    3655                 :             :                                  resultRelInfo->ri_oldTupleSlot,
    3656         [ +  + ]:          76 :                                  context->mtstate->ps.state);
    3657                 :             :         }
    3658                 :             : 
    3659                 :             :         /* Perform stated action */
    3660   [ +  +  +  - ]:        1787 :         switch (commandType)
    3661                 :             :         {
    3662                 :        1416 :             case CMD_UPDATE:
    3663                 :             : 
    3664                 :             :                 /*
    3665                 :             :                  * Project the output tuple, and use that to update the table.
    3666                 :             :                  * We don't need to filter out junk attributes, because the
    3667                 :             :                  * UPDATE action's targetlist doesn't have any.
    3668                 :             :                  */
    3669                 :        1416 :                 newslot = ExecProject(relaction->mas_proj);
    3670                 :             : 
    3671                 :        1416 :                 mtstate->mt_merge_action = relaction;
    3672         [ +  + ]:        1416 :                 if (!ExecUpdatePrologue(context, resultRelInfo,
    3673                 :             :                                         tupleid, NULL, newslot, &result))
    3674                 :             :                 {
    3675         [ +  + ]:          12 :                     if (result == TM_Ok)
    3676                 :         102 :                         goto out;   /* "do nothing" */
    3677                 :             : 
    3678                 :           8 :                     break;      /* concurrent update/delete */
    3679                 :             :                 }
    3680                 :             : 
    3681                 :             :                 /* INSTEAD OF ROW UPDATE Triggers */
    3682         [ +  + ]:        1404 :                 if (resultRelInfo->ri_TrigDesc &&
    3683         [ +  + ]:         230 :                     resultRelInfo->ri_TrigDesc->trig_update_instead_row)
    3684                 :             :                 {
    3685         [ -  + ]:          52 :                     if (!ExecIRUpdateTriggers(estate, resultRelInfo,
    3686                 :             :                                               oldtuple, newslot))
    3687                 :           0 :                         goto out;   /* "do nothing" */
    3688                 :             :                 }
    3689                 :             :                 else
    3690                 :             :                 {
    3691                 :             :                     /* checked ri_needLockTagTuple above */
    3692                 :             :                     Assert(oldtuple == NULL);
    3693                 :             : 
    3694                 :        1352 :                     result = ExecUpdateAct(context, resultRelInfo, tupleid,
    3695                 :             :                                            NULL, newslot, canSetTag,
    3696                 :             :                                            &updateCxt);
    3697                 :             : 
    3698                 :             :                     /*
    3699                 :             :                      * As in ExecUpdate(), if ExecUpdateAct() reports that a
    3700                 :             :                      * cross-partition update was done, then there's nothing
    3701                 :             :                      * else for us to do --- the UPDATE has been turned into a
    3702                 :             :                      * DELETE and an INSERT, and we must not perform any of
    3703                 :             :                      * the usual post-update tasks.  Also, the RETURNING tuple
    3704                 :             :                      * (if any) has been projected, so we can just return
    3705                 :             :                      * that.
    3706                 :             :                      */
    3707         [ +  + ]:        1337 :                     if (updateCxt.crossPartUpdate)
    3708                 :             :                     {
    3709                 :          89 :                         mtstate->mt_merge_updated += 1;
    3710                 :          89 :                         rslot = context->cpUpdateReturningSlot;
    3711                 :          89 :                         goto out;
    3712                 :             :                     }
    3713                 :             :                 }
    3714                 :             : 
    3715         [ +  + ]:        1300 :                 if (result == TM_Ok)
    3716                 :             :                 {
    3717                 :        1251 :                     ExecUpdateEpilogue(context, &updateCxt, resultRelInfo,
    3718                 :             :                                        tupleid, NULL, newslot);
    3719                 :        1243 :                     mtstate->mt_merge_updated += 1;
    3720                 :             :                 }
    3721                 :        1292 :                 break;
    3722                 :             : 
    3723                 :         351 :             case CMD_DELETE:
    3724                 :         351 :                 mtstate->mt_merge_action = relaction;
    3725         [ +  + ]:         351 :                 if (!ExecDeletePrologue(context, resultRelInfo, tupleid,
    3726                 :             :                                         NULL, NULL, &result))
    3727                 :             :                 {
    3728         [ +  + ]:           7 :                     if (result == TM_Ok)
    3729                 :           4 :                         goto out;   /* "do nothing" */
    3730                 :             : 
    3731                 :           3 :                     break;      /* concurrent update/delete */
    3732                 :             :                 }
    3733                 :             : 
    3734                 :             :                 /* INSTEAD OF ROW DELETE Triggers */
    3735         [ +  + ]:         344 :                 if (resultRelInfo->ri_TrigDesc &&
    3736         [ +  + ]:          38 :                     resultRelInfo->ri_TrigDesc->trig_delete_instead_row)
    3737                 :             :                 {
    3738         [ -  + ]:           4 :                     if (!ExecIRDeleteTriggers(estate, resultRelInfo,
    3739                 :             :                                               oldtuple))
    3740                 :           0 :                         goto out;   /* "do nothing" */
    3741                 :             :                 }
    3742                 :             :                 else
    3743                 :             :                 {
    3744                 :             :                     /* checked ri_needLockTagTuple above */
    3745                 :             :                     Assert(oldtuple == NULL);
    3746                 :             : 
    3747                 :         340 :                     result = ExecDeleteAct(context, resultRelInfo, tupleid,
    3748                 :             :                                            false);
    3749                 :             :                 }
    3750                 :             : 
    3751         [ +  + ]:         344 :                 if (result == TM_Ok)
    3752                 :             :                 {
    3753                 :         333 :                     ExecDeleteEpilogue(context, resultRelInfo, tupleid, NULL,
    3754                 :             :                                        false);
    3755                 :         333 :                     mtstate->mt_merge_deleted += 1;
    3756                 :             :                 }
    3757                 :         344 :                 break;
    3758                 :             : 
    3759                 :          20 :             case CMD_NOTHING:
    3760                 :             :                 /* Doing nothing is always OK */
    3761                 :          20 :                 result = TM_Ok;
    3762                 :          20 :                 break;
    3763                 :             : 
    3764                 :           0 :             default:
    3765         [ #  # ]:           0 :                 elog(ERROR, "unknown action in MERGE WHEN clause");
    3766                 :             :         }
    3767                 :             : 
    3768   [ +  +  +  +  :        1667 :         switch (result)
                   -  - ]
    3769                 :             :         {
    3770                 :        1596 :             case TM_Ok:
    3771                 :             :                 /* all good; perform final actions */
    3772   [ +  +  +  + ]:        1596 :                 if (canSetTag && commandType != CMD_NOTHING)
    3773                 :        1561 :                     (estate->es_processed)++;
    3774                 :             : 
    3775                 :        1596 :                 break;
    3776                 :             : 
    3777                 :          21 :             case TM_SelfModified:
    3778                 :             : 
    3779                 :             :                 /*
    3780                 :             :                  * The target tuple was already updated or deleted by the
    3781                 :             :                  * current command, or by a later command in the current
    3782                 :             :                  * transaction.  The former case is explicitly disallowed by
    3783                 :             :                  * the SQL standard for MERGE, which insists that the MERGE
    3784                 :             :                  * join condition should not join a target row to more than
    3785                 :             :                  * one source row.
    3786                 :             :                  *
    3787                 :             :                  * The latter case arises if the tuple is modified by a
    3788                 :             :                  * command in a BEFORE trigger, or perhaps by a command in a
    3789                 :             :                  * volatile function used in the query.  In such situations we
    3790                 :             :                  * should not ignore the MERGE action, but it is equally
    3791                 :             :                  * unsafe to proceed.  We don't want to discard the original
    3792                 :             :                  * MERGE action while keeping the triggered actions based on
    3793                 :             :                  * it; and it would be no better to allow the original MERGE
    3794                 :             :                  * action while discarding the updates that it triggered.  So
    3795                 :             :                  * throwing an error is the only safe course.
    3796                 :             :                  */
    3797         [ +  + ]:          21 :                 if (context->tmfd.cmax != estate->es_output_cid)
    3798         [ +  - ]:           8 :                     ereport(ERROR,
    3799                 :             :                             (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    3800                 :             :                              errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
    3801                 :             :                              errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    3802                 :             : 
    3803         [ +  - ]:          13 :                 if (TransactionIdIsCurrentTransactionId(context->tmfd.xmax))
    3804         [ +  - ]:          13 :                     ereport(ERROR,
    3805                 :             :                             (errcode(ERRCODE_CARDINALITY_VIOLATION),
    3806                 :             :                     /* translator: %s is a SQL command name */
    3807                 :             :                              errmsg("%s command cannot affect row a second time",
    3808                 :             :                                     "MERGE"),
    3809                 :             :                              errhint("Ensure that not more than one source row matches any one target row.")));
    3810                 :             : 
    3811                 :             :                 /* This shouldn't happen */
    3812         [ #  # ]:           0 :                 elog(ERROR, "attempted to update or delete invisible tuple");
    3813                 :             :                 break;
    3814                 :             : 
    3815                 :           5 :             case TM_Deleted:
    3816         [ -  + ]:           5 :                 if (IsolationUsesXactSnapshot())
    3817         [ #  # ]:           0 :                     ereport(ERROR,
    3818                 :             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3819                 :             :                              errmsg("could not serialize access due to concurrent delete")));
    3820                 :             : 
    3821                 :             :                 /*
    3822                 :             :                  * If the tuple was already deleted, set matched to false to
    3823                 :             :                  * let caller handle it under NOT MATCHED [BY TARGET] clauses.
    3824                 :             :                  */
    3825                 :           5 :                 *matched = false;
    3826                 :           5 :                 goto out;
    3827                 :             : 
    3828                 :          45 :             case TM_Updated:
    3829                 :             :                 {
    3830                 :             :                     bool        was_matched;
    3831                 :             :                     Relation    resultRelationDesc;
    3832                 :             :                     TupleTableSlot *epqslot,
    3833                 :             :                                *inputslot;
    3834                 :             :                     LockTupleMode lockmode;
    3835                 :             : 
    3836         [ +  + ]:          45 :                     if (IsolationUsesXactSnapshot())
    3837         [ +  - ]:           1 :                         ereport(ERROR,
    3838                 :             :                                 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3839                 :             :                                  errmsg("could not serialize access due to concurrent update")));
    3840                 :             : 
    3841                 :             :                     /*
    3842                 :             :                      * The target tuple was concurrently updated by some other
    3843                 :             :                      * transaction.  If we are currently processing a MATCHED
    3844                 :             :                      * action, use EvalPlanQual() with the new version of the
    3845                 :             :                      * tuple and recheck the join qual, to detect a change
    3846                 :             :                      * from the MATCHED to the NOT MATCHED cases.  If we are
    3847                 :             :                      * already processing a NOT MATCHED BY SOURCE action, we
    3848                 :             :                      * skip this (cannot switch from NOT MATCHED BY SOURCE to
    3849                 :             :                      * MATCHED).
    3850                 :             :                      */
    3851                 :          44 :                     was_matched = relaction->mas_action->matchKind == MERGE_WHEN_MATCHED;
    3852                 :          44 :                     resultRelationDesc = resultRelInfo->ri_RelationDesc;
    3853                 :          44 :                     lockmode = ExecUpdateLockMode(estate, resultRelInfo);
    3854                 :             : 
    3855         [ +  - ]:          44 :                     if (was_matched)
    3856                 :          44 :                         inputslot = EvalPlanQualSlot(epqstate, resultRelationDesc,
    3857                 :             :                                                      resultRelInfo->ri_RangeTableIndex);
    3858                 :             :                     else
    3859                 :           0 :                         inputslot = resultRelInfo->ri_oldTupleSlot;
    3860                 :             : 
    3861                 :          44 :                     result = table_tuple_lock(resultRelationDesc, tupleid,
    3862                 :             :                                               estate->es_snapshot,
    3863                 :             :                                               inputslot, estate->es_output_cid,
    3864                 :             :                                               lockmode, LockWaitBlock,
    3865                 :             :                                               TUPLE_LOCK_FLAG_FIND_LAST_VERSION,
    3866                 :             :                                               &context->tmfd);
    3867   [ +  -  +  - ]:          44 :                     switch (result)
    3868                 :             :                     {
    3869                 :          43 :                         case TM_Ok:
    3870                 :             : 
    3871                 :             :                             /*
    3872                 :             :                              * If the tuple was updated and migrated to
    3873                 :             :                              * another partition concurrently, the current
    3874                 :             :                              * MERGE implementation can't follow.  There's
    3875                 :             :                              * probably a better way to handle this case, but
    3876                 :             :                              * it'd require recognizing the relation to which
    3877                 :             :                              * the tuple moved, and setting our current
    3878                 :             :                              * resultRelInfo to that.
    3879                 :             :                              */
    3880         [ -  + ]:          43 :                             if (ItemPointerIndicatesMovedPartitions(tupleid))
    3881         [ #  # ]:           0 :                                 ereport(ERROR,
    3882                 :             :                                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3883                 :             :                                          errmsg("tuple to be merged was already moved to another partition due to concurrent update")));
    3884                 :             : 
    3885                 :             :                             /*
    3886                 :             :                              * If this was a MATCHED case, use EvalPlanQual()
    3887                 :             :                              * to recheck the join condition.
    3888                 :             :                              */
    3889         [ +  - ]:          43 :                             if (was_matched)
    3890                 :             :                             {
    3891                 :          43 :                                 epqslot = EvalPlanQual(epqstate,
    3892                 :             :                                                        resultRelationDesc,
    3893                 :             :                                                        resultRelInfo->ri_RangeTableIndex,
    3894                 :             :                                                        inputslot);
    3895                 :             : 
    3896                 :             :                                 /*
    3897                 :             :                                  * If the subplan didn't return a tuple, then
    3898                 :             :                                  * we must be dealing with an inner join for
    3899                 :             :                                  * which the join condition no longer matches.
    3900                 :             :                                  * This can only happen if there are no NOT
    3901                 :             :                                  * MATCHED actions, and so there is nothing
    3902                 :             :                                  * more to do.
    3903                 :             :                                  */
    3904   [ +  -  -  + ]:          43 :                                 if (TupIsNull(epqslot))
    3905                 :           0 :                                     goto out;
    3906                 :             : 
    3907                 :             :                                 /*
    3908                 :             :                                  * If we got a NULL ctid from the subplan, the
    3909                 :             :                                  * join quals no longer pass and we switch to
    3910                 :             :                                  * the NOT MATCHED BY SOURCE case.
    3911                 :             :                                  */
    3912                 :          43 :                                 (void) ExecGetJunkAttribute(epqslot,
    3913                 :          43 :                                                             resultRelInfo->ri_RowIdAttNo,
    3914                 :             :                                                             &isNull);
    3915         [ +  + ]:          43 :                                 if (isNull)
    3916                 :           2 :                                     *matched = false;
    3917                 :             : 
    3918                 :             :                                 /*
    3919                 :             :                                  * Otherwise, recheck the join quals to see if
    3920                 :             :                                  * we need to switch to the NOT MATCHED BY
    3921                 :             :                                  * SOURCE case.
    3922                 :             :                                  */
    3923         [ +  + ]:          43 :                                 if (resultRelInfo->ri_needLockTagTuple)
    3924                 :             :                                 {
    3925         [ +  - ]:           1 :                                     if (ItemPointerIsValid(&lockedtid))
    3926                 :           1 :                                         UnlockTuple(resultRelInfo->ri_RelationDesc, &lockedtid,
    3927                 :             :                                                     InplaceUpdateTupleLock);
    3928                 :           1 :                                     LockTuple(resultRelInfo->ri_RelationDesc, tupleid,
    3929                 :             :                                               InplaceUpdateTupleLock);
    3930                 :           1 :                                     lockedtid = *tupleid;
    3931                 :             :                                 }
    3932                 :             : 
    3933         [ -  + ]:          43 :                                 if (!table_tuple_fetch_row_version(resultRelationDesc,
    3934                 :             :                                                                    tupleid,
    3935                 :             :                                                                    SnapshotAny,
    3936                 :             :                                                                    resultRelInfo->ri_oldTupleSlot))
    3937         [ #  # ]:           0 :                                     elog(ERROR, "failed to fetch the target tuple");
    3938                 :             : 
    3939         [ +  + ]:          43 :                                 if (*matched)
    3940                 :          41 :                                     *matched = ExecQual(resultRelInfo->ri_MergeJoinCondition,
    3941                 :             :                                                         econtext);
    3942                 :             : 
    3943                 :             :                                 /* Switch lists, if necessary */
    3944         [ +  + ]:          43 :                                 if (!*matched)
    3945                 :             :                                 {
    3946                 :           4 :                                     actionStates = mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE];
    3947                 :             : 
    3948                 :             :                                     /*
    3949                 :             :                                      * If we have both NOT MATCHED BY SOURCE
    3950                 :             :                                      * and NOT MATCHED BY TARGET actions (a
    3951                 :             :                                      * full join between the source and target
    3952                 :             :                                      * relations), the single previously
    3953                 :             :                                      * matched tuple from the outer plan node
    3954                 :             :                                      * is treated as two not matched tuples,
    3955                 :             :                                      * in the same way as if they had not
    3956                 :             :                                      * matched to start with.  Therefore, we
    3957                 :             :                                      * must adjust the outer plan node's tuple
    3958                 :             :                                      * count, if we're instrumenting the
    3959                 :             :                                      * query, to get the correct "skipped" row
    3960                 :             :                                      * count --- see show_modifytable_info().
    3961                 :             :                                      */
    3962         [ +  + ]:           4 :                                     if (outerPlanState(mtstate)->instrument &&
    3963         [ +  - ]:           1 :                                         mergeActions[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
    3964         [ +  - ]:           1 :                                         mergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
    3965                 :           1 :                                         InstrUpdateTupleCount(outerPlanState(mtstate)->instrument, 1.0);
    3966                 :             :                                 }
    3967                 :             :                             }
    3968                 :             : 
    3969                 :             :                             /*
    3970                 :             :                              * Loop back and process the MATCHED or NOT
    3971                 :             :                              * MATCHED BY SOURCE actions from the start.
    3972                 :             :                              */
    3973                 :          43 :                             goto lmerge_matched;
    3974                 :             : 
    3975                 :           0 :                         case TM_Deleted:
    3976                 :             : 
    3977                 :             :                             /*
    3978                 :             :                              * tuple already deleted; tell caller to run NOT
    3979                 :             :                              * MATCHED [BY TARGET] actions
    3980                 :             :                              */
    3981                 :           0 :                             *matched = false;
    3982                 :           0 :                             goto out;
    3983                 :             : 
    3984                 :           1 :                         case TM_SelfModified:
    3985                 :             : 
    3986                 :             :                             /*
    3987                 :             :                              * This can be reached when following an update
    3988                 :             :                              * chain from a tuple updated by another session,
    3989                 :             :                              * reaching a tuple that was already updated or
    3990                 :             :                              * deleted by the current command, or by a later
    3991                 :             :                              * command in the current transaction. As above,
    3992                 :             :                              * this should always be treated as an error.
    3993                 :             :                              */
    3994         [ -  + ]:           1 :                             if (context->tmfd.cmax != estate->es_output_cid)
    3995         [ #  # ]:           0 :                                 ereport(ERROR,
    3996                 :             :                                         (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    3997                 :             :                                          errmsg("tuple to be updated or deleted was already modified by an operation triggered by the current command"),
    3998                 :             :                                          errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    3999                 :             : 
    4000         [ +  - ]:           1 :                             if (TransactionIdIsCurrentTransactionId(context->tmfd.xmax))
    4001         [ +  - ]:           1 :                                 ereport(ERROR,
    4002                 :             :                                         (errcode(ERRCODE_CARDINALITY_VIOLATION),
    4003                 :             :                                 /* translator: %s is a SQL command name */
    4004                 :             :                                          errmsg("%s command cannot affect row a second time",
    4005                 :             :                                                 "MERGE"),
    4006                 :             :                                          errhint("Ensure that not more than one source row matches any one target row.")));
    4007                 :             : 
    4008                 :             :                             /* This shouldn't happen */
    4009         [ #  # ]:           0 :                             elog(ERROR, "attempted to update or delete invisible tuple");
    4010                 :             :                             goto out;
    4011                 :             : 
    4012                 :           0 :                         default:
    4013                 :             :                             /* see table_tuple_lock call in ExecDelete() */
    4014         [ #  # ]:           0 :                             elog(ERROR, "unexpected table_tuple_lock status: %u",
    4015                 :             :                                  result);
    4016                 :             :                             goto out;
    4017                 :             :                     }
    4018                 :             :                 }
    4019                 :             : 
    4020                 :           0 :             case TM_Invisible:
    4021                 :             :             case TM_WouldBlock:
    4022                 :             :             case TM_BeingModified:
    4023                 :             :                 /* these should not occur */
    4024         [ #  # ]:           0 :                 elog(ERROR, "unexpected tuple operation result: %d", result);
    4025                 :             :                 break;
    4026                 :             :         }
    4027                 :             : 
    4028                 :             :         /* Process RETURNING if present */
    4029         [ +  + ]:        1596 :         if (resultRelInfo->ri_projectReturning)
    4030                 :             :         {
    4031   [ +  +  -  - ]:         296 :             switch (commandType)
    4032                 :             :             {
    4033                 :         129 :                 case CMD_UPDATE:
    4034                 :         129 :                     rslot = ExecProcessReturning(context,
    4035                 :             :                                                  resultRelInfo,
    4036                 :             :                                                  false,
    4037                 :             :                                                  resultRelInfo->ri_oldTupleSlot,
    4038                 :             :                                                  newslot,
    4039                 :             :                                                  context->planSlot);
    4040                 :         129 :                     break;
    4041                 :             : 
    4042                 :         167 :                 case CMD_DELETE:
    4043                 :         167 :                     rslot = ExecProcessReturning(context,
    4044                 :             :                                                  resultRelInfo,
    4045                 :             :                                                  true,
    4046                 :             :                                                  resultRelInfo->ri_oldTupleSlot,
    4047                 :             :                                                  NULL,
    4048                 :             :                                                  context->planSlot);
    4049                 :         167 :                     break;
    4050                 :             : 
    4051                 :           0 :                 case CMD_NOTHING:
    4052                 :           0 :                     break;
    4053                 :             : 
    4054                 :           0 :                 default:
    4055         [ #  # ]:           0 :                     elog(ERROR, "unrecognized commandType: %d",
    4056                 :             :                          (int) commandType);
    4057                 :             :             }
    4058                 :             :         }
    4059                 :             : 
    4060                 :             :         /*
    4061                 :             :          * We've activated one of the WHEN clauses, so we don't search
    4062                 :             :          * further. This is required behaviour, not an optimization.
    4063                 :             :          */
    4064                 :        1596 :         break;
    4065                 :             :     }
    4066                 :             : 
    4067                 :             :     /*
    4068                 :             :      * Successfully executed an action or no qualifying action was found.
    4069                 :             :      */
    4070                 :        8256 : out:
    4071         [ +  + ]:        8256 :     if (ItemPointerIsValid(&lockedtid))
    4072                 :        5634 :         UnlockTuple(resultRelInfo->ri_RelationDesc, &lockedtid,
    4073                 :             :                     InplaceUpdateTupleLock);
    4074                 :        8256 :     return rslot;
    4075                 :             : }
    4076                 :             : 
    4077                 :             : /*
    4078                 :             :  * Execute the first qualifying NOT MATCHED [BY TARGET] action.
    4079                 :             :  */
    4080                 :             : static TupleTableSlot *
    4081                 :        1800 : ExecMergeNotMatched(ModifyTableContext *context, ResultRelInfo *resultRelInfo,
    4082                 :             :                     bool canSetTag)
    4083                 :             : {
    4084                 :        1800 :     ModifyTableState *mtstate = context->mtstate;
    4085                 :        1800 :     ExprContext *econtext = mtstate->ps.ps_ExprContext;
    4086                 :             :     List       *actionStates;
    4087                 :        1800 :     TupleTableSlot *rslot = NULL;
    4088                 :             :     ListCell   *l;
    4089                 :             : 
    4090                 :             :     /*
    4091                 :             :      * For INSERT actions, the root relation's merge action is OK since the
    4092                 :             :      * INSERT's targetlist and the WHEN conditions can only refer to the
    4093                 :             :      * source relation and hence it does not matter which result relation we
    4094                 :             :      * work with.
    4095                 :             :      *
    4096                 :             :      * XXX does this mean that we can avoid creating copies of actionStates on
    4097                 :             :      * partitioned tables, for not-matched actions?
    4098                 :             :      */
    4099                 :        1800 :     actionStates = resultRelInfo->ri_MergeActions[MERGE_WHEN_NOT_MATCHED_BY_TARGET];
    4100                 :             : 
    4101                 :             :     /*
    4102                 :             :      * Make source tuple available to ExecQual and ExecProject. We don't need
    4103                 :             :      * the target tuple, since the WHEN quals and targetlist can't refer to
    4104                 :             :      * the target columns.
    4105                 :             :      */
    4106                 :        1800 :     econtext->ecxt_scantuple = NULL;
    4107                 :        1800 :     econtext->ecxt_innertuple = context->planSlot;
    4108                 :        1800 :     econtext->ecxt_outertuple = NULL;
    4109                 :             : 
    4110   [ +  -  +  +  :        2380 :     foreach(l, actionStates)
                   +  + ]
    4111                 :             :     {
    4112                 :        1800 :         MergeActionState *action = (MergeActionState *) lfirst(l);
    4113                 :        1800 :         CmdType     commandType = action->mas_action->commandType;
    4114                 :             :         TupleTableSlot *newslot;
    4115                 :             : 
    4116                 :             :         /*
    4117                 :             :          * Test condition, if any.
    4118                 :             :          *
    4119                 :             :          * In the absence of any condition, we perform the action
    4120                 :             :          * unconditionally (no need to check separately since ExecQual() will
    4121                 :             :          * return true if there are no conditions to evaluate).
    4122                 :             :          */
    4123         [ +  + ]:        1800 :         if (!ExecQual(action->mas_whenqual, econtext))
    4124                 :         580 :             continue;
    4125                 :             : 
    4126                 :             :         /* Perform stated action */
    4127      [ +  -  - ]:        1220 :         switch (commandType)
    4128                 :             :         {
    4129                 :        1220 :             case CMD_INSERT:
    4130                 :             : 
    4131                 :             :                 /*
    4132                 :             :                  * Project the tuple.  In case of a partitioned table, the
    4133                 :             :                  * projection was already built to use the root's descriptor,
    4134                 :             :                  * so we don't need to map the tuple here.
    4135                 :             :                  */
    4136                 :        1220 :                 newslot = ExecProject(action->mas_proj);
    4137                 :        1220 :                 mtstate->mt_merge_action = action;
    4138                 :             : 
    4139                 :        1220 :                 rslot = ExecInsert(context, mtstate->rootResultRelInfo,
    4140                 :             :                                    newslot, canSetTag, NULL, NULL);
    4141                 :        1181 :                 mtstate->mt_merge_inserted += 1;
    4142                 :        1181 :                 break;
    4143                 :           0 :             case CMD_NOTHING:
    4144                 :             :                 /* Do nothing */
    4145                 :           0 :                 break;
    4146                 :           0 :             default:
    4147         [ #  # ]:           0 :                 elog(ERROR, "unknown action in MERGE WHEN NOT MATCHED clause");
    4148                 :             :         }
    4149                 :             : 
    4150                 :             :         /*
    4151                 :             :          * We've activated one of the WHEN clauses, so we don't search
    4152                 :             :          * further. This is required behaviour, not an optimization.
    4153                 :             :          */
    4154                 :        1181 :         break;
    4155                 :             :     }
    4156                 :             : 
    4157                 :        1761 :     return rslot;
    4158                 :             : }
    4159                 :             : 
    4160                 :             : /*
    4161                 :             :  * Initialize state for execution of MERGE.
    4162                 :             :  */
    4163                 :             : void
    4164                 :        1060 : ExecInitMerge(ModifyTableState *mtstate, EState *estate)
    4165                 :             : {
    4166                 :        1060 :     List       *mergeActionLists = mtstate->mt_mergeActionLists;
    4167                 :        1060 :     List       *mergeJoinConditions = mtstate->mt_mergeJoinConditions;
    4168                 :        1060 :     ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
    4169                 :             :     ResultRelInfo *resultRelInfo;
    4170                 :             :     ExprContext *econtext;
    4171                 :             :     ListCell   *lc;
    4172                 :             :     int         i;
    4173                 :             : 
    4174         [ -  + ]:        1060 :     if (mergeActionLists == NIL)
    4175                 :           0 :         return;
    4176                 :             : 
    4177                 :        1060 :     mtstate->mt_merge_subcommands = 0;
    4178                 :             : 
    4179         [ +  + ]:        1060 :     if (mtstate->ps.ps_ExprContext == NULL)
    4180                 :         857 :         ExecAssignExprContext(estate, &mtstate->ps);
    4181                 :        1060 :     econtext = mtstate->ps.ps_ExprContext;
    4182                 :             : 
    4183                 :             :     /*
    4184                 :             :      * Create a MergeActionState for each action on the mergeActionList and
    4185                 :             :      * add it to either a list of matched actions or not-matched actions.
    4186                 :             :      *
    4187                 :             :      * Similar logic appears in ExecInitPartitionInfo(), so if changing
    4188                 :             :      * anything here, do so there too.
    4189                 :             :      */
    4190                 :        1060 :     i = 0;
    4191   [ +  -  +  +  :        2277 :     foreach(lc, mergeActionLists)
                   +  + ]
    4192                 :             :     {
    4193                 :        1217 :         List       *mergeActionList = lfirst(lc);
    4194                 :             :         Node       *joinCondition;
    4195                 :             :         TupleDesc   relationDesc;
    4196                 :             :         ListCell   *l;
    4197                 :             : 
    4198                 :        1217 :         joinCondition = (Node *) list_nth(mergeJoinConditions, i);
    4199                 :        1217 :         resultRelInfo = mtstate->resultRelInfo + i;
    4200                 :        1217 :         i++;
    4201                 :        1217 :         relationDesc = RelationGetDescr(resultRelInfo->ri_RelationDesc);
    4202                 :             : 
    4203                 :             :         /* initialize slots for MERGE fetches from this rel */
    4204         [ +  - ]:        1217 :         if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
    4205                 :        1217 :             ExecInitMergeTupleSlots(mtstate, resultRelInfo);
    4206                 :             : 
    4207                 :             :         /* initialize state for join condition checking */
    4208                 :        1217 :         resultRelInfo->ri_MergeJoinCondition =
    4209                 :        1217 :             ExecInitQual((List *) joinCondition, &mtstate->ps);
    4210                 :             : 
    4211   [ +  -  +  +  :        3361 :         foreach(l, mergeActionList)
                   +  + ]
    4212                 :             :         {
    4213                 :        2144 :             MergeAction *action = (MergeAction *) lfirst(l);
    4214                 :             :             MergeActionState *action_state;
    4215                 :             :             TupleTableSlot *tgtslot;
    4216                 :             :             TupleDesc   tgtdesc;
    4217                 :             : 
    4218                 :             :             /*
    4219                 :             :              * Build action merge state for this rel.  (For partitions,
    4220                 :             :              * equivalent code exists in ExecInitPartitionInfo.)
    4221                 :             :              */
    4222                 :        2144 :             action_state = makeNode(MergeActionState);
    4223                 :        2144 :             action_state->mas_action = action;
    4224                 :        2144 :             action_state->mas_whenqual = ExecInitQual((List *) action->qual,
    4225                 :             :                                                       &mtstate->ps);
    4226                 :             : 
    4227                 :             :             /*
    4228                 :             :              * We create three lists - one for each MergeMatchKind - and stick
    4229                 :             :              * the MergeActionState into the appropriate list.
    4230                 :             :              */
    4231                 :        4288 :             resultRelInfo->ri_MergeActions[action->matchKind] =
    4232                 :        2144 :                 lappend(resultRelInfo->ri_MergeActions[action->matchKind],
    4233                 :             :                         action_state);
    4234                 :             : 
    4235   [ +  +  +  +  :        2144 :             switch (action->commandType)
                      - ]
    4236                 :             :             {
    4237                 :         704 :                 case CMD_INSERT:
    4238                 :             :                     /* INSERT actions always use rootRelInfo */
    4239                 :         704 :                     ExecCheckPlanOutput(rootRelInfo->ri_RelationDesc,
    4240                 :             :                                         action->targetList);
    4241                 :             : 
    4242                 :             :                     /*
    4243                 :             :                      * If the MERGE targets a partitioned table, any INSERT
    4244                 :             :                      * actions must be routed through it, not the child
    4245                 :             :                      * relations. Initialize the routing struct and the root
    4246                 :             :                      * table's "new" tuple slot for that, if not already done.
    4247                 :             :                      * The projection we prepare, for all relations, uses the
    4248                 :             :                      * root relation descriptor, and targets the plan's root
    4249                 :             :                      * slot.  (This is consistent with the fact that we
    4250                 :             :                      * checked the plan output to match the root relation,
    4251                 :             :                      * above.)
    4252                 :             :                      */
    4253         [ +  + ]:         704 :                     if (rootRelInfo->ri_RelationDesc->rd_rel->relkind ==
    4254                 :             :                         RELKIND_PARTITIONED_TABLE)
    4255                 :             :                     {
    4256         [ +  + ]:         216 :                         if (mtstate->mt_partition_tuple_routing == NULL)
    4257                 :             :                         {
    4258                 :             :                             /*
    4259                 :             :                              * Initialize planstate for routing if not already
    4260                 :             :                              * done.
    4261                 :             :                              *
    4262                 :             :                              * Note that the slot is managed as a standalone
    4263                 :             :                              * slot belonging to ModifyTableState, so we pass
    4264                 :             :                              * NULL for the 2nd argument.
    4265                 :             :                              */
    4266                 :         100 :                             mtstate->mt_root_tuple_slot =
    4267                 :         100 :                                 table_slot_create(rootRelInfo->ri_RelationDesc,
    4268                 :             :                                                   NULL);
    4269                 :         100 :                             mtstate->mt_partition_tuple_routing =
    4270                 :         100 :                                 ExecSetupPartitionTupleRouting(estate,
    4271                 :             :                                                                rootRelInfo->ri_RelationDesc);
    4272                 :             :                         }
    4273                 :         216 :                         tgtslot = mtstate->mt_root_tuple_slot;
    4274                 :         216 :                         tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
    4275                 :             :                     }
    4276                 :             :                     else
    4277                 :             :                     {
    4278                 :             :                         /*
    4279                 :             :                          * If the MERGE targets an inherited table, we insert
    4280                 :             :                          * into the root table, so we must initialize its
    4281                 :             :                          * "new" tuple slot, if not already done, and use its
    4282                 :             :                          * relation descriptor for the projection.
    4283                 :             :                          *
    4284                 :             :                          * For non-inherited tables, rootRelInfo and
    4285                 :             :                          * resultRelInfo are the same, and the "new" tuple
    4286                 :             :                          * slot will already have been initialized.
    4287                 :             :                          */
    4288         [ +  + ]:         488 :                         if (rootRelInfo->ri_newTupleSlot == NULL)
    4289                 :          24 :                             rootRelInfo->ri_newTupleSlot =
    4290                 :          24 :                                 table_slot_create(rootRelInfo->ri_RelationDesc,
    4291                 :             :                                                   &estate->es_tupleTable);
    4292                 :             : 
    4293                 :         488 :                         tgtslot = rootRelInfo->ri_newTupleSlot;
    4294                 :         488 :                         tgtdesc = RelationGetDescr(rootRelInfo->ri_RelationDesc);
    4295                 :             :                     }
    4296                 :             : 
    4297                 :         704 :                     action_state->mas_proj =
    4298                 :         704 :                         ExecBuildProjectionInfo(action->targetList, econtext,
    4299                 :             :                                                 tgtslot,
    4300                 :             :                                                 &mtstate->ps,
    4301                 :             :                                                 tgtdesc);
    4302                 :             : 
    4303                 :         704 :                     mtstate->mt_merge_subcommands |= MERGE_INSERT;
    4304                 :         704 :                     break;
    4305                 :        1055 :                 case CMD_UPDATE:
    4306                 :        1055 :                     action_state->mas_proj =
    4307                 :        1055 :                         ExecBuildUpdateProjection(action->targetList,
    4308                 :             :                                                   true,
    4309                 :             :                                                   action->updateColnos,
    4310                 :             :                                                   relationDesc,
    4311                 :             :                                                   econtext,
    4312                 :             :                                                   resultRelInfo->ri_newTupleSlot,
    4313                 :             :                                                   &mtstate->ps);
    4314                 :        1055 :                     mtstate->mt_merge_subcommands |= MERGE_UPDATE;
    4315                 :        1055 :                     break;
    4316                 :         335 :                 case CMD_DELETE:
    4317                 :         335 :                     mtstate->mt_merge_subcommands |= MERGE_DELETE;
    4318                 :         335 :                     break;
    4319                 :          50 :                 case CMD_NOTHING:
    4320                 :          50 :                     break;
    4321                 :           0 :                 default:
    4322         [ #  # ]:           0 :                     elog(ERROR, "unknown action in MERGE WHEN clause");
    4323                 :             :                     break;
    4324                 :             :             }
    4325                 :             :         }
    4326                 :             :     }
    4327                 :             : 
    4328                 :             :     /*
    4329                 :             :      * If the MERGE targets an inherited table, any INSERT actions will use
    4330                 :             :      * rootRelInfo, and rootRelInfo will not be in the resultRelInfo array.
    4331                 :             :      * Therefore we must initialize its WITH CHECK OPTION constraints and
    4332                 :             :      * RETURNING projection, as ExecInitModifyTable did for the resultRelInfo
    4333                 :             :      * entries.
    4334                 :             :      *
    4335                 :             :      * Note that the planner does not build a withCheckOptionList or
    4336                 :             :      * returningList for the root relation, but as in ExecInitPartitionInfo,
    4337                 :             :      * we can use the first resultRelInfo entry as a reference to calculate
    4338                 :             :      * the attno's for the root table.
    4339                 :             :      */
    4340         [ +  + ]:        1060 :     if (rootRelInfo != mtstate->resultRelInfo &&
    4341         [ +  + ]:         160 :         rootRelInfo->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
    4342         [ +  + ]:          32 :         (mtstate->mt_merge_subcommands & MERGE_INSERT) != 0)
    4343                 :             :     {
    4344                 :          24 :         ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
    4345                 :          24 :         Relation    rootRelation = rootRelInfo->ri_RelationDesc;
    4346                 :          24 :         Relation    firstResultRel = mtstate->resultRelInfo[0].ri_RelationDesc;
    4347                 :          24 :         int         firstVarno = mtstate->resultRelInfo[0].ri_RangeTableIndex;
    4348                 :          24 :         AttrMap    *part_attmap = NULL;
    4349                 :             :         bool        found_whole_row;
    4350                 :             : 
    4351         [ +  + ]:          24 :         if (node->withCheckOptionLists != NIL)
    4352                 :             :         {
    4353                 :             :             List       *wcoList;
    4354                 :          12 :             List       *wcoExprs = NIL;
    4355                 :             : 
    4356                 :             :             /* There should be as many WCO lists as result rels */
    4357                 :             :             Assert(list_length(node->withCheckOptionLists) ==
    4358                 :             :                    list_length(node->resultRelations));
    4359                 :             : 
    4360                 :             :             /*
    4361                 :             :              * Use the first WCO list as a reference. In the most common case,
    4362                 :             :              * this will be for the same relation as rootRelInfo, and so there
    4363                 :             :              * will be no need to adjust its attno's.
    4364                 :             :              */
    4365                 :          12 :             wcoList = linitial(node->withCheckOptionLists);
    4366         [ +  - ]:          12 :             if (rootRelation != firstResultRel)
    4367                 :             :             {
    4368                 :             :                 /* Convert any Vars in it to contain the root's attno's */
    4369                 :             :                 part_attmap =
    4370                 :          12 :                     build_attrmap_by_name(RelationGetDescr(rootRelation),
    4371                 :             :                                           RelationGetDescr(firstResultRel),
    4372                 :             :                                           false);
    4373                 :             : 
    4374                 :             :                 wcoList = (List *)
    4375                 :          12 :                     map_variable_attnos((Node *) wcoList,
    4376                 :             :                                         firstVarno, 0,
    4377                 :             :                                         part_attmap,
    4378                 :          12 :                                         RelationGetForm(rootRelation)->reltype,
    4379                 :             :                                         &found_whole_row);
    4380                 :             :             }
    4381                 :             : 
    4382   [ +  -  +  +  :          60 :             foreach(lc, wcoList)
                   +  + ]
    4383                 :             :             {
    4384                 :          48 :                 WithCheckOption *wco = lfirst_node(WithCheckOption, lc);
    4385                 :          48 :                 ExprState  *wcoExpr = ExecInitQual(castNode(List, wco->qual),
    4386                 :             :                                                    &mtstate->ps);
    4387                 :             : 
    4388                 :          48 :                 wcoExprs = lappend(wcoExprs, wcoExpr);
    4389                 :             :             }
    4390                 :             : 
    4391                 :          12 :             rootRelInfo->ri_WithCheckOptions = wcoList;
    4392                 :          12 :             rootRelInfo->ri_WithCheckOptionExprs = wcoExprs;
    4393                 :             :         }
    4394                 :             : 
    4395         [ +  + ]:          24 :         if (node->returningLists != NIL)
    4396                 :             :         {
    4397                 :             :             List       *returningList;
    4398                 :             : 
    4399                 :             :             /* There should be as many returning lists as result rels */
    4400                 :             :             Assert(list_length(node->returningLists) ==
    4401                 :             :                    list_length(node->resultRelations));
    4402                 :             : 
    4403                 :             :             /*
    4404                 :             :              * Use the first returning list as a reference. In the most common
    4405                 :             :              * case, this will be for the same relation as rootRelInfo, and so
    4406                 :             :              * there will be no need to adjust its attno's.
    4407                 :             :              */
    4408                 :           4 :             returningList = linitial(node->returningLists);
    4409         [ +  - ]:           4 :             if (rootRelation != firstResultRel)
    4410                 :             :             {
    4411                 :             :                 /* Convert any Vars in it to contain the root's attno's */
    4412         [ -  + ]:           4 :                 if (part_attmap == NULL)
    4413                 :             :                     part_attmap =
    4414                 :           0 :                         build_attrmap_by_name(RelationGetDescr(rootRelation),
    4415                 :             :                                               RelationGetDescr(firstResultRel),
    4416                 :             :                                               false);
    4417                 :             : 
    4418                 :             :                 returningList = (List *)
    4419                 :           4 :                     map_variable_attnos((Node *) returningList,
    4420                 :             :                                         firstVarno, 0,
    4421                 :             :                                         part_attmap,
    4422                 :           4 :                                         RelationGetForm(rootRelation)->reltype,
    4423                 :             :                                         &found_whole_row);
    4424                 :             :             }
    4425                 :           4 :             rootRelInfo->ri_returningList = returningList;
    4426                 :             : 
    4427                 :             :             /* Initialize the RETURNING projection */
    4428                 :           4 :             rootRelInfo->ri_projectReturning =
    4429                 :           4 :                 ExecBuildProjectionInfo(returningList, econtext,
    4430                 :             :                                         mtstate->ps.ps_ResultTupleSlot,
    4431                 :             :                                         &mtstate->ps,
    4432                 :             :                                         RelationGetDescr(rootRelation));
    4433                 :             :         }
    4434                 :             :     }
    4435                 :             : }
    4436                 :             : 
    4437                 :             : /*
    4438                 :             :  * Initializes the tuple slots in a ResultRelInfo for any MERGE action.
    4439                 :             :  *
    4440                 :             :  * We mark 'projectNewInfoValid' even though the projections themselves
    4441                 :             :  * are not initialized here.
    4442                 :             :  */
    4443                 :             : void
    4444                 :        1232 : ExecInitMergeTupleSlots(ModifyTableState *mtstate,
    4445                 :             :                         ResultRelInfo *resultRelInfo)
    4446                 :             : {
    4447                 :        1232 :     EState     *estate = mtstate->ps.state;
    4448                 :             : 
    4449                 :             :     Assert(!resultRelInfo->ri_projectNewInfoValid);
    4450                 :             : 
    4451                 :        1232 :     resultRelInfo->ri_oldTupleSlot =
    4452                 :        1232 :         table_slot_create(resultRelInfo->ri_RelationDesc,
    4453                 :             :                           &estate->es_tupleTable);
    4454                 :        1232 :     resultRelInfo->ri_newTupleSlot =
    4455                 :        1232 :         table_slot_create(resultRelInfo->ri_RelationDesc,
    4456                 :             :                           &estate->es_tupleTable);
    4457                 :        1232 :     resultRelInfo->ri_projectNewInfoValid = true;
    4458                 :        1232 : }
    4459                 :             : 
    4460                 :             : /*
    4461                 :             :  * Process BEFORE EACH STATEMENT triggers
    4462                 :             :  */
    4463                 :             : static void
    4464                 :       77394 : fireBSTriggers(ModifyTableState *node)
    4465                 :             : {
    4466                 :       77394 :     ModifyTable *plan = (ModifyTable *) node->ps.plan;
    4467                 :       77394 :     ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
    4468                 :             : 
    4469   [ +  +  +  +  :       77394 :     switch (node->operation)
                      - ]
    4470                 :             :     {
    4471                 :       58993 :         case CMD_INSERT:
    4472                 :       58993 :             ExecBSInsertTriggers(node->ps.state, resultRelInfo);
    4473         [ +  + ]:       58985 :             if (plan->onConflictAction == ONCONFLICT_UPDATE)
    4474                 :         617 :                 ExecBSUpdateTriggers(node->ps.state,
    4475                 :             :                                      resultRelInfo);
    4476                 :       58985 :             break;
    4477                 :        9057 :         case CMD_UPDATE:
    4478                 :        9057 :             ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
    4479                 :        9057 :             break;
    4480                 :        8384 :         case CMD_DELETE:
    4481                 :        8384 :             ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
    4482                 :        8384 :             break;
    4483                 :         960 :         case CMD_MERGE:
    4484         [ +  + ]:         960 :             if (node->mt_merge_subcommands & MERGE_INSERT)
    4485                 :         523 :                 ExecBSInsertTriggers(node->ps.state, resultRelInfo);
    4486         [ +  + ]:         960 :             if (node->mt_merge_subcommands & MERGE_UPDATE)
    4487                 :         632 :                 ExecBSUpdateTriggers(node->ps.state, resultRelInfo);
    4488         [ +  + ]:         960 :             if (node->mt_merge_subcommands & MERGE_DELETE)
    4489                 :         271 :                 ExecBSDeleteTriggers(node->ps.state, resultRelInfo);
    4490                 :         960 :             break;
    4491                 :           0 :         default:
    4492         [ #  # ]:           0 :             elog(ERROR, "unknown operation");
    4493                 :             :             break;
    4494                 :             :     }
    4495                 :       77386 : }
    4496                 :             : 
    4497                 :             : /*
    4498                 :             :  * Process AFTER EACH STATEMENT triggers
    4499                 :             :  */
    4500                 :             : static void
    4501                 :       75047 : fireASTriggers(ModifyTableState *node)
    4502                 :             : {
    4503                 :       75047 :     ModifyTable *plan = (ModifyTable *) node->ps.plan;
    4504                 :       75047 :     ResultRelInfo *resultRelInfo = node->rootResultRelInfo;
    4505                 :             : 
    4506   [ +  +  +  +  :       75047 :     switch (node->operation)
                      - ]
    4507                 :             :     {
    4508                 :       57373 :         case CMD_INSERT:
    4509         [ +  + ]:       57373 :             if (plan->onConflictAction == ONCONFLICT_UPDATE)
    4510                 :         545 :                 ExecASUpdateTriggers(node->ps.state,
    4511                 :             :                                      resultRelInfo,
    4512                 :         545 :                                      node->mt_oc_transition_capture);
    4513                 :       57373 :             ExecASInsertTriggers(node->ps.state, resultRelInfo,
    4514                 :       57373 :                                  node->mt_transition_capture);
    4515                 :       57373 :             break;
    4516                 :        8540 :         case CMD_UPDATE:
    4517                 :        8540 :             ExecASUpdateTriggers(node->ps.state, resultRelInfo,
    4518                 :        8540 :                                  node->mt_transition_capture);
    4519                 :        8540 :             break;
    4520                 :        8276 :         case CMD_DELETE:
    4521                 :        8276 :             ExecASDeleteTriggers(node->ps.state, resultRelInfo,
    4522                 :        8276 :                                  node->mt_transition_capture);
    4523                 :        8276 :             break;
    4524                 :         858 :         case CMD_MERGE:
    4525         [ +  + ]:         858 :             if (node->mt_merge_subcommands & MERGE_DELETE)
    4526                 :         244 :                 ExecASDeleteTriggers(node->ps.state, resultRelInfo,
    4527                 :         244 :                                      node->mt_transition_capture);
    4528         [ +  + ]:         858 :             if (node->mt_merge_subcommands & MERGE_UPDATE)
    4529                 :         567 :                 ExecASUpdateTriggers(node->ps.state, resultRelInfo,
    4530                 :         567 :                                      node->mt_transition_capture);
    4531         [ +  + ]:         858 :             if (node->mt_merge_subcommands & MERGE_INSERT)
    4532                 :         478 :                 ExecASInsertTriggers(node->ps.state, resultRelInfo,
    4533                 :         478 :                                      node->mt_transition_capture);
    4534                 :         858 :             break;
    4535                 :           0 :         default:
    4536         [ #  # ]:           0 :             elog(ERROR, "unknown operation");
    4537                 :             :             break;
    4538                 :             :     }
    4539                 :       75047 : }
    4540                 :             : 
    4541                 :             : /*
    4542                 :             :  * Set up the state needed for collecting transition tuples for AFTER
    4543                 :             :  * triggers.
    4544                 :             :  */
    4545                 :             : static void
    4546                 :       77661 : ExecSetupTransitionCaptureState(ModifyTableState *mtstate, EState *estate)
    4547                 :             : {
    4548                 :       77661 :     ModifyTable *plan = (ModifyTable *) mtstate->ps.plan;
    4549                 :       77661 :     ResultRelInfo *targetRelInfo = mtstate->rootResultRelInfo;
    4550                 :             : 
    4551                 :             :     /* Check for transition tables on the directly targeted relation. */
    4552                 :       77661 :     mtstate->mt_transition_capture =
    4553                 :       77661 :         MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
    4554                 :       77661 :                                    RelationGetRelid(targetRelInfo->ri_RelationDesc),
    4555                 :             :                                    mtstate->operation);
    4556         [ +  + ]:       77661 :     if (plan->operation == CMD_INSERT &&
    4557         [ +  + ]:       57779 :         plan->onConflictAction == ONCONFLICT_UPDATE)
    4558                 :         621 :         mtstate->mt_oc_transition_capture =
    4559                 :         621 :             MakeTransitionCaptureState(targetRelInfo->ri_TrigDesc,
    4560                 :         621 :                                        RelationGetRelid(targetRelInfo->ri_RelationDesc),
    4561                 :             :                                        CMD_UPDATE);
    4562                 :       77661 : }
    4563                 :             : 
    4564                 :             : /*
    4565                 :             :  * ExecPrepareTupleRouting --- prepare for routing one tuple
    4566                 :             :  *
    4567                 :             :  * Determine the partition in which the tuple in slot is to be inserted,
    4568                 :             :  * and return its ResultRelInfo in *partRelInfo.  The return value is
    4569                 :             :  * a slot holding the tuple of the partition rowtype.
    4570                 :             :  *
    4571                 :             :  * This also sets the transition table information in mtstate based on the
    4572                 :             :  * selected partition.
    4573                 :             :  */
    4574                 :             : static TupleTableSlot *
    4575                 :      481064 : ExecPrepareTupleRouting(ModifyTableState *mtstate,
    4576                 :             :                         EState *estate,
    4577                 :             :                         PartitionTupleRouting *proute,
    4578                 :             :                         ResultRelInfo *targetRelInfo,
    4579                 :             :                         TupleTableSlot *slot,
    4580                 :             :                         ResultRelInfo **partRelInfo)
    4581                 :             : {
    4582                 :             :     ResultRelInfo *partrel;
    4583                 :             :     TupleConversionMap *map;
    4584                 :             : 
    4585                 :             :     /*
    4586                 :             :      * Lookup the target partition's ResultRelInfo.  If ExecFindPartition does
    4587                 :             :      * not find a valid partition for the tuple in 'slot' then an error is
    4588                 :             :      * raised.  An error may also be raised if the found partition is not a
    4589                 :             :      * valid target for INSERTs.  This is required since a partitioned table
    4590                 :             :      * UPDATE to another partition becomes a DELETE+INSERT.
    4591                 :             :      */
    4592                 :      481064 :     partrel = ExecFindPartition(mtstate, targetRelInfo, proute, slot, estate);
    4593                 :             : 
    4594                 :             :     /*
    4595                 :             :      * If we're capturing transition tuples, we might need to convert from the
    4596                 :             :      * partition rowtype to root partitioned table's rowtype.  But if there
    4597                 :             :      * are no BEFORE triggers on the partition that could change the tuple, we
    4598                 :             :      * can just remember the original unconverted tuple to avoid a needless
    4599                 :             :      * round trip conversion.
    4600                 :             :      */
    4601         [ +  + ]:      480920 :     if (mtstate->mt_transition_capture != NULL)
    4602                 :             :     {
    4603                 :             :         bool        has_before_insert_row_trig;
    4604                 :             : 
    4605         [ +  + ]:         130 :         has_before_insert_row_trig = (partrel->ri_TrigDesc &&
    4606         [ +  + ]:          28 :                                       partrel->ri_TrigDesc->trig_insert_before_row);
    4607                 :             : 
    4608                 :         102 :         mtstate->mt_transition_capture->tcs_original_insert_tuple =
    4609         [ +  + ]:         102 :             !has_before_insert_row_trig ? slot : NULL;
    4610                 :             :     }
    4611                 :             : 
    4612                 :             :     /*
    4613                 :             :      * Convert the tuple, if necessary.
    4614                 :             :      */
    4615                 :      480920 :     map = ExecGetRootToChildMap(partrel, estate);
    4616         [ +  + ]:      480920 :     if (map != NULL)
    4617                 :             :     {
    4618                 :       45768 :         TupleTableSlot *new_slot = partrel->ri_PartitionTupleSlot;
    4619                 :             : 
    4620                 :       45768 :         slot = execute_attr_map_slot(map->attrMap, slot, new_slot);
    4621                 :             :     }
    4622                 :             : 
    4623                 :      480920 :     *partRelInfo = partrel;
    4624                 :      480920 :     return slot;
    4625                 :             : }
    4626                 :             : 
    4627                 :             : /* ----------------------------------------------------------------
    4628                 :             :  *     ExecModifyTable
    4629                 :             :  *
    4630                 :             :  *      Perform table modifications as required, and return RETURNING results
    4631                 :             :  *      if needed.
    4632                 :             :  * ----------------------------------------------------------------
    4633                 :             :  */
    4634                 :             : static TupleTableSlot *
    4635                 :       82486 : ExecModifyTable(PlanState *pstate)
    4636                 :             : {
    4637                 :       82486 :     ModifyTableState *node = castNode(ModifyTableState, pstate);
    4638                 :             :     ModifyTableContext context;
    4639                 :       82486 :     EState     *estate = node->ps.state;
    4640                 :       82486 :     CmdType     operation = node->operation;
    4641                 :             :     ResultRelInfo *resultRelInfo;
    4642                 :             :     PlanState  *subplanstate;
    4643                 :             :     TupleTableSlot *slot;
    4644                 :             :     TupleTableSlot *oldSlot;
    4645                 :             :     ItemPointerData tuple_ctid;
    4646                 :             :     HeapTupleData oldtupdata;
    4647                 :             :     HeapTuple   oldtuple;
    4648                 :             :     ItemPointer tupleid;
    4649                 :             :     bool        tuplock;
    4650                 :             : 
    4651         [ -  + ]:       82486 :     CHECK_FOR_INTERRUPTS();
    4652                 :             : 
    4653                 :             :     /*
    4654                 :             :      * This should NOT get called during EvalPlanQual; we should have passed a
    4655                 :             :      * subplan tree to EvalPlanQual, instead.  Use a runtime test not just
    4656                 :             :      * Assert because this condition is easy to miss in testing.  (Note:
    4657                 :             :      * although ModifyTable should not get executed within an EvalPlanQual
    4658                 :             :      * operation, we do have to allow it to be initialized and shut down in
    4659                 :             :      * case it is within a CTE subplan.  Hence this test must be here, not in
    4660                 :             :      * ExecInitModifyTable.)
    4661                 :             :      */
    4662         [ -  + ]:       82486 :     if (estate->es_epq_active != NULL)
    4663         [ #  # ]:           0 :         elog(ERROR, "ModifyTable should not be called during EvalPlanQual");
    4664                 :             : 
    4665                 :             :     /*
    4666                 :             :      * If we've already completed processing, don't try to do more.  We need
    4667                 :             :      * this test because ExecPostprocessPlan might call us an extra time, and
    4668                 :             :      * our subplan's nodes aren't necessarily robust against being called
    4669                 :             :      * extra times.
    4670                 :             :      */
    4671         [ +  + ]:       82486 :     if (node->mt_done)
    4672                 :         585 :         return NULL;
    4673                 :             : 
    4674                 :             :     /*
    4675                 :             :      * On first call, fire BEFORE STATEMENT triggers before proceeding.
    4676                 :             :      */
    4677         [ +  + ]:       81901 :     if (node->fireBSTriggers)
    4678                 :             :     {
    4679                 :       76171 :         fireBSTriggers(node);
    4680                 :       76163 :         node->fireBSTriggers = false;
    4681                 :             :     }
    4682                 :             : 
    4683                 :             :     /* Preload local variables */
    4684                 :       81893 :     resultRelInfo = node->resultRelInfo + node->mt_lastResultIndex;
    4685                 :       81893 :     subplanstate = outerPlanState(node);
    4686                 :             : 
    4687                 :             :     /* Set global context */
    4688                 :       81893 :     context.mtstate = node;
    4689                 :       81893 :     context.epqstate = &node->mt_epqstate;
    4690                 :       81893 :     context.estate = estate;
    4691                 :             : 
    4692                 :             :     /*
    4693                 :             :      * Fetch rows from subplan, and execute the required table modification
    4694                 :             :      * for each row.
    4695                 :             :      */
    4696                 :             :     for (;;)
    4697                 :             :     {
    4698                 :             :         /*
    4699                 :             :          * Reset the per-output-tuple exprcontext.  This is needed because
    4700                 :             :          * triggers expect to use that context as workspace.  It's a bit ugly
    4701                 :             :          * to do this below the top level of the plan, however.  We might need
    4702                 :             :          * to rethink this later.
    4703                 :             :          */
    4704         [ +  + ]:    11414950 :         ResetPerTupleExprContext(estate);
    4705                 :             : 
    4706                 :             :         /*
    4707                 :             :          * Reset per-tuple memory context used for processing on conflict and
    4708                 :             :          * returning clauses, to free any expression evaluation storage
    4709                 :             :          * allocated in the previous cycle.
    4710                 :             :          */
    4711         [ +  + ]:    11414950 :         if (pstate->ps_ExprContext)
    4712                 :     2233822 :             ResetExprContext(pstate->ps_ExprContext);
    4713                 :             : 
    4714                 :             :         /*
    4715                 :             :          * If there is a pending MERGE ... WHEN NOT MATCHED [BY TARGET] action
    4716                 :             :          * to execute, do so now --- see the comments in ExecMerge().
    4717                 :             :          */
    4718         [ +  + ]:    11414950 :         if (node->mt_merge_pending_not_matched != NULL)
    4719                 :             :         {
    4720                 :           2 :             context.planSlot = node->mt_merge_pending_not_matched;
    4721                 :           2 :             context.cpDeletedSlot = NULL;
    4722                 :             : 
    4723                 :           2 :             slot = ExecMergeNotMatched(&context, node->resultRelInfo,
    4724                 :           2 :                                        node->canSetTag);
    4725                 :             : 
    4726                 :             :             /* Clear the pending action */
    4727                 :           2 :             node->mt_merge_pending_not_matched = NULL;
    4728                 :             : 
    4729                 :             :             /*
    4730                 :             :              * If we got a RETURNING result, return it to the caller.  We'll
    4731                 :             :              * continue the work on next call.
    4732                 :             :              */
    4733         [ +  - ]:           2 :             if (slot)
    4734                 :           2 :                 return slot;
    4735                 :             : 
    4736                 :           0 :             continue;           /* continue with the next tuple */
    4737                 :             :         }
    4738                 :             : 
    4739                 :             :         /* Fetch the next row from subplan */
    4740                 :    11414948 :         context.planSlot = ExecProcNode(subplanstate);
    4741                 :    11414650 :         context.cpDeletedSlot = NULL;
    4742                 :             : 
    4743                 :             :         /* No more tuples to process? */
    4744   [ +  +  +  + ]:    11414650 :         if (TupIsNull(context.planSlot))
    4745                 :             :             break;
    4746                 :             : 
    4747                 :             :         /*
    4748                 :             :          * When there are multiple result relations, each tuple contains a
    4749                 :             :          * junk column that gives the OID of the rel from which it came.
    4750                 :             :          * Extract it and select the correct result relation.
    4751                 :             :          */
    4752         [ +  + ]:    11340789 :         if (AttributeNumberIsValid(node->mt_resultOidAttno))
    4753                 :             :         {
    4754                 :             :             Datum       datum;
    4755                 :             :             bool        isNull;
    4756                 :             :             Oid         resultoid;
    4757                 :             : 
    4758                 :        3448 :             datum = ExecGetJunkAttribute(context.planSlot, node->mt_resultOidAttno,
    4759                 :             :                                          &isNull);
    4760         [ +  + ]:        3448 :             if (isNull)
    4761                 :             :             {
    4762                 :             :                 /*
    4763                 :             :                  * For commands other than MERGE, any tuples having InvalidOid
    4764                 :             :                  * for tableoid are errors.  For MERGE, we may need to handle
    4765                 :             :                  * them as WHEN NOT MATCHED clauses if any, so do that.
    4766                 :             :                  *
    4767                 :             :                  * Note that we use the node's toplevel resultRelInfo, not any
    4768                 :             :                  * specific partition's.
    4769                 :             :                  */
    4770         [ +  - ]:         338 :                 if (operation == CMD_MERGE)
    4771                 :             :                 {
    4772                 :         338 :                     EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
    4773                 :             : 
    4774                 :         338 :                     slot = ExecMerge(&context, node->resultRelInfo,
    4775                 :         338 :                                      NULL, NULL, node->canSetTag);
    4776                 :             : 
    4777                 :             :                     /*
    4778                 :             :                      * If we got a RETURNING result, return it to the caller.
    4779                 :             :                      * We'll continue the work on next call.
    4780                 :             :                      */
    4781         [ +  + ]:         330 :                     if (slot)
    4782                 :          25 :                         return slot;
    4783                 :             : 
    4784                 :         305 :                     continue;   /* continue with the next tuple */
    4785                 :             :                 }
    4786                 :             : 
    4787         [ #  # ]:           0 :                 elog(ERROR, "tableoid is NULL");
    4788                 :             :             }
    4789                 :        3110 :             resultoid = DatumGetObjectId(datum);
    4790                 :             : 
    4791                 :             :             /* If it's not the same as last time, we need to locate the rel */
    4792         [ +  + ]:        3110 :             if (resultoid != node->mt_lastResultOid)
    4793                 :        2158 :                 resultRelInfo = ExecLookupResultRelByOid(node, resultoid,
    4794                 :             :                                                          false, true);
    4795                 :             :         }
    4796                 :             : 
    4797                 :             :         /*
    4798                 :             :          * If we don't have a ForPortionOfState yet, we must be a partition or
    4799                 :             :          * inheritance child being hit for the first time. Make a copy from
    4800                 :             :          * the root, with our own TupleTableSlot. We do this lazily so that we
    4801                 :             :          * don't pay the price of unused partitions.
    4802                 :             :          */
    4803         [ +  + ]:    11340451 :         if (((ModifyTable *) context.mtstate->ps.plan)->forPortionOf &&
    4804         [ +  + ]:         973 :             !resultRelInfo->ri_forPortionOf)
    4805                 :          74 :             ExecInitForPortionOf(context.mtstate, estate, resultRelInfo);
    4806                 :             : 
    4807                 :             :         /*
    4808                 :             :          * If resultRelInfo->ri_usesFdwDirectModify is true, all we need to do
    4809                 :             :          * here is compute the RETURNING expressions.
    4810                 :             :          */
    4811         [ +  + ]:    11340451 :         if (resultRelInfo->ri_usesFdwDirectModify)
    4812                 :             :         {
    4813                 :             :             Assert(resultRelInfo->ri_projectReturning);
    4814                 :             : 
    4815                 :             :             /*
    4816                 :             :              * A scan slot containing the data that was actually inserted,
    4817                 :             :              * updated or deleted has already been made available to
    4818                 :             :              * ExecProcessReturning by IterateDirectModify, so no need to
    4819                 :             :              * provide it here.  The individual old and new slots are not
    4820                 :             :              * needed, since direct-modify is disabled if the RETURNING list
    4821                 :             :              * refers to OLD/NEW values.
    4822                 :             :              */
    4823                 :             :             Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 &&
    4824                 :             :                    (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0);
    4825                 :             : 
    4826                 :         349 :             slot = ExecProcessReturning(&context, resultRelInfo,
    4827                 :             :                                         operation == CMD_DELETE,
    4828                 :             :                                         NULL, NULL, context.planSlot);
    4829                 :             : 
    4830                 :         349 :             return slot;
    4831                 :             :         }
    4832                 :             : 
    4833                 :    11340102 :         EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
    4834                 :    11340102 :         slot = context.planSlot;
    4835                 :             : 
    4836                 :    11340102 :         tupleid = NULL;
    4837                 :    11340102 :         oldtuple = NULL;
    4838                 :             : 
    4839                 :             :         /*
    4840                 :             :          * For UPDATE/DELETE/MERGE, fetch the row identity info for the tuple
    4841                 :             :          * to be updated/deleted/merged.  For a heap relation, that's a TID;
    4842                 :             :          * otherwise we may have a wholerow junk attr that carries the old
    4843                 :             :          * tuple in toto.  Keep this in step with the part of
    4844                 :             :          * ExecInitModifyTable that sets up ri_RowIdAttNo.
    4845                 :             :          */
    4846   [ +  +  +  +  :    11340102 :         if (operation == CMD_UPDATE || operation == CMD_DELETE ||
                   +  + ]
    4847                 :             :             operation == CMD_MERGE)
    4848                 :             :         {
    4849                 :             :             char        relkind;
    4850                 :             :             Datum       datum;
    4851                 :             :             bool        isNull;
    4852                 :             : 
    4853                 :     3262517 :             relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
    4854   [ +  +  +  + ]:     3262517 :             if (relkind == RELKIND_RELATION ||
    4855         [ +  + ]:         340 :                 relkind == RELKIND_MATVIEW ||
    4856                 :             :                 relkind == RELKIND_PARTITIONED_TABLE)
    4857                 :             :             {
    4858                 :             :                 /*
    4859                 :             :                  * ri_RowIdAttNo refers to a ctid attribute.  See the comment
    4860                 :             :                  * in ExecInitModifyTable().
    4861                 :             :                  */
    4862                 :             :                 Assert(AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo) ||
    4863                 :             :                        relkind == RELKIND_PARTITIONED_TABLE);
    4864                 :     3262181 :                 datum = ExecGetJunkAttribute(slot,
    4865                 :     3262181 :                                              resultRelInfo->ri_RowIdAttNo,
    4866                 :             :                                              &isNull);
    4867                 :             : 
    4868                 :             :                 /*
    4869                 :             :                  * For commands other than MERGE, any tuples having a null row
    4870                 :             :                  * identifier are errors.  For MERGE, we may need to handle
    4871                 :             :                  * them as WHEN NOT MATCHED clauses if any, so do that.
    4872                 :             :                  *
    4873                 :             :                  * Note that we use the node's toplevel resultRelInfo, not any
    4874                 :             :                  * specific partition's.
    4875                 :             :                  */
    4876         [ +  + ]:     3262181 :                 if (isNull)
    4877                 :             :                 {
    4878         [ +  - ]:        1421 :                     if (operation == CMD_MERGE)
    4879                 :             :                     {
    4880                 :        1421 :                         EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
    4881                 :             : 
    4882                 :        1421 :                         slot = ExecMerge(&context, node->resultRelInfo,
    4883                 :        1421 :                                          NULL, NULL, node->canSetTag);
    4884                 :             : 
    4885                 :             :                         /*
    4886                 :             :                          * If we got a RETURNING result, return it to the
    4887                 :             :                          * caller.  We'll continue the work on next call.
    4888                 :             :                          */
    4889         [ +  + ]:        1394 :                         if (slot)
    4890                 :          88 :                             return slot;
    4891                 :             : 
    4892                 :        1334 :                         continue;   /* continue with the next tuple */
    4893                 :             :                     }
    4894                 :             : 
    4895         [ #  # ]:           0 :                     elog(ERROR, "ctid is NULL");
    4896                 :             :                 }
    4897                 :             : 
    4898                 :     3260760 :                 tupleid = (ItemPointer) DatumGetPointer(datum);
    4899                 :     3260760 :                 tuple_ctid = *tupleid;  /* be sure we don't free ctid!! */
    4900                 :     3260760 :                 tupleid = &tuple_ctid;
    4901                 :             :             }
    4902                 :             : 
    4903                 :             :             /*
    4904                 :             :              * Use the wholerow attribute, when available, to reconstruct the
    4905                 :             :              * old relation tuple.  The old tuple serves one or both of two
    4906                 :             :              * purposes: 1) it serves as the OLD tuple for row triggers, 2) it
    4907                 :             :              * provides values for any unchanged columns for the NEW tuple of
    4908                 :             :              * an UPDATE, because the subplan does not produce all the columns
    4909                 :             :              * of the target table.
    4910                 :             :              *
    4911                 :             :              * Note that the wholerow attribute does not carry system columns,
    4912                 :             :              * so foreign table triggers miss seeing those, except that we
    4913                 :             :              * know enough here to set t_tableOid.  Quite separately from
    4914                 :             :              * this, the FDW may fetch its own junk attrs to identify the row.
    4915                 :             :              *
    4916                 :             :              * Other relevant relkinds, currently limited to views, always
    4917                 :             :              * have a wholerow attribute.
    4918                 :             :              */
    4919         [ +  + ]:         336 :             else if (AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
    4920                 :             :             {
    4921                 :         321 :                 datum = ExecGetJunkAttribute(slot,
    4922                 :         321 :                                              resultRelInfo->ri_RowIdAttNo,
    4923                 :             :                                              &isNull);
    4924                 :             : 
    4925                 :             :                 /*
    4926                 :             :                  * For commands other than MERGE, any tuples having a null row
    4927                 :             :                  * identifier are errors.  For MERGE, we may need to handle
    4928                 :             :                  * them as WHEN NOT MATCHED clauses if any, so do that.
    4929                 :             :                  *
    4930                 :             :                  * Note that we use the node's toplevel resultRelInfo, not any
    4931                 :             :                  * specific partition's.
    4932                 :             :                  */
    4933         [ +  + ]:         321 :                 if (isNull)
    4934                 :             :                 {
    4935         [ +  - ]:          32 :                     if (operation == CMD_MERGE)
    4936                 :             :                     {
    4937                 :          32 :                         EvalPlanQualSetSlot(&node->mt_epqstate, context.planSlot);
    4938                 :             : 
    4939                 :          32 :                         slot = ExecMerge(&context, node->resultRelInfo,
    4940                 :          32 :                                          NULL, NULL, node->canSetTag);
    4941                 :             : 
    4942                 :             :                         /*
    4943                 :             :                          * If we got a RETURNING result, return it to the
    4944                 :             :                          * caller.  We'll continue the work on next call.
    4945                 :             :                          */
    4946         [ +  + ]:          28 :                         if (slot)
    4947                 :           8 :                             return slot;
    4948                 :             : 
    4949                 :          20 :                         continue;   /* continue with the next tuple */
    4950                 :             :                     }
    4951                 :             : 
    4952         [ #  # ]:           0 :                     elog(ERROR, "wholerow is NULL");
    4953                 :             :                 }
    4954                 :             : 
    4955                 :         289 :                 oldtupdata.t_data = DatumGetHeapTupleHeader(datum);
    4956                 :         289 :                 oldtupdata.t_len =
    4957                 :         289 :                     HeapTupleHeaderGetDatumLength(oldtupdata.t_data);
    4958                 :         289 :                 ItemPointerSetInvalid(&(oldtupdata.t_self));
    4959                 :             :                 /* Historically, view triggers see invalid t_tableOid. */
    4960                 :         289 :                 oldtupdata.t_tableOid =
    4961         [ +  + ]:         289 :                     (relkind == RELKIND_VIEW) ? InvalidOid :
    4962                 :         107 :                     RelationGetRelid(resultRelInfo->ri_RelationDesc);
    4963                 :             : 
    4964                 :         289 :                 oldtuple = &oldtupdata;
    4965                 :             :             }
    4966                 :             :             else
    4967                 :             :             {
    4968                 :             :                 /* Only foreign tables are allowed to omit a row-ID attr */
    4969                 :             :                 Assert(relkind == RELKIND_FOREIGN_TABLE);
    4970                 :             :             }
    4971                 :             :         }
    4972                 :             : 
    4973   [ +  +  +  +  :    11338649 :         switch (operation)
                      - ]
    4974                 :             :         {
    4975                 :     8077585 :             case CMD_INSERT:
    4976                 :             :                 /* Initialize projection info if first time for this table */
    4977         [ +  + ]:     8077585 :                 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
    4978                 :       57020 :                     ExecInitInsertProjection(node, resultRelInfo);
    4979                 :     8077585 :                 slot = ExecGetInsertNewTuple(resultRelInfo, context.planSlot);
    4980                 :     8077585 :                 slot = ExecInsert(&context, resultRelInfo, slot,
    4981                 :     8077585 :                                   node->canSetTag, NULL, NULL);
    4982                 :     8076142 :                 break;
    4983                 :             : 
    4984                 :     2209449 :             case CMD_UPDATE:
    4985                 :     2209449 :                 tuplock = false;
    4986                 :             : 
    4987                 :             :                 /* Initialize projection info if first time for this table */
    4988         [ +  + ]:     2209449 :                 if (unlikely(!resultRelInfo->ri_projectNewInfoValid))
    4989                 :        8794 :                     ExecInitUpdateProjection(node, resultRelInfo);
    4990                 :             : 
    4991                 :             :                 /*
    4992                 :             :                  * Make the new tuple by combining plan's output tuple with
    4993                 :             :                  * the old tuple being updated.
    4994                 :             :                  */
    4995                 :     2209449 :                 oldSlot = resultRelInfo->ri_oldTupleSlot;
    4996         [ +  + ]:     2209449 :                 if (oldtuple != NULL)
    4997                 :             :                 {
    4998                 :             :                     Assert(!resultRelInfo->ri_needLockTagTuple);
    4999                 :             :                     /* Use the wholerow junk attr as the old tuple. */
    5000                 :         181 :                     ExecForceStoreHeapTuple(oldtuple, oldSlot, false);
    5001                 :             :                 }
    5002                 :             :                 else
    5003                 :             :                 {
    5004                 :             :                     /* Fetch the most recent version of old tuple. */
    5005                 :     2209268 :                     Relation    relation = resultRelInfo->ri_RelationDesc;
    5006                 :             : 
    5007         [ +  + ]:     2209268 :                     if (resultRelInfo->ri_needLockTagTuple)
    5008                 :             :                     {
    5009                 :       15809 :                         LockTuple(relation, tupleid, InplaceUpdateTupleLock);
    5010                 :       15809 :                         tuplock = true;
    5011                 :             :                     }
    5012         [ -  + ]:     2209268 :                     if (!table_tuple_fetch_row_version(relation, tupleid,
    5013                 :             :                                                        SnapshotAny,
    5014                 :             :                                                        oldSlot))
    5015         [ #  # ]:           0 :                         elog(ERROR, "failed to fetch tuple being updated");
    5016                 :             :                 }
    5017                 :     2209449 :                 slot = ExecGetUpdateNewTuple(resultRelInfo, context.planSlot,
    5018                 :             :                                              oldSlot);
    5019                 :             : 
    5020                 :             :                 /* Now apply the update. */
    5021                 :     2209449 :                 slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple,
    5022                 :     2209449 :                                   oldSlot, slot, node->canSetTag);
    5023         [ +  + ]:     2209075 :                 if (tuplock)
    5024                 :       15809 :                     UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid,
    5025                 :             :                                 InplaceUpdateTupleLock);
    5026                 :     2209075 :                 break;
    5027                 :             : 
    5028                 :     1042965 :             case CMD_DELETE:
    5029                 :     1042965 :                 slot = ExecDelete(&context, resultRelInfo, tupleid, oldtuple,
    5030                 :     1042965 :                                   true, false, node->canSetTag, NULL, NULL, NULL);
    5031                 :     1042886 :                 break;
    5032                 :             : 
    5033                 :        8650 :             case CMD_MERGE:
    5034                 :        8650 :                 slot = ExecMerge(&context, resultRelInfo, tupleid, oldtuple,
    5035                 :        8650 :                                  node->canSetTag);
    5036                 :        8588 :                 break;
    5037                 :             : 
    5038                 :           0 :             default:
    5039         [ #  # ]:           0 :                 elog(ERROR, "unknown operation");
    5040                 :             :                 break;
    5041                 :             :         }
    5042                 :             : 
    5043                 :             :         /*
    5044                 :             :          * If we got a RETURNING result, return it to caller.  We'll continue
    5045                 :             :          * the work on next call.
    5046                 :             :          */
    5047         [ +  + ]:    11336691 :         if (slot)
    5048                 :        5273 :             return slot;
    5049                 :             :     }
    5050                 :             : 
    5051                 :             :     /*
    5052                 :             :      * Insert remaining tuples for batch insert.
    5053                 :             :      */
    5054         [ +  + ]:       73861 :     if (estate->es_insert_pending_result_relations != NIL)
    5055                 :          13 :         ExecPendingInserts(estate);
    5056                 :             : 
    5057                 :             :     /*
    5058                 :             :      * We're done, but fire AFTER STATEMENT triggers before exiting.
    5059                 :             :      */
    5060                 :       73860 :     fireASTriggers(node);
    5061                 :             : 
    5062                 :       73860 :     node->mt_done = true;
    5063                 :             : 
    5064                 :       73860 :     return NULL;
    5065                 :             : }
    5066                 :             : 
    5067                 :             : /*
    5068                 :             :  * ExecLookupResultRelByOid
    5069                 :             :  *      If the table with given OID is among the result relations to be
    5070                 :             :  *      updated by the given ModifyTable node, return its ResultRelInfo.
    5071                 :             :  *
    5072                 :             :  * If not found, return NULL if missing_ok, else raise error.
    5073                 :             :  *
    5074                 :             :  * If update_cache is true, then upon successful lookup, update the node's
    5075                 :             :  * one-element cache.  ONLY ExecModifyTable may pass true for this.
    5076                 :             :  */
    5077                 :             : ResultRelInfo *
    5078                 :        8190 : ExecLookupResultRelByOid(ModifyTableState *node, Oid resultoid,
    5079                 :             :                          bool missing_ok, bool update_cache)
    5080                 :             : {
    5081         [ -  + ]:        8190 :     if (node->mt_resultOidHash)
    5082                 :             :     {
    5083                 :             :         /* Use the pre-built hash table to locate the rel */
    5084                 :             :         MTTargetRelLookup *mtlookup;
    5085                 :             : 
    5086                 :             :         mtlookup = (MTTargetRelLookup *)
    5087                 :           0 :             hash_search(node->mt_resultOidHash, &resultoid, HASH_FIND, NULL);
    5088         [ #  # ]:           0 :         if (mtlookup)
    5089                 :             :         {
    5090         [ #  # ]:           0 :             if (update_cache)
    5091                 :             :             {
    5092                 :           0 :                 node->mt_lastResultOid = resultoid;
    5093                 :           0 :                 node->mt_lastResultIndex = mtlookup->relationIndex;
    5094                 :             :             }
    5095                 :           0 :             return node->resultRelInfo + mtlookup->relationIndex;
    5096                 :             :         }
    5097                 :             :     }
    5098                 :             :     else
    5099                 :             :     {
    5100                 :             :         /* With few target rels, just search the ResultRelInfo array */
    5101         [ +  + ]:       15523 :         for (int ndx = 0; ndx < node->mt_nrels; ndx++)
    5102                 :             :         {
    5103                 :        9897 :             ResultRelInfo *rInfo = node->resultRelInfo + ndx;
    5104                 :             : 
    5105         [ +  + ]:        9897 :             if (RelationGetRelid(rInfo->ri_RelationDesc) == resultoid)
    5106                 :             :             {
    5107         [ +  + ]:        2564 :                 if (update_cache)
    5108                 :             :                 {
    5109                 :        2158 :                     node->mt_lastResultOid = resultoid;
    5110                 :        2158 :                     node->mt_lastResultIndex = ndx;
    5111                 :             :                 }
    5112                 :        2564 :                 return rInfo;
    5113                 :             :             }
    5114                 :             :         }
    5115                 :             :     }
    5116                 :             : 
    5117         [ -  + ]:        5626 :     if (!missing_ok)
    5118         [ #  # ]:           0 :         elog(ERROR, "incorrect result relation OID %u", resultoid);
    5119                 :        5626 :     return NULL;
    5120                 :             : }
    5121                 :             : 
    5122                 :             : /* ----------------------------------------------------------------
    5123                 :             :  *      ExecInitModifyTable
    5124                 :             :  * ----------------------------------------------------------------
    5125                 :             :  */
    5126                 :             : ModifyTableState *
    5127                 :       77103 : ExecInitModifyTable(ModifyTable *node, EState *estate, int eflags)
    5128                 :             : {
    5129                 :             :     ModifyTableState *mtstate;
    5130                 :       77103 :     Plan       *subplan = outerPlan(node);
    5131                 :       77103 :     CmdType     operation = node->operation;
    5132                 :       77103 :     int         total_nrels = list_length(node->resultRelations);
    5133                 :             :     int         nrels;
    5134                 :       77103 :     List       *resultRelations = NIL;
    5135                 :       77103 :     List       *withCheckOptionLists = NIL;
    5136                 :       77103 :     List       *returningLists = NIL;
    5137                 :       77103 :     List       *updateColnosLists = NIL;
    5138                 :       77103 :     List       *mergeActionLists = NIL;
    5139                 :       77103 :     List       *mergeJoinConditions = NIL;
    5140                 :       77103 :     List       *fdwPrivLists = NIL;
    5141                 :       77103 :     Bitmapset  *fdwDirectModifyPlans = NULL;
    5142                 :             :     ResultRelInfo *resultRelInfo;
    5143                 :             :     List       *arowmarks;
    5144                 :             :     ListCell   *l;
    5145                 :             :     int         i;
    5146                 :             :     Relation    rel;
    5147                 :             : 
    5148                 :             :     /* check for unsupported flags */
    5149                 :             :     Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
    5150                 :             : 
    5151                 :             :     /*
    5152                 :             :      * Only consider unpruned relations for initializing their ResultRelInfo
    5153                 :             :      * struct and other fields such as withCheckOptions, etc.
    5154                 :             :      *
    5155                 :             :      * Note: We must avoid pruning every result relation.  This is important
    5156                 :             :      * for MERGE, since even if every result relation is pruned from the
    5157                 :             :      * subplan, there might still be NOT MATCHED rows, for which there may be
    5158                 :             :      * INSERT actions to perform.  To allow these actions to be found, at
    5159                 :             :      * least one result relation must be kept.  Also, when inserting into a
    5160                 :             :      * partitioned table, ExecInitPartitionInfo() needs a ResultRelInfo struct
    5161                 :             :      * as a reference for building the ResultRelInfo of the target partition.
    5162                 :             :      * In either case, it doesn't matter which result relation is kept, so we
    5163                 :             :      * just keep the first one, if all others have been pruned.  See also,
    5164                 :             :      * ExecDoInitialPruning(), which ensures that this first result relation
    5165                 :             :      * has been locked.
    5166                 :             :      */
    5167                 :       77103 :     i = 0;
    5168   [ +  -  +  +  :      155892 :     foreach(l, node->resultRelations)
                   +  + ]
    5169                 :             :     {
    5170                 :       78789 :         Index       rti = lfirst_int(l);
    5171                 :             :         bool        keep_rel;
    5172                 :             : 
    5173                 :       78789 :         keep_rel = bms_is_member(rti, estate->es_unpruned_relids);
    5174   [ +  +  +  +  :       78789 :         if (!keep_rel && i == total_nrels - 1 && resultRelations == NIL)
                   +  + ]
    5175                 :             :         {
    5176                 :             :             /* all result relations pruned; keep the first one */
    5177                 :          32 :             keep_rel = true;
    5178                 :          32 :             rti = linitial_int(node->resultRelations);
    5179                 :          32 :             i = 0;
    5180                 :             :         }
    5181                 :             : 
    5182         [ +  + ]:       78789 :         if (keep_rel)
    5183                 :             :         {
    5184                 :       78728 :             List       *fdwPrivList = (List *) list_nth(node->fdwPrivLists, i);
    5185                 :             : 
    5186                 :       78728 :             resultRelations = lappend_int(resultRelations, rti);
    5187         [ +  + ]:       78728 :             if (node->withCheckOptionLists)
    5188                 :             :             {
    5189                 :        1092 :                 List       *withCheckOptions = list_nth_node(List,
    5190                 :             :                                                              node->withCheckOptionLists,
    5191                 :             :                                                              i);
    5192                 :             : 
    5193                 :        1092 :                 withCheckOptionLists = lappend(withCheckOptionLists, withCheckOptions);
    5194                 :             :             }
    5195         [ +  + ]:       78728 :             if (node->returningLists)
    5196                 :             :             {
    5197                 :        3953 :                 List       *returningList = list_nth_node(List,
    5198                 :             :                                                           node->returningLists,
    5199                 :             :                                                           i);
    5200                 :             : 
    5201                 :        3953 :                 returningLists = lappend(returningLists, returningList);
    5202                 :             :             }
    5203         [ +  + ]:       78728 :             if (node->updateColnosLists)
    5204                 :             :             {
    5205                 :       10667 :                 List       *updateColnosList = list_nth(node->updateColnosLists, i);
    5206                 :             : 
    5207                 :       10667 :                 updateColnosLists = lappend(updateColnosLists, updateColnosList);
    5208                 :             :             }
    5209         [ +  + ]:       78728 :             if (node->mergeActionLists)
    5210                 :             :             {
    5211                 :        1225 :                 List       *mergeActionList = list_nth(node->mergeActionLists, i);
    5212                 :             : 
    5213                 :        1225 :                 mergeActionLists = lappend(mergeActionLists, mergeActionList);
    5214                 :             :             }
    5215         [ +  + ]:       78728 :             if (node->mergeJoinConditions)
    5216                 :             :             {
    5217                 :        1225 :                 List       *mergeJoinCondition = list_nth(node->mergeJoinConditions, i);
    5218                 :             : 
    5219                 :        1225 :                 mergeJoinConditions = lappend(mergeJoinConditions, mergeJoinCondition);
    5220                 :             :             }
    5221                 :             : 
    5222                 :             :             /*
    5223                 :             :              * fdwPrivLists/fdwDirectModifyPlans are re-indexed to match
    5224                 :             :              * resultRelations
    5225                 :             :              */
    5226                 :       78728 :             fdwPrivLists = lappend(fdwPrivLists, fdwPrivList);
    5227         [ +  + ]:       78728 :             if (bms_is_member(i, node->fdwDirectModifyPlans))
    5228                 :             :             {
    5229                 :         112 :                 int         new_index = list_length(resultRelations) - 1;
    5230                 :             : 
    5231                 :         112 :                 fdwDirectModifyPlans = bms_add_member(fdwDirectModifyPlans,
    5232                 :             :                                                       new_index);
    5233                 :             :             }
    5234                 :             :         }
    5235                 :       78789 :         i++;
    5236                 :             :     }
    5237                 :       77103 :     nrels = list_length(resultRelations);
    5238                 :             :     Assert(nrels > 0);
    5239                 :             : 
    5240                 :             :     /*
    5241                 :             :      * create state structure
    5242                 :             :      */
    5243                 :       77103 :     mtstate = makeNode(ModifyTableState);
    5244                 :       77103 :     mtstate->ps.plan = (Plan *) node;
    5245                 :       77103 :     mtstate->ps.state = estate;
    5246                 :       77103 :     mtstate->ps.ExecProcNode = ExecModifyTable;
    5247                 :             : 
    5248                 :       77103 :     mtstate->operation = operation;
    5249                 :       77103 :     mtstate->canSetTag = node->canSetTag;
    5250                 :       77103 :     mtstate->mt_done = false;
    5251                 :             : 
    5252                 :       77103 :     mtstate->mt_nrels = nrels;
    5253                 :       77103 :     mtstate->resultRelInfo = palloc_array(ResultRelInfo, nrels);
    5254                 :             : 
    5255                 :       77103 :     mtstate->mt_merge_pending_not_matched = NULL;
    5256                 :       77103 :     mtstate->mt_merge_inserted = 0;
    5257                 :       77103 :     mtstate->mt_merge_updated = 0;
    5258                 :       77103 :     mtstate->mt_merge_deleted = 0;
    5259                 :       77103 :     mtstate->mt_updateColnosLists = updateColnosLists;
    5260                 :       77103 :     mtstate->mt_mergeActionLists = mergeActionLists;
    5261                 :       77103 :     mtstate->mt_mergeJoinConditions = mergeJoinConditions;
    5262                 :       77103 :     mtstate->mt_fdwPrivLists = fdwPrivLists;
    5263                 :             : 
    5264                 :             :     /*----------
    5265                 :             :      * Resolve the target relation. This is the same as:
    5266                 :             :      *
    5267                 :             :      * - the relation for which we will fire FOR STATEMENT triggers,
    5268                 :             :      * - the relation into whose tuple format all captured transition tuples
    5269                 :             :      *   must be converted, and
    5270                 :             :      * - the root partitioned table used for tuple routing.
    5271                 :             :      *
    5272                 :             :      * If it's a partitioned or inherited table, the root partition or
    5273                 :             :      * appendrel RTE doesn't appear elsewhere in the plan and its RT index is
    5274                 :             :      * given explicitly in node->rootRelation.  Otherwise, the target relation
    5275                 :             :      * is the sole relation in the node->resultRelations list and, since it can
    5276                 :             :      * never be pruned, also in the resultRelations list constructed above.
    5277                 :             :      *----------
    5278                 :             :      */
    5279         [ +  + ]:       77103 :     if (node->rootRelation > 0)
    5280                 :             :     {
    5281                 :             :         Assert(bms_is_member(node->rootRelation, estate->es_unpruned_relids));
    5282                 :        1954 :         mtstate->rootResultRelInfo = makeNode(ResultRelInfo);
    5283                 :        1954 :         ExecInitResultRelation(estate, mtstate->rootResultRelInfo,
    5284                 :             :                                node->rootRelation);
    5285                 :             :     }
    5286                 :             :     else
    5287                 :             :     {
    5288                 :             :         Assert(list_length(node->resultRelations) == 1);
    5289                 :             :         Assert(list_length(resultRelations) == 1);
    5290                 :       75149 :         mtstate->rootResultRelInfo = mtstate->resultRelInfo;
    5291                 :       75149 :         ExecInitResultRelation(estate, mtstate->resultRelInfo,
    5292                 :       75149 :                                linitial_int(resultRelations));
    5293                 :             :     }
    5294                 :             : 
    5295                 :             :     /* set up epqstate with dummy subplan data for the moment */
    5296                 :       77103 :     EvalPlanQualInit(&mtstate->mt_epqstate, estate, NULL, NIL,
    5297                 :             :                      node->epqParam, resultRelations);
    5298                 :       77103 :     mtstate->fireBSTriggers = true;
    5299                 :             : 
    5300                 :             :     /*
    5301                 :             :      * Build state for collecting transition tuples.  This requires having a
    5302                 :             :      * valid trigger query context, so skip it in explain-only mode.
    5303                 :             :      */
    5304         [ +  + ]:       77103 :     if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
    5305                 :       76438 :         ExecSetupTransitionCaptureState(mtstate, estate);
    5306                 :             : 
    5307                 :             :     /*
    5308                 :             :      * Open all the result relations and initialize the ResultRelInfo structs.
    5309                 :             :      * (But root relation was initialized above, if it's part of the array.)
    5310                 :             :      * We must do this before initializing the subplan, because direct-modify
    5311                 :             :      * FDWs expect their ResultRelInfos to be available.
    5312                 :             :      */
    5313                 :       77103 :     resultRelInfo = mtstate->resultRelInfo;
    5314                 :       77103 :     i = 0;
    5315   [ +  -  +  +  :      155591 :     foreach(l, resultRelations)
                   +  + ]
    5316                 :             :     {
    5317                 :       78724 :         Index       resultRelation = lfirst_int(l);
    5318                 :       78724 :         List       *mergeActions = NIL;
    5319                 :             : 
    5320         [ +  + ]:       78724 :         if (mergeActionLists)
    5321                 :        1225 :             mergeActions = list_nth(mergeActionLists, i);
    5322                 :             : 
    5323         [ +  + ]:       78724 :         if (resultRelInfo != mtstate->rootResultRelInfo)
    5324                 :             :         {
    5325                 :        3575 :             ExecInitResultRelation(estate, resultRelInfo, resultRelation);
    5326                 :             : 
    5327                 :             :             /*
    5328                 :             :              * For child result relations, store the root result relation
    5329                 :             :              * pointer.  We do so for the convenience of places that want to
    5330                 :             :              * look at the query's original target relation but don't have the
    5331                 :             :              * mtstate handy.
    5332                 :             :              */
    5333                 :        3575 :             resultRelInfo->ri_RootResultRelInfo = mtstate->rootResultRelInfo;
    5334                 :             :         }
    5335                 :             : 
    5336                 :             :         /* Initialize the usesFdwDirectModify flag */
    5337                 :       78724 :         resultRelInfo->ri_usesFdwDirectModify =
    5338                 :       78724 :             bms_is_member(i, fdwDirectModifyPlans);
    5339                 :             : 
    5340                 :             :         /*
    5341                 :             :          * Verify result relation is a valid target for the current operation
    5342                 :             :          */
    5343                 :       78724 :         CheckValidResultRel(resultRelInfo, operation, node->onConflictAction,
    5344                 :             :                             mergeActions, node);
    5345                 :             : 
    5346                 :       78488 :         resultRelInfo++;
    5347                 :       78488 :         i++;
    5348                 :             :     }
    5349                 :             : 
    5350                 :             :     /*
    5351                 :             :      * Now we may initialize the subplan.
    5352                 :             :      */
    5353                 :       76867 :     outerPlanState(mtstate) = ExecInitNode(subplan, estate, eflags);
    5354                 :             : 
    5355                 :             :     /*
    5356                 :             :      * Do additional per-result-relation initialization.
    5357                 :             :      */
    5358         [ +  + ]:      155333 :     for (i = 0; i < nrels; i++)
    5359                 :             :     {
    5360                 :       78466 :         resultRelInfo = &mtstate->resultRelInfo[i];
    5361                 :             : 
    5362                 :             :         /* Let FDWs init themselves for foreign-table result rels */
    5363         [ +  + ]:       78466 :         if (!resultRelInfo->ri_usesFdwDirectModify &&
    5364         [ +  + ]:       78358 :             resultRelInfo->ri_FdwRoutine != NULL &&
    5365         [ +  - ]:         173 :             resultRelInfo->ri_FdwRoutine->BeginForeignModify != NULL)
    5366                 :             :         {
    5367                 :         173 :             List       *fdw_private = (List *) list_nth(fdwPrivLists, i);
    5368                 :             : 
    5369                 :         173 :             resultRelInfo->ri_FdwRoutine->BeginForeignModify(mtstate,
    5370                 :             :                                                              resultRelInfo,
    5371                 :             :                                                              fdw_private,
    5372                 :             :                                                              i,
    5373                 :             :                                                              eflags);
    5374                 :             :         }
    5375                 :             : 
    5376                 :             :         /*
    5377                 :             :          * For UPDATE/DELETE/MERGE, find the appropriate junk attr now, either
    5378                 :             :          * a 'ctid' or 'wholerow' attribute depending on relkind.  For foreign
    5379                 :             :          * tables, the FDW might have created additional junk attr(s), but
    5380                 :             :          * those are no concern of ours.
    5381                 :             :          */
    5382   [ +  +  +  +  :       78466 :         if (operation == CMD_UPDATE || operation == CMD_DELETE ||
                   +  + ]
    5383                 :             :             operation == CMD_MERGE)
    5384                 :             :         {
    5385                 :             :             char        relkind;
    5386                 :             : 
    5387                 :       20510 :             relkind = resultRelInfo->ri_RelationDesc->rd_rel->relkind;
    5388   [ +  +  +  + ]:       20510 :             if (relkind == RELKIND_RELATION ||
    5389         [ +  + ]:         413 :                 relkind == RELKIND_MATVIEW ||
    5390                 :             :                 relkind == RELKIND_PARTITIONED_TABLE)
    5391                 :             :             {
    5392                 :       20127 :                 resultRelInfo->ri_RowIdAttNo =
    5393                 :       20127 :                     ExecFindJunkAttributeInTlist(subplan->targetlist, "ctid");
    5394                 :             : 
    5395                 :             :                 /*
    5396                 :             :                  * For heap relations, a ctid junk attribute must be present.
    5397                 :             :                  * Partitioned tables should only appear here when all leaf
    5398                 :             :                  * partitions were pruned, in which case no rows can be
    5399                 :             :                  * produced and ctid is not needed.
    5400                 :             :                  */
    5401         [ +  + ]:       20127 :                 if (relkind == RELKIND_PARTITIONED_TABLE)
    5402                 :             :                     Assert(nrels == 1);
    5403         [ -  + ]:       20097 :                 else if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
    5404         [ #  # ]:           0 :                     elog(ERROR, "could not find junk ctid column");
    5405                 :             :             }
    5406         [ +  + ]:         383 :             else if (relkind == RELKIND_FOREIGN_TABLE)
    5407                 :             :             {
    5408                 :             :                 /*
    5409                 :             :                  * We don't support MERGE with foreign tables for now.  (It's
    5410                 :             :                  * problematic because the implementation uses CTID.)
    5411                 :             :                  */
    5412                 :             :                 Assert(operation != CMD_MERGE);
    5413                 :             : 
    5414                 :             :                 /*
    5415                 :             :                  * When there is a row-level trigger, there should be a
    5416                 :             :                  * wholerow attribute.  We also require it to be present in
    5417                 :             :                  * UPDATE and MERGE, so we can get the values of unchanged
    5418                 :             :                  * columns.
    5419                 :             :                  */
    5420                 :         193 :                 resultRelInfo->ri_RowIdAttNo =
    5421                 :         193 :                     ExecFindJunkAttributeInTlist(subplan->targetlist,
    5422                 :             :                                                  "wholerow");
    5423   [ +  +  -  + ]:         193 :                 if ((mtstate->operation == CMD_UPDATE || mtstate->operation == CMD_MERGE) &&
    5424         [ -  + ]:         112 :                     !AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
    5425         [ #  # ]:           0 :                     elog(ERROR, "could not find junk wholerow column");
    5426                 :             :             }
    5427                 :             :             else
    5428                 :             :             {
    5429                 :             :                 /* Other valid target relkinds must provide wholerow */
    5430                 :         190 :                 resultRelInfo->ri_RowIdAttNo =
    5431                 :         190 :                     ExecFindJunkAttributeInTlist(subplan->targetlist,
    5432                 :             :                                                  "wholerow");
    5433         [ -  + ]:         190 :                 if (!AttributeNumberIsValid(resultRelInfo->ri_RowIdAttNo))
    5434         [ #  # ]:           0 :                     elog(ERROR, "could not find junk wholerow column");
    5435                 :             :             }
    5436                 :             :         }
    5437                 :             :     }
    5438                 :             : 
    5439                 :             :     /*
    5440                 :             :      * If this is an inherited update/delete/merge, there will be a junk
    5441                 :             :      * attribute named "tableoid" present in the subplan's targetlist.  It
    5442                 :             :      * will be used to identify the result relation for a given tuple to be
    5443                 :             :      * updated/deleted/merged.
    5444                 :             :      */
    5445                 :       76867 :     mtstate->mt_resultOidAttno =
    5446                 :       76867 :         ExecFindJunkAttributeInTlist(subplan->targetlist, "tableoid");
    5447                 :             :     Assert(AttributeNumberIsValid(mtstate->mt_resultOidAttno) || total_nrels == 1);
    5448                 :       76867 :     mtstate->mt_lastResultOid = InvalidOid; /* force lookup at first tuple */
    5449                 :       76867 :     mtstate->mt_lastResultIndex = 0; /* must be zero if no such attr */
    5450                 :             : 
    5451                 :             :     /* Get the root target relation */
    5452                 :       76867 :     rel = mtstate->rootResultRelInfo->ri_RelationDesc;
    5453                 :             : 
    5454                 :             :     /*
    5455                 :             :      * Build state for tuple routing if it's a partitioned INSERT.  An UPDATE
    5456                 :             :      * or MERGE might need this too, but only if it actually moves tuples
    5457                 :             :      * between partitions; in that case setup is done by
    5458                 :             :      * ExecCrossPartitionUpdate.
    5459                 :             :      */
    5460   [ +  +  +  + ]:       76867 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
    5461                 :             :         operation == CMD_INSERT)
    5462                 :        3769 :         mtstate->mt_partition_tuple_routing =
    5463                 :        3769 :             ExecSetupPartitionTupleRouting(estate, rel);
    5464                 :             : 
    5465                 :             :     /*
    5466                 :             :      * Initialize any WITH CHECK OPTION constraints if needed.
    5467                 :             :      */
    5468                 :       76867 :     resultRelInfo = mtstate->resultRelInfo;
    5469   [ +  +  +  +  :       77959 :     foreach(l, withCheckOptionLists)
                   +  + ]
    5470                 :             :     {
    5471                 :        1092 :         List       *wcoList = (List *) lfirst(l);
    5472                 :        1092 :         List       *wcoExprs = NIL;
    5473                 :             :         ListCell   *ll;
    5474                 :             : 
    5475   [ +  -  +  +  :        3211 :         foreach(ll, wcoList)
                   +  + ]
    5476                 :             :         {
    5477                 :        2119 :             WithCheckOption *wco = (WithCheckOption *) lfirst(ll);
    5478                 :        2119 :             ExprState  *wcoExpr = ExecInitQual((List *) wco->qual,
    5479                 :             :                                                &mtstate->ps);
    5480                 :             : 
    5481                 :        2119 :             wcoExprs = lappend(wcoExprs, wcoExpr);
    5482                 :             :         }
    5483                 :             : 
    5484                 :        1092 :         resultRelInfo->ri_WithCheckOptions = wcoList;
    5485                 :        1092 :         resultRelInfo->ri_WithCheckOptionExprs = wcoExprs;
    5486                 :        1092 :         resultRelInfo++;
    5487                 :             :     }
    5488                 :             : 
    5489                 :             :     /*
    5490                 :             :      * Initialize RETURNING projections if needed.
    5491                 :             :      */
    5492         [ +  + ]:       76867 :     if (returningLists)
    5493                 :             :     {
    5494                 :             :         TupleTableSlot *slot;
    5495                 :             :         ExprContext *econtext;
    5496                 :             : 
    5497                 :             :         /*
    5498                 :             :          * Initialize result tuple slot and assign its rowtype using the plan
    5499                 :             :          * node's declared targetlist, which the planner set up to be the same
    5500                 :             :          * as the first (before runtime pruning) RETURNING list.  We assume
    5501                 :             :          * all the result rels will produce compatible output.
    5502                 :             :          */
    5503                 :        3733 :         ExecInitResultTupleSlotTL(&mtstate->ps, &TTSOpsVirtual);
    5504                 :        3733 :         slot = mtstate->ps.ps_ResultTupleSlot;
    5505                 :             : 
    5506                 :             :         /* Need an econtext too */
    5507         [ +  - ]:        3733 :         if (mtstate->ps.ps_ExprContext == NULL)
    5508                 :        3733 :             ExecAssignExprContext(estate, &mtstate->ps);
    5509                 :        3733 :         econtext = mtstate->ps.ps_ExprContext;
    5510                 :             : 
    5511                 :             :         /*
    5512                 :             :          * Build a projection for each result rel.
    5513                 :             :          */
    5514                 :        3733 :         resultRelInfo = mtstate->resultRelInfo;
    5515   [ +  -  +  +  :        7686 :         foreach(l, returningLists)
                   +  + ]
    5516                 :             :         {
    5517                 :        3953 :             List       *rlist = (List *) lfirst(l);
    5518                 :             : 
    5519                 :        3953 :             resultRelInfo->ri_returningList = rlist;
    5520                 :        3953 :             resultRelInfo->ri_projectReturning =
    5521                 :        3953 :                 ExecBuildProjectionInfo(rlist, econtext, slot, &mtstate->ps,
    5522                 :        3953 :                                         resultRelInfo->ri_RelationDesc->rd_att);
    5523                 :        3953 :             resultRelInfo++;
    5524                 :             :         }
    5525                 :             :     }
    5526                 :             :     else
    5527                 :             :     {
    5528                 :             :         /*
    5529                 :             :          * We still must construct a dummy result tuple type, because InitPlan
    5530                 :             :          * expects one (maybe should change that?).
    5531                 :             :          */
    5532                 :       73134 :         ExecInitResultTypeTL(&mtstate->ps);
    5533                 :             : 
    5534                 :       73134 :         mtstate->ps.ps_ExprContext = NULL;
    5535                 :             :     }
    5536                 :             : 
    5537                 :             :     /* Set the list of arbiter indexes if needed for ON CONFLICT */
    5538                 :       76867 :     resultRelInfo = mtstate->resultRelInfo;
    5539         [ +  + ]:       76867 :     if (node->onConflictAction != ONCONFLICT_NONE)
    5540                 :             :     {
    5541                 :             :         /* insert may only have one relation, inheritance is not expanded */
    5542                 :             :         Assert(total_nrels == 1);
    5543                 :        1193 :         resultRelInfo->ri_onConflictArbiterIndexes = node->arbiterIndexes;
    5544                 :             :     }
    5545                 :             : 
    5546                 :             :     /*
    5547                 :             :      * For ON CONFLICT DO SELECT/UPDATE, initialize the ON CONFLICT action
    5548                 :             :      * state.
    5549                 :             :      */
    5550         [ +  + ]:       76867 :     if (node->onConflictAction == ONCONFLICT_UPDATE ||
    5551         [ +  + ]:       76198 :         node->onConflictAction == ONCONFLICT_SELECT)
    5552                 :             :     {
    5553                 :         889 :         OnConflictActionState *onconfl = makeNode(OnConflictActionState);
    5554                 :             : 
    5555                 :             :         /* already exists if created by RETURNING processing above */
    5556         [ +  + ]:         889 :         if (mtstate->ps.ps_ExprContext == NULL)
    5557                 :         453 :             ExecAssignExprContext(estate, &mtstate->ps);
    5558                 :             : 
    5559                 :             :         /* action state for DO SELECT/UPDATE */
    5560                 :         889 :         resultRelInfo->ri_onConflict = onconfl;
    5561                 :             : 
    5562                 :             :         /* lock strength for DO SELECT [FOR UPDATE/SHARE] */
    5563                 :         889 :         onconfl->oc_LockStrength = node->onConflictLockStrength;
    5564                 :             : 
    5565                 :             :         /* initialize slot for the existing tuple */
    5566                 :         889 :         onconfl->oc_Existing =
    5567                 :         889 :             table_slot_create(resultRelInfo->ri_RelationDesc,
    5568                 :         889 :                               &mtstate->ps.state->es_tupleTable);
    5569                 :             : 
    5570                 :             :         /*
    5571                 :             :          * For ON CONFLICT DO UPDATE, initialize target list and projection.
    5572                 :             :          */
    5573         [ +  + ]:         889 :         if (node->onConflictAction == ONCONFLICT_UPDATE)
    5574                 :             :         {
    5575                 :             :             ExprContext *econtext;
    5576                 :             :             TupleDesc   relationDesc;
    5577                 :             : 
    5578                 :         669 :             econtext = mtstate->ps.ps_ExprContext;
    5579                 :         669 :             relationDesc = resultRelInfo->ri_RelationDesc->rd_att;
    5580                 :             : 
    5581                 :             :             /*
    5582                 :             :              * Create the tuple slot for the UPDATE SET projection. We want a
    5583                 :             :              * slot of the table's type here, because the slot will be used to
    5584                 :             :              * insert into the table, and for RETURNING processing - which may
    5585                 :             :              * access system attributes.
    5586                 :             :              */
    5587                 :         669 :             onconfl->oc_ProjSlot =
    5588                 :         669 :                 table_slot_create(resultRelInfo->ri_RelationDesc,
    5589                 :         669 :                                   &mtstate->ps.state->es_tupleTable);
    5590                 :             : 
    5591                 :             :             /* build UPDATE SET projection state */
    5592                 :         669 :             onconfl->oc_ProjInfo =
    5593                 :         669 :                 ExecBuildUpdateProjection(node->onConflictSet,
    5594                 :             :                                           true,
    5595                 :             :                                           node->onConflictCols,
    5596                 :             :                                           relationDesc,
    5597                 :             :                                           econtext,
    5598                 :             :                                           onconfl->oc_ProjSlot,
    5599                 :             :                                           &mtstate->ps);
    5600                 :             :         }
    5601                 :             : 
    5602                 :             :         /* initialize state to evaluate the WHERE clause, if any */
    5603         [ +  + ]:         889 :         if (node->onConflictWhere)
    5604                 :             :         {
    5605                 :             :             ExprState  *qualexpr;
    5606                 :             : 
    5607                 :         207 :             qualexpr = ExecInitQual((List *) node->onConflictWhere,
    5608                 :             :                                     &mtstate->ps);
    5609                 :         207 :             onconfl->oc_WhereClause = qualexpr;
    5610                 :             :         }
    5611                 :             :     }
    5612                 :             : 
    5613                 :             :     /*
    5614                 :             :      * If needed, initialize the target range for FOR PORTION OF.
    5615                 :             :      */
    5616         [ +  + ]:       76867 :     if (node->forPortionOf)
    5617                 :             :     {
    5618                 :             :         ResultRelInfo *rootRelInfo;
    5619                 :             :         TupleDesc   tupDesc;
    5620                 :             :         ForPortionOfExpr *forPortionOf;
    5621                 :             :         Datum       targetRange;
    5622                 :             :         bool        isNull;
    5623                 :             :         ExprContext *econtext;
    5624                 :             :         ExprState  *exprState;
    5625                 :             :         ForPortionOfState *fpoState;
    5626                 :             : 
    5627                 :         916 :         rootRelInfo = mtstate->resultRelInfo;
    5628         [ +  + ]:         916 :         if (rootRelInfo->ri_RootResultRelInfo)
    5629                 :          74 :             rootRelInfo = rootRelInfo->ri_RootResultRelInfo;
    5630                 :             : 
    5631                 :         916 :         tupDesc = rootRelInfo->ri_RelationDesc->rd_att;
    5632                 :         916 :         forPortionOf = (ForPortionOfExpr *) node->forPortionOf;
    5633                 :             : 
    5634                 :             :         /* Eval the FOR PORTION OF target */
    5635         [ +  + ]:         916 :         if (mtstate->ps.ps_ExprContext == NULL)
    5636                 :         892 :             ExecAssignExprContext(estate, &mtstate->ps);
    5637                 :         916 :         econtext = mtstate->ps.ps_ExprContext;
    5638                 :             : 
    5639                 :         916 :         exprState = ExecPrepareExpr((Expr *) forPortionOf->targetRange, estate);
    5640                 :         916 :         targetRange = ExecEvalExpr(exprState, econtext, &isNull);
    5641                 :             : 
    5642                 :             :         /*
    5643                 :             :          * FOR PORTION OF ... TO ... FROM should never give us a NULL target,
    5644                 :             :          * but FOR PORTION OF (...) could.
    5645                 :             :          */
    5646         [ +  + ]:         916 :         if (isNull)
    5647         [ +  - ]:          16 :             ereport(ERROR,
    5648                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5649                 :             :                      errmsg("FOR PORTION OF target must not be null"),
    5650                 :             :                      executor_errposition(estate, forPortionOf->targetLocation)));
    5651                 :             : 
    5652                 :             :         /* Create state for FOR PORTION OF operation */
    5653                 :             : 
    5654                 :         900 :         fpoState = makeNode(ForPortionOfState);
    5655                 :         900 :         fpoState->fp_rangeType = forPortionOf->rangeType;
    5656                 :         900 :         fpoState->fp_rangeAttno = forPortionOf->rangeVar->varattno;
    5657                 :         900 :         fpoState->fp_targetRange = targetRange;
    5658                 :             : 
    5659                 :             :         /* Initialize slot for the existing tuple */
    5660                 :             : 
    5661                 :         900 :         fpoState->fp_Existing =
    5662                 :         900 :             table_slot_create(rootRelInfo->ri_RelationDesc,
    5663                 :         900 :                               &mtstate->ps.state->es_tupleTable);
    5664                 :             : 
    5665                 :             :         /* Create the tuple slot for INSERTing the temporal leftovers */
    5666                 :             : 
    5667                 :         900 :         fpoState->fp_Leftover =
    5668                 :         900 :             ExecInitExtraTupleSlot(mtstate->ps.state, tupDesc, &TTSOpsVirtual);
    5669                 :             : 
    5670                 :         900 :         rootRelInfo->ri_forPortionOf = fpoState;
    5671                 :             : 
    5672                 :             :         /*
    5673                 :             :          * Make sure the root relation has the FOR PORTION OF clause too. Each
    5674                 :             :          * partition needs its own TupleTableSlot, since they can have
    5675                 :             :          * different descriptors, so they'll use the root fpoState to
    5676                 :             :          * initialize one if necessary.
    5677                 :             :          */
    5678         [ +  + ]:         900 :         if (node->rootRelation > 0)
    5679                 :          74 :             mtstate->rootResultRelInfo->ri_forPortionOf = fpoState;
    5680                 :             : 
    5681         [ +  + ]:         900 :         if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
    5682         [ +  - ]:          58 :             mtstate->mt_partition_tuple_routing == NULL)
    5683                 :             :         {
    5684                 :             :             /*
    5685                 :             :              * We will need tuple routing to insert temporal leftovers. Since
    5686                 :             :              * we are initializing things before ExecCrossPartitionUpdate
    5687                 :             :              * runs, we must do everything it needs as well.
    5688                 :             :              */
    5689                 :          58 :             Relation    rootRel = mtstate->rootResultRelInfo->ri_RelationDesc;
    5690                 :             :             MemoryContext oldcxt;
    5691                 :             : 
    5692                 :             :             /* Things built here have to last for the query duration. */
    5693                 :          58 :             oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
    5694                 :             : 
    5695                 :          58 :             mtstate->mt_partition_tuple_routing =
    5696                 :          58 :                 ExecSetupPartitionTupleRouting(estate, rootRel);
    5697                 :             : 
    5698                 :             :             /*
    5699                 :             :              * Before a partition's tuple can be re-routed, it must first be
    5700                 :             :              * converted to the root's format, so we'll need a slot for
    5701                 :             :              * storing such tuples.
    5702                 :             :              */
    5703                 :             :             Assert(mtstate->mt_root_tuple_slot == NULL);
    5704                 :          58 :             mtstate->mt_root_tuple_slot = table_slot_create(rootRel, NULL);
    5705                 :             : 
    5706                 :          58 :             MemoryContextSwitchTo(oldcxt);
    5707                 :             :         }
    5708                 :             : 
    5709                 :             :         /*
    5710                 :             :          * Don't free the ExprContext here because the result must last for
    5711                 :             :          * the whole query.
    5712                 :             :          */
    5713                 :             :     }
    5714                 :             : 
    5715                 :             :     /*
    5716                 :             :      * If we have any secondary relations in an UPDATE or DELETE, they need to
    5717                 :             :      * be treated like non-locked relations in SELECT FOR UPDATE, i.e., the
    5718                 :             :      * EvalPlanQual mechanism needs to be told about them.  This also goes for
    5719                 :             :      * the source relations in a MERGE.  Locate the relevant ExecRowMarks.
    5720                 :             :      */
    5721                 :       76851 :     arowmarks = NIL;
    5722   [ +  +  +  +  :       78744 :     foreach(l, node->rowMarks)
                   +  + ]
    5723                 :             :     {
    5724                 :        1893 :         PlanRowMark *rc = lfirst_node(PlanRowMark, l);
    5725                 :        1893 :         RangeTblEntry *rte = exec_rt_fetch(rc->rti, estate);
    5726                 :             :         ExecRowMark *erm;
    5727                 :             :         ExecAuxRowMark *aerm;
    5728                 :             : 
    5729                 :             :         /* ignore "parent" rowmarks; they are irrelevant at runtime */
    5730         [ +  + ]:        1893 :         if (rc->isParent)
    5731                 :          94 :             continue;
    5732                 :             : 
    5733                 :             :         /*
    5734                 :             :          * Also ignore rowmarks belonging to child tables that have been
    5735                 :             :          * pruned in ExecDoInitialPruning().
    5736                 :             :          */
    5737         [ +  + ]:        1799 :         if (rte->rtekind == RTE_RELATION &&
    5738         [ -  + ]:        1418 :             !bms_is_member(rc->rti, estate->es_unpruned_relids))
    5739                 :           0 :             continue;
    5740                 :             : 
    5741                 :             :         /* Find ExecRowMark and build ExecAuxRowMark */
    5742                 :        1799 :         erm = ExecFindRowMark(estate, rc->rti, false);
    5743                 :        1799 :         aerm = ExecBuildAuxRowMark(erm, subplan->targetlist);
    5744                 :        1799 :         arowmarks = lappend(arowmarks, aerm);
    5745                 :             :     }
    5746                 :             : 
    5747                 :             :     /* For a MERGE command, initialize its state */
    5748         [ +  + ]:       76851 :     if (mtstate->operation == CMD_MERGE)
    5749                 :        1060 :         ExecInitMerge(mtstate, estate);
    5750                 :             : 
    5751                 :       76851 :     EvalPlanQualSetPlan(&mtstate->mt_epqstate, subplan, arowmarks);
    5752                 :             : 
    5753                 :             :     /*
    5754                 :             :      * If there are a lot of result relations, use a hash table to speed the
    5755                 :             :      * lookups.  If there are not a lot, a simple linear search is faster.
    5756                 :             :      *
    5757                 :             :      * It's not clear where the threshold is, but try 64 for starters.  In a
    5758                 :             :      * debugging build, use a small threshold so that we get some test
    5759                 :             :      * coverage of both code paths.
    5760                 :             :      */
    5761                 :             : #ifdef USE_ASSERT_CHECKING
    5762                 :             : #define MT_NRELS_HASH 4
    5763                 :             : #else
    5764                 :             : #define MT_NRELS_HASH 64
    5765                 :             : #endif
    5766         [ -  + ]:       76851 :     if (nrels >= MT_NRELS_HASH)
    5767                 :             :     {
    5768                 :             :         HASHCTL     hash_ctl;
    5769                 :             : 
    5770                 :           0 :         hash_ctl.keysize = sizeof(Oid);
    5771                 :           0 :         hash_ctl.entrysize = sizeof(MTTargetRelLookup);
    5772                 :           0 :         hash_ctl.hcxt = CurrentMemoryContext;
    5773                 :           0 :         mtstate->mt_resultOidHash =
    5774                 :           0 :             hash_create("ModifyTable target hash",
    5775                 :             :                         nrels, &hash_ctl,
    5776                 :             :                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    5777         [ #  # ]:           0 :         for (i = 0; i < nrels; i++)
    5778                 :             :         {
    5779                 :             :             Oid         hashkey;
    5780                 :             :             MTTargetRelLookup *mtlookup;
    5781                 :             :             bool        found;
    5782                 :             : 
    5783                 :           0 :             resultRelInfo = &mtstate->resultRelInfo[i];
    5784                 :           0 :             hashkey = RelationGetRelid(resultRelInfo->ri_RelationDesc);
    5785                 :             :             mtlookup = (MTTargetRelLookup *)
    5786                 :           0 :                 hash_search(mtstate->mt_resultOidHash, &hashkey,
    5787                 :             :                             HASH_ENTER, &found);
    5788                 :             :             Assert(!found);
    5789                 :           0 :             mtlookup->relationIndex = i;
    5790                 :             :         }
    5791                 :             :     }
    5792                 :             :     else
    5793                 :       76851 :         mtstate->mt_resultOidHash = NULL;
    5794                 :             : 
    5795                 :             :     /*
    5796                 :             :      * Determine if the FDW supports batch insert and determine the batch size
    5797                 :             :      * (a FDW may support batching, but it may be disabled for the
    5798                 :             :      * server/table).
    5799                 :             :      *
    5800                 :             :      * We only do this for INSERT, so that for UPDATE/DELETE the batch size
    5801                 :             :      * remains set to 0.
    5802                 :             :      */
    5803         [ +  + ]:       76851 :     if (operation == CMD_INSERT)
    5804                 :             :     {
    5805                 :             :         /* insert may only have one relation, inheritance is not expanded */
    5806                 :             :         Assert(total_nrels == 1);
    5807                 :       57956 :         resultRelInfo = mtstate->resultRelInfo;
    5808         [ +  - ]:       57956 :         if (!resultRelInfo->ri_usesFdwDirectModify &&
    5809         [ +  + ]:       57956 :             resultRelInfo->ri_FdwRoutine != NULL &&
    5810         [ +  - ]:          88 :             resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
    5811         [ +  - ]:          88 :             resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
    5812                 :             :         {
    5813                 :          88 :             resultRelInfo->ri_BatchSize =
    5814                 :          88 :                 resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
    5815                 :          88 :             Assert(resultRelInfo->ri_BatchSize >= 1);
    5816                 :             :         }
    5817                 :             :         else
    5818                 :       57868 :             resultRelInfo->ri_BatchSize = 1;
    5819                 :             :     }
    5820                 :             : 
    5821                 :             :     /*
    5822                 :             :      * Lastly, if this is not the primary (canSetTag) ModifyTable node, add it
    5823                 :             :      * to estate->es_auxmodifytables so that it will be run to completion by
    5824                 :             :      * ExecPostprocessPlan.  (It'd actually work fine to add the primary
    5825                 :             :      * ModifyTable node too, but there's no need.)  Note the use of lcons not
    5826                 :             :      * lappend: we need later-initialized ModifyTable nodes to be shut down
    5827                 :             :      * before earlier ones.  This ensures that we don't throw away RETURNING
    5828                 :             :      * rows that need to be seen by a later CTE subplan.
    5829                 :             :      */
    5830         [ +  + ]:       76851 :     if (!mtstate->canSetTag)
    5831                 :         702 :         estate->es_auxmodifytables = lcons(mtstate,
    5832                 :             :                                            estate->es_auxmodifytables);
    5833                 :             : 
    5834                 :       76851 :     return mtstate;
    5835                 :             : }
    5836                 :             : 
    5837                 :             : /* ----------------------------------------------------------------
    5838                 :             :  *      ExecEndModifyTable
    5839                 :             :  *
    5840                 :             :  *      Shuts down the plan.
    5841                 :             :  *
    5842                 :             :  *      Returns nothing of interest.
    5843                 :             :  * ----------------------------------------------------------------
    5844                 :             :  */
    5845                 :             : void
    5846                 :       73712 : ExecEndModifyTable(ModifyTableState *node)
    5847                 :             : {
    5848                 :             :     int         i;
    5849                 :             : 
    5850                 :             :     /*
    5851                 :             :      * Allow any FDWs to shut down
    5852                 :             :      */
    5853         [ +  + ]:      148823 :     for (i = 0; i < node->mt_nrels; i++)
    5854                 :             :     {
    5855                 :             :         int         j;
    5856                 :       75111 :         ResultRelInfo *resultRelInfo = node->resultRelInfo + i;
    5857                 :             : 
    5858         [ +  + ]:       75111 :         if (!resultRelInfo->ri_usesFdwDirectModify &&
    5859         [ +  + ]:       75011 :             resultRelInfo->ri_FdwRoutine != NULL &&
    5860         [ +  - ]:         159 :             resultRelInfo->ri_FdwRoutine->EndForeignModify != NULL)
    5861                 :         159 :             resultRelInfo->ri_FdwRoutine->EndForeignModify(node->ps.state,
    5862                 :             :                                                            resultRelInfo);
    5863                 :             : 
    5864                 :             :         /*
    5865                 :             :          * Cleanup the initialized batch slots. This only matters for FDWs
    5866                 :             :          * with batching, but the other cases will have ri_NumSlotsInitialized
    5867                 :             :          * == 0.
    5868                 :             :          */
    5869         [ +  + ]:       75139 :         for (j = 0; j < resultRelInfo->ri_NumSlotsInitialized; j++)
    5870                 :             :         {
    5871                 :          28 :             ExecDropSingleTupleTableSlot(resultRelInfo->ri_Slots[j]);
    5872                 :          28 :             ExecDropSingleTupleTableSlot(resultRelInfo->ri_PlanSlots[j]);
    5873                 :             :         }
    5874                 :             :     }
    5875                 :             : 
    5876                 :             :     /*
    5877                 :             :      * Close all the partitioned tables, leaf partitions, and their indices
    5878                 :             :      * and release the slot used for tuple routing, if set.
    5879                 :             :      */
    5880         [ +  + ]:       73712 :     if (node->mt_partition_tuple_routing)
    5881                 :             :     {
    5882                 :        3840 :         ExecCleanupTupleRouting(node, node->mt_partition_tuple_routing);
    5883                 :             : 
    5884         [ +  + ]:        3840 :         if (node->mt_root_tuple_slot)
    5885                 :         484 :             ExecDropSingleTupleTableSlot(node->mt_root_tuple_slot);
    5886                 :             :     }
    5887                 :             : 
    5888                 :             :     /*
    5889                 :             :      * Terminate EPQ execution if active
    5890                 :             :      */
    5891                 :       73712 :     EvalPlanQualEnd(&node->mt_epqstate);
    5892                 :             : 
    5893                 :             :     /*
    5894                 :             :      * shut down subplan
    5895                 :             :      */
    5896                 :       73712 :     ExecEndNode(outerPlanState(node));
    5897                 :       73712 : }
    5898                 :             : 
    5899                 :             : void
    5900                 :           0 : ExecReScanModifyTable(ModifyTableState *node)
    5901                 :             : {
    5902                 :             :     /*
    5903                 :             :      * Currently, we don't need to support rescan on ModifyTable nodes. The
    5904                 :             :      * semantics of that would be a bit debatable anyway.
    5905                 :             :      */
    5906         [ #  # ]:           0 :     elog(ERROR, "ExecReScanModifyTable is not implemented");
    5907                 :             : }
    5908                 :             : 
    5909                 :             : /* ----------------------------------------------------------------
    5910                 :             :  *      ExecInitForPortionOf
    5911                 :             :  *
    5912                 :             :  *      Initializes resultRelInfo->ri_forPortionOf for child tables.
    5913                 :             :  *
    5914                 :             :  *      Partitions share the root leftover slot, since they must insert via
    5915                 :             :  *      the root relation to get tuple routing. Plain inheritance children
    5916                 :             :  *      must keep their own leftover slot and insert back into the child, or
    5917                 :             :  *      else child-only column values and physical placement would be lost.
    5918                 :             :  * ----------------------------------------------------------------
    5919                 :             :  */
    5920                 :             : static void
    5921                 :          74 : ExecInitForPortionOf(ModifyTableState *mtstate, EState *estate,
    5922                 :             :                      ResultRelInfo *resultRelInfo)
    5923                 :             : {
    5924                 :             :     MemoryContext oldcxt;
    5925                 :             :     ForPortionOfState *leafState;
    5926                 :          74 :     ResultRelInfo *rootRelInfo = mtstate->rootResultRelInfo;
    5927                 :             :     ForPortionOfState *fpoState;
    5928                 :             :     TupleConversionMap *map;
    5929                 :             : 
    5930         [ -  + ]:          74 :     if (!rootRelInfo)
    5931         [ #  # ]:           0 :         elog(ERROR, "no root relation but ri_forPortionOf is uninitialized");
    5932                 :             : 
    5933                 :          74 :     fpoState = rootRelInfo->ri_forPortionOf;
    5934                 :             :     Assert(fpoState);
    5935                 :             : 
    5936                 :             :     /* Things built here have to last for the query duration. */
    5937                 :          74 :     oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
    5938                 :             : 
    5939                 :          74 :     leafState = makeNode(ForPortionOfState);
    5940                 :             : 
    5941                 :          74 :     leafState->fp_rangeType = fpoState->fp_rangeType;
    5942                 :          74 :     leafState->fp_targetRange = fpoState->fp_targetRange;
    5943                 :          74 :     map = ExecGetChildToRootMap(resultRelInfo);
    5944                 :             : 
    5945                 :             :     /*
    5946                 :             :      * fp_rangeAttno must match the tuple layout used for reading the old
    5947                 :             :      * range value. The query uses the target relation's attno, so translate
    5948                 :             :      * it to the child attno when the child has a different column layout.
    5949                 :             :      */
    5950         [ +  + ]:          74 :     if (map)
    5951                 :          32 :         leafState->fp_rangeAttno = map->attrMap->attnums[fpoState->fp_rangeAttno - 1];
    5952                 :             :     else
    5953                 :          42 :         leafState->fp_rangeAttno = fpoState->fp_rangeAttno;
    5954                 :             : 
    5955                 :             :     /*
    5956                 :             :      * For partitioned tables we must read the leftovers using the child
    5957                 :             :      * table's tuple descriptor, but then insert them into the root table
    5958                 :             :      * (using its tuple descriptor) so we get tuple routing.
    5959                 :             :      *
    5960                 :             :      * For traditional table inheritance, we read and insert directly into
    5961                 :             :      * this resultRelInfo; no tuple routing via the parent is required.
    5962                 :             :      */
    5963         [ +  + ]:          74 :     if (rootRelInfo->ri_RelationDesc->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    5964                 :          58 :         leafState->fp_Leftover = fpoState->fp_Leftover;
    5965                 :             :     else
    5966                 :          16 :         leafState->fp_Leftover =
    5967                 :          16 :             ExecInitExtraTupleSlot(mtstate->ps.state,
    5968                 :          16 :                                    RelationGetDescr(resultRelInfo->ri_RelationDesc),
    5969                 :             :                                    &TTSOpsVirtual);
    5970                 :             : 
    5971                 :             :     /* Each child relation needs a slot matching its tuple descriptor. */
    5972                 :          74 :     leafState->fp_Existing =
    5973                 :          74 :         table_slot_create(resultRelInfo->ri_RelationDesc,
    5974                 :          74 :                           &mtstate->ps.state->es_tupleTable);
    5975                 :             : 
    5976                 :          74 :     resultRelInfo->ri_forPortionOf = leafState;
    5977                 :             : 
    5978                 :          74 :     MemoryContextSwitchTo(oldcxt);
    5979                 :          74 : }
        

Generated by: LCOV version 2.0-1