LCOV - code coverage report
Current view: top level - src/backend/executor - nodeModifyTable.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.9 % 1572 1461
Test Date: 2026-11-24 10:15:57 Functions: 97.6 % 41 40
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 78.9 % 1148 906

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

Generated by: LCOV version 2.0-1