LCOV - code coverage report
Current view: top level - src/backend/tcop - pquery.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.5 % 585 541
Test Date: 2026-11-12 13:16:03 Functions: 100.0 % 22 22
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 78.1 % 401 313

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * pquery.c
       4                 :             :  *    POSTGRES process query command code
       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/tcop/pquery.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : 
      16                 :             : #include "postgres.h"
      17                 :             : 
      18                 :             : #include <limits.h>
      19                 :             : 
      20                 :             : #include "access/xact.h"
      21                 :             : #include "commands/prepare.h"
      22                 :             : #include "executor/executor.h"
      23                 :             : #include "executor/tstoreReceiver.h"
      24                 :             : #include "miscadmin.h"
      25                 :             : #include "pg_trace.h"
      26                 :             : #include "port/pg_bitutils.h"
      27                 :             : #include "tcop/pquery.h"
      28                 :             : #include "tcop/utility.h"
      29                 :             : #include "utils/memutils.h"
      30                 :             : #include "utils/snapmgr.h"
      31                 :             : 
      32                 :             : /*
      33                 :             :  * ActivePortal is the currently executing Portal (the most closely nested,
      34                 :             :  * if there are several).
      35                 :             :  */
      36                 :             : Portal      ActivePortal = NULL;
      37                 :             : 
      38                 :             : /* Private data for QueryDesc.extension_state. */
      39                 :             : static const char **QueryDescExtensionNameArray = NULL;
      40                 :             : static int  QueryDescExtensionNamesAssigned = 0;
      41                 :             : static int  QueryDescExtensionNamesAllocated = 0;
      42                 :             : 
      43                 :             : static void ProcessQuery(PlannedStmt *plan,
      44                 :             :                          const char *sourceText,
      45                 :             :                          ParamListInfo params,
      46                 :             :                          QueryEnvironment *queryEnv,
      47                 :             :                          DestReceiver *dest,
      48                 :             :                          QueryCompletion *qc);
      49                 :             : static void FillPortalStore(Portal portal, bool isTopLevel);
      50                 :             : static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count,
      51                 :             :                            DestReceiver *dest);
      52                 :             : static uint64 PortalRunSelect(Portal portal, bool forward, long count,
      53                 :             :                               DestReceiver *dest);
      54                 :             : static void PortalRunUtility(Portal portal, PlannedStmt *pstmt,
      55                 :             :                              bool isTopLevel, bool setHoldSnapshot,
      56                 :             :                              DestReceiver *dest, QueryCompletion *qc);
      57                 :             : static void PortalRunMulti(Portal portal,
      58                 :             :                            bool isTopLevel, bool setHoldSnapshot,
      59                 :             :                            DestReceiver *dest, DestReceiver *altdest,
      60                 :             :                            QueryCompletion *qc);
      61                 :             : static uint64 DoPortalRunFetch(Portal portal,
      62                 :             :                                FetchDirection fdirection,
      63                 :             :                                long count,
      64                 :             :                                DestReceiver *dest);
      65                 :             : static void DoPortalRewind(Portal portal);
      66                 :             : 
      67                 :             : 
      68                 :             : /*
      69                 :             :  * CreateQueryDesc
      70                 :             :  */
      71                 :             : QueryDesc *
      72                 :      382554 : CreateQueryDesc(PlannedStmt *plannedstmt,
      73                 :             :                 const char *sourceText,
      74                 :             :                 Snapshot snapshot,
      75                 :             :                 Snapshot crosscheck_snapshot,
      76                 :             :                 DestReceiver *dest,
      77                 :             :                 ParamListInfo params,
      78                 :             :                 QueryEnvironment *queryEnv,
      79                 :             :                 int instrument_options)
      80                 :             : {
      81                 :      382554 :     QueryDesc  *qd = palloc_object(QueryDesc);
      82                 :             : 
      83                 :      382554 :     qd->operation = plannedstmt->commandType; /* operation */
      84                 :      382554 :     qd->plannedstmt = plannedstmt;   /* plan */
      85                 :      382554 :     qd->sourceText = sourceText; /* query text */
      86                 :      382554 :     qd->snapshot = RegisterSnapshot(snapshot);   /* snapshot */
      87                 :             :     /* RI check snapshot */
      88                 :      382554 :     qd->crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);
      89                 :      382554 :     qd->dest = dest;         /* output dest */
      90                 :      382554 :     qd->params = params;     /* parameter values passed into query */
      91                 :      382554 :     qd->queryEnv = queryEnv;
      92                 :      382554 :     qd->instrument_options = instrument_options; /* instrumentation wanted? */
      93                 :      382554 :     qd->query_instr_options = 0;
      94                 :             : 
      95                 :             :     /* null these fields until set by ExecutorStart */
      96                 :      382554 :     qd->tupDesc = NULL;
      97                 :      382554 :     qd->estate = NULL;
      98                 :      382554 :     qd->planstate = NULL;
      99                 :      382554 :     qd->query_instr = NULL;
     100                 :             : 
     101                 :             :     /* not yet executed */
     102                 :      382554 :     qd->already_executed = false;
     103                 :             : 
     104                 :             :     /* no extension state yet */
     105                 :      382554 :     qd->extension_state = NULL;
     106                 :      382554 :     qd->extension_state_allocated = 0;
     107                 :             : 
     108                 :      382554 :     return qd;
     109                 :             : }
     110                 :             : 
     111                 :             : /*
     112                 :             :  * FreeQueryDesc
     113                 :             :  */
     114                 :             : void
     115                 :      362812 : FreeQueryDesc(QueryDesc *qdesc)
     116                 :             : {
     117                 :             :     /* Can't be a live query */
     118                 :             :     Assert(qdesc->estate == NULL);
     119                 :             : 
     120                 :             :     /* forget our snapshots */
     121                 :      362812 :     UnregisterSnapshot(qdesc->snapshot);
     122                 :      362812 :     UnregisterSnapshot(qdesc->crosscheck_snapshot);
     123                 :             : 
     124                 :             :     /* Free extension state pointers */
     125         [ +  + ]:      362812 :     if (qdesc->extension_state != NULL)
     126                 :       39907 :         pfree(qdesc->extension_state);
     127                 :             : 
     128                 :             :     /* Free the QueryDesc itself */
     129                 :      362812 :     pfree(qdesc);
     130                 :      362812 : }
     131                 :             : 
     132                 :             : /*
     133                 :             :  * Map the name of an extension to an integer ID, to be used with
     134                 :             :  * SetQueryDescExtensionState() and GetQueryDescExtensionState().
     135                 :             :  *
     136                 :             :  * Within the lifetime of a particular backend, the same name will be mapped
     137                 :             :  * to the same ID every time.  IDs are not stable across backends.
     138                 :             :  */
     139                 :             : int
     140                 :           9 : GetQueryDescExtensionId(const char *extension_name)
     141                 :             : {
     142                 :             :     /* Search for an existing extension by this name; if found, return ID. */
     143         [ -  + ]:           9 :     for (int i = 0; i < QueryDescExtensionNamesAssigned; ++i)
     144         [ #  # ]:           0 :         if (strcmp(QueryDescExtensionNameArray[i], extension_name) == 0)
     145                 :           0 :             return i;
     146                 :             : 
     147                 :             :     /* If there is no array yet, create one. */
     148         [ +  - ]:           9 :     if (QueryDescExtensionNameArray == NULL)
     149                 :             :     {
     150                 :           9 :         QueryDescExtensionNamesAllocated = 16;
     151                 :           9 :         QueryDescExtensionNameArray = (const char **)
     152                 :           9 :             MemoryContextAlloc(TopMemoryContext,
     153                 :             :                                QueryDescExtensionNamesAllocated
     154                 :             :                                * sizeof(char *));
     155                 :             :     }
     156                 :             : 
     157                 :             :     /* If there's an array but it's currently full, expand it. */
     158         [ -  + ]:           9 :     if (QueryDescExtensionNamesAssigned >= QueryDescExtensionNamesAllocated)
     159                 :             :     {
     160                 :           0 :         int         i = pg_nextpower2_32(QueryDescExtensionNamesAssigned + 1);
     161                 :             : 
     162                 :           0 :         QueryDescExtensionNameArray =
     163                 :           0 :             repalloc_array(QueryDescExtensionNameArray, const char *, i);
     164                 :           0 :         QueryDescExtensionNamesAllocated = i;
     165                 :             :     }
     166                 :             : 
     167                 :             :     /* Assign and return new ID.  The name is copied, to be on the safe side. */
     168                 :          18 :     QueryDescExtensionNameArray[QueryDescExtensionNamesAssigned] =
     169                 :           9 :         MemoryContextStrdup(TopMemoryContext, extension_name);
     170                 :           9 :     return QueryDescExtensionNamesAssigned++;
     171                 :             : }
     172                 :             : 
     173                 :             : /*
     174                 :             :  * Get extension-specific state from a QueryDesc, or NULL if none was set.
     175                 :             :  */
     176                 :             : void *
     177                 :       57021 : GetQueryDescExtensionState(QueryDesc *qdesc, int extension_id)
     178                 :             : {
     179                 :             :     Assert(extension_id >= 0);
     180                 :             : 
     181         [ +  + ]:       57021 :     if (extension_id >= qdesc->extension_state_allocated)
     182                 :       17114 :         return NULL;
     183                 :             : 
     184                 :       39907 :     return qdesc->extension_state[extension_id];
     185                 :             : }
     186                 :             : 
     187                 :             : /*
     188                 :             :  * Store extension-specific state into a QueryDesc.
     189                 :             :  *
     190                 :             :  * The array of pointers is allocated in the memory context of the QueryDesc,
     191                 :             :  * and is freed by FreeQueryDesc().
     192                 :             :  */
     193                 :             : void
     194                 :       41946 : SetQueryDescExtensionState(QueryDesc *qdesc, int extension_id, void *opaque)
     195                 :             : {
     196                 :             :     Assert(extension_id >= 0);
     197                 :             : 
     198                 :             :     /* If there is no array yet, create one. */
     199         [ +  - ]:       41946 :     if (qdesc->extension_state == NULL)
     200                 :             :     {
     201                 :       41946 :         qdesc->extension_state_allocated =
     202         [ -  + ]:       41946 :             Max(4, pg_nextpower2_32(extension_id + 1));
     203                 :       41946 :         qdesc->extension_state =
     204                 :       41946 :             MemoryContextAllocZero(GetMemoryChunkContext(qdesc),
     205                 :       41946 :                                    qdesc->extension_state_allocated
     206                 :             :                                    * sizeof(void *));
     207                 :             :     }
     208                 :             : 
     209                 :             :     /* If there's an array but it's currently full, expand it. */
     210         [ -  + ]:       41946 :     if (extension_id >= qdesc->extension_state_allocated)
     211                 :             :     {
     212                 :           0 :         int         i = pg_nextpower2_32(extension_id + 1);
     213                 :             : 
     214                 :           0 :         qdesc->extension_state =
     215                 :           0 :             repalloc0_array(qdesc->extension_state, void *,
     216                 :             :                             qdesc->extension_state_allocated, i);
     217                 :           0 :         qdesc->extension_state_allocated = i;
     218                 :             :     }
     219                 :             : 
     220                 :       41946 :     qdesc->extension_state[extension_id] = opaque;
     221                 :       41946 : }
     222                 :             : 
     223                 :             : 
     224                 :             : /*
     225                 :             :  * ProcessQuery
     226                 :             :  *      Execute a single plannable query within a PORTAL_MULTI_QUERY,
     227                 :             :  *      PORTAL_ONE_RETURNING, or PORTAL_ONE_MOD_WITH portal
     228                 :             :  *
     229                 :             :  *  plan: the plan tree for the query
     230                 :             :  *  sourceText: the source text of the query
     231                 :             :  *  params: any parameters needed
     232                 :             :  *  dest: where to send results
     233                 :             :  *  qc: where to store the command completion status data.
     234                 :             :  *
     235                 :             :  * qc may be NULL if caller doesn't want a status string.
     236                 :             :  *
     237                 :             :  * Must be called in a memory context that will be reset or deleted on
     238                 :             :  * error; otherwise the executor's memory usage will be leaked.
     239                 :             :  */
     240                 :             : static void
     241                 :       56584 : ProcessQuery(PlannedStmt *plan,
     242                 :             :              const char *sourceText,
     243                 :             :              ParamListInfo params,
     244                 :             :              QueryEnvironment *queryEnv,
     245                 :             :              DestReceiver *dest,
     246                 :             :              QueryCompletion *qc)
     247                 :             : {
     248                 :             :     QueryDesc  *queryDesc;
     249                 :             : 
     250                 :             :     /*
     251                 :             :      * Create the QueryDesc object
     252                 :             :      */
     253                 :       56584 :     queryDesc = CreateQueryDesc(plan, sourceText,
     254                 :             :                                 GetActiveSnapshot(), InvalidSnapshot,
     255                 :             :                                 dest, params, queryEnv, 0);
     256                 :             : 
     257                 :             :     /*
     258                 :             :      * Call ExecutorStart to prepare the plan for execution
     259                 :             :      */
     260                 :       56584 :     ExecutorStart(queryDesc, 0);
     261                 :             : 
     262                 :             :     /*
     263                 :             :      * Run the plan to completion.
     264                 :             :      */
     265                 :       55891 :     ExecutorRun(queryDesc, ForwardScanDirection, 0);
     266                 :             : 
     267                 :             :     /*
     268                 :             :      * Build command completion status data, if caller wants one.
     269                 :             :      */
     270         [ +  + ]:       53582 :     if (qc)
     271                 :             :     {
     272                 :             :         CommandTag  tag;
     273                 :             : 
     274         [ +  + ]:       53142 :         if (queryDesc->operation == CMD_SELECT)
     275                 :          81 :             tag = CMDTAG_SELECT;
     276         [ +  + ]:       53061 :         else if (queryDesc->operation == CMD_INSERT)
     277                 :       42965 :             tag = CMDTAG_INSERT;
     278         [ +  + ]:       10096 :         else if (queryDesc->operation == CMD_UPDATE)
     279                 :        7042 :             tag = CMDTAG_UPDATE;
     280         [ +  + ]:        3054 :         else if (queryDesc->operation == CMD_DELETE)
     281                 :        2286 :             tag = CMDTAG_DELETE;
     282         [ +  - ]:         768 :         else if (queryDesc->operation == CMD_MERGE)
     283                 :         768 :             tag = CMDTAG_MERGE;
     284                 :             :         else
     285                 :           0 :             tag = CMDTAG_UNKNOWN;
     286                 :             : 
     287                 :       53142 :         SetQueryCompletion(qc, tag, queryDesc->estate->es_processed);
     288                 :             :     }
     289                 :             : 
     290                 :             :     /*
     291                 :             :      * Now, we close down all the scans and free allocated resources.
     292                 :             :      */
     293                 :       53582 :     ExecutorFinish(queryDesc);
     294                 :       52764 :     ExecutorEnd(queryDesc);
     295                 :             : 
     296                 :       52764 :     FreeQueryDesc(queryDesc);
     297                 :       52764 : }
     298                 :             : 
     299                 :             : /*
     300                 :             :  * ChoosePortalStrategy
     301                 :             :  *      Select portal execution strategy given the intended statement list.
     302                 :             :  *
     303                 :             :  * The list elements can be Querys or PlannedStmts.
     304                 :             :  * That's more general than portals need, but plancache.c uses this too.
     305                 :             :  *
     306                 :             :  * See the comments in portal.h.
     307                 :             :  */
     308                 :             : PortalStrategy
     309                 :      541076 : ChoosePortalStrategy(List *stmts)
     310                 :             : {
     311                 :             :     int         nSetTag;
     312                 :             :     ListCell   *lc;
     313                 :             : 
     314                 :             :     /*
     315                 :             :      * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
     316                 :             :      * single-statement case, since there are no rewrite rules that can add
     317                 :             :      * auxiliary queries to a SELECT or a utility command. PORTAL_ONE_MOD_WITH
     318                 :             :      * likewise allows only one top-level statement.
     319                 :             :      */
     320         [ +  + ]:      541076 :     if (list_length(stmts) == 1)
     321                 :             :     {
     322                 :      540828 :         Node       *stmt = (Node *) linitial(stmts);
     323                 :             : 
     324         [ +  + ]:      540828 :         if (IsA(stmt, Query))
     325                 :             :         {
     326                 :       55801 :             Query      *query = (Query *) stmt;
     327                 :             : 
     328         [ +  - ]:       55801 :             if (query->canSetTag)
     329                 :             :             {
     330         [ +  + ]:       55801 :                 if (query->commandType == CMD_SELECT)
     331                 :             :                 {
     332         [ -  + ]:       35687 :                     if (query->hasModifyingCTE)
     333                 :           0 :                         return PORTAL_ONE_MOD_WITH;
     334                 :             :                     else
     335                 :       35687 :                         return PORTAL_ONE_SELECT;
     336                 :             :                 }
     337         [ +  + ]:       20114 :                 if (query->commandType == CMD_UTILITY)
     338                 :             :                 {
     339         [ +  + ]:       15474 :                     if (UtilityReturnsTuples(query->utilityStmt))
     340                 :        6729 :                         return PORTAL_UTIL_SELECT;
     341                 :             :                     /* it can't be ONE_RETURNING, so give up */
     342                 :        8745 :                     return PORTAL_MULTI_QUERY;
     343                 :             :                 }
     344                 :             :             }
     345                 :             :         }
     346         [ +  - ]:      485027 :         else if (IsA(stmt, PlannedStmt))
     347                 :             :         {
     348                 :      485027 :             PlannedStmt *pstmt = (PlannedStmt *) stmt;
     349                 :             : 
     350         [ +  + ]:      485027 :             if (pstmt->canSetTag)
     351                 :             :             {
     352         [ +  + ]:      485003 :                 if (pstmt->commandType == CMD_SELECT)
     353                 :             :                 {
     354         [ +  + ]:      190673 :                     if (pstmt->hasModifyingCTE)
     355                 :          89 :                         return PORTAL_ONE_MOD_WITH;
     356                 :             :                     else
     357                 :      190584 :                         return PORTAL_ONE_SELECT;
     358                 :             :                 }
     359         [ +  + ]:      294330 :                 if (pstmt->commandType == CMD_UTILITY)
     360                 :             :                 {
     361         [ +  + ]:      238515 :                     if (UtilityReturnsTuples(pstmt->utilityStmt))
     362                 :       30356 :                         return PORTAL_UTIL_SELECT;
     363                 :             :                     /* it can't be ONE_RETURNING, so give up */
     364                 :      208159 :                     return PORTAL_MULTI_QUERY;
     365                 :             :                 }
     366                 :             :             }
     367                 :             :         }
     368                 :             :         else
     369         [ #  # ]:           0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
     370                 :             :     }
     371                 :             : 
     372                 :             :     /*
     373                 :             :      * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
     374                 :             :      * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query and
     375                 :             :      * it has a RETURNING list.
     376                 :             :      */
     377                 :       60727 :     nSetTag = 0;
     378   [ +  +  +  +  :       63336 :     foreach(lc, stmts)
                   +  + ]
     379                 :             :     {
     380                 :       60855 :         Node       *stmt = (Node *) lfirst(lc);
     381                 :             : 
     382         [ +  + ]:       60855 :         if (IsA(stmt, Query))
     383                 :             :         {
     384                 :        4648 :             Query      *query = (Query *) stmt;
     385                 :             : 
     386         [ +  + ]:        4648 :             if (query->canSetTag)
     387                 :             :             {
     388         [ -  + ]:        4644 :                 if (++nSetTag > 1)
     389                 :       58246 :                     return PORTAL_MULTI_QUERY;  /* no need to look further */
     390         [ +  - ]:        4644 :                 if (query->commandType == CMD_UTILITY ||
     391         [ +  + ]:        4644 :                     query->returningList == NIL)
     392                 :        4449 :                     return PORTAL_MULTI_QUERY;  /* no need to look further */
     393                 :             :             }
     394                 :             :         }
     395         [ +  - ]:       56207 :         else if (IsA(stmt, PlannedStmt))
     396                 :             :         {
     397                 :       56207 :             PlannedStmt *pstmt = (PlannedStmt *) stmt;
     398                 :             : 
     399         [ +  + ]:       56207 :             if (pstmt->canSetTag)
     400                 :             :             {
     401         [ -  + ]:       56051 :                 if (++nSetTag > 1)
     402                 :           0 :                     return PORTAL_MULTI_QUERY;  /* no need to look further */
     403         [ +  - ]:       56051 :                 if (pstmt->commandType == CMD_UTILITY ||
     404         [ +  + ]:       56051 :                     !pstmt->hasReturning)
     405                 :       53797 :                     return PORTAL_MULTI_QUERY;  /* no need to look further */
     406                 :             :             }
     407                 :             :         }
     408                 :             :         else
     409         [ #  # ]:           0 :             elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
     410                 :             :     }
     411         [ +  + ]:        2481 :     if (nSetTag == 1)
     412                 :        2449 :         return PORTAL_ONE_RETURNING;
     413                 :             : 
     414                 :             :     /* Else, it's the general case... */
     415                 :          32 :     return PORTAL_MULTI_QUERY;
     416                 :             : }
     417                 :             : 
     418                 :             : /*
     419                 :             :  * FetchPortalTargetList
     420                 :             :  *      Given a portal that returns tuples, extract the query targetlist.
     421                 :             :  *      Returns NIL if the portal doesn't have a determinable targetlist.
     422                 :             :  *
     423                 :             :  * Note: do not modify the result.
     424                 :             :  */
     425                 :             : List *
     426                 :      205932 : FetchPortalTargetList(Portal portal)
     427                 :             : {
     428                 :             :     /* no point in looking if we determined it doesn't return tuples */
     429         [ +  + ]:      205932 :     if (portal->strategy == PORTAL_MULTI_QUERY)
     430                 :          20 :         return NIL;
     431                 :             :     /* get the primary statement and find out what it returns */
     432                 :      205912 :     return FetchStatementTargetList((Node *) PortalGetPrimaryStmt(portal));
     433                 :             : }
     434                 :             : 
     435                 :             : /*
     436                 :             :  * FetchStatementTargetList
     437                 :             :  *      Given a statement that returns tuples, extract the query targetlist.
     438                 :             :  *      Returns NIL if the statement doesn't have a determinable targetlist.
     439                 :             :  *
     440                 :             :  * This can be applied to a Query or a PlannedStmt.
     441                 :             :  * That's more general than portals need, but plancache.c uses this too.
     442                 :             :  *
     443                 :             :  * Note: do not modify the result.
     444                 :             :  *
     445                 :             :  * XXX be careful to keep this in sync with UtilityReturnsTuples.
     446                 :             :  */
     447                 :             : List *
     448                 :      214500 : FetchStatementTargetList(Node *stmt)
     449                 :             : {
     450         [ -  + ]:      214500 :     if (stmt == NULL)
     451                 :           0 :         return NIL;
     452         [ +  + ]:      214500 :     if (IsA(stmt, Query))
     453                 :             :     {
     454                 :        8588 :         Query      *query = (Query *) stmt;
     455                 :             : 
     456         [ +  + ]:        8588 :         if (query->commandType == CMD_UTILITY)
     457                 :             :         {
     458                 :             :             /* transfer attention to utility statement */
     459                 :           9 :             stmt = query->utilityStmt;
     460                 :             :         }
     461                 :             :         else
     462                 :             :         {
     463         [ +  + ]:        8579 :             if (query->commandType == CMD_SELECT)
     464                 :        8569 :                 return query->targetList;
     465         [ +  - ]:          10 :             if (query->returningList)
     466                 :          10 :                 return query->returningList;
     467                 :           0 :             return NIL;
     468                 :             :         }
     469                 :             :     }
     470         [ +  + ]:      205921 :     if (IsA(stmt, PlannedStmt))
     471                 :             :     {
     472                 :      205912 :         PlannedStmt *pstmt = (PlannedStmt *) stmt;
     473                 :             : 
     474         [ +  + ]:      205912 :         if (pstmt->commandType == CMD_UTILITY)
     475                 :             :         {
     476                 :             :             /* transfer attention to utility statement */
     477                 :       24651 :             stmt = pstmt->utilityStmt;
     478                 :             :         }
     479                 :             :         else
     480                 :             :         {
     481         [ +  + ]:      181261 :             if (pstmt->commandType == CMD_SELECT)
     482                 :      179258 :                 return pstmt->planTree->targetlist;
     483         [ +  - ]:        2003 :             if (pstmt->hasReturning)
     484                 :        2003 :                 return pstmt->planTree->targetlist;
     485                 :           0 :             return NIL;
     486                 :             :         }
     487                 :             :     }
     488         [ +  + ]:       24660 :     if (IsA(stmt, FetchStmt))
     489                 :             :     {
     490                 :        3378 :         FetchStmt  *fstmt = (FetchStmt *) stmt;
     491                 :             :         Portal      subportal;
     492                 :             : 
     493                 :             :         Assert(!fstmt->ismove);
     494                 :        3378 :         subportal = GetPortalByName(fstmt->portalname);
     495         [ +  + ]:        3378 :         if (!PortalIsValid(subportal))
     496         [ +  - ]:           1 :             ereport(ERROR,
     497                 :             :                     (errcode(ERRCODE_UNDEFINED_CURSOR),
     498                 :             :                      errmsg("cursor \"%s\" does not exist",
     499                 :             :                             fstmt->portalname)));
     500                 :        3377 :         return FetchPortalTargetList(subportal);
     501                 :             :     }
     502         [ +  + ]:       21282 :     if (IsA(stmt, ExecuteStmt))
     503                 :             :     {
     504                 :        8516 :         ExecuteStmt *estmt = (ExecuteStmt *) stmt;
     505                 :             :         PreparedStatement *entry;
     506                 :             : 
     507                 :        8516 :         entry = FetchPreparedStatement(estmt->name, true);
     508                 :        8516 :         return FetchPreparedStatementTargetList(entry);
     509                 :             :     }
     510                 :       12766 :     return NIL;
     511                 :             : }
     512                 :             : 
     513                 :             : /*
     514                 :             :  * PortalStart
     515                 :             :  *      Prepare a portal for execution.
     516                 :             :  *
     517                 :             :  * Caller must already have created the portal, done PortalDefineQuery(),
     518                 :             :  * and adjusted portal options if needed.
     519                 :             :  *
     520                 :             :  * If parameters are needed by the query, they must be passed in "params"
     521                 :             :  * (caller is responsible for giving them appropriate lifetime).
     522                 :             :  *
     523                 :             :  * The caller can also provide an initial set of "eflags" to be passed to
     524                 :             :  * ExecutorStart (but note these can be modified internally, and they are
     525                 :             :  * currently only honored for PORTAL_ONE_SELECT portals).  Most callers
     526                 :             :  * should simply pass zero.
     527                 :             :  *
     528                 :             :  * The caller can optionally pass a snapshot to be used; pass InvalidSnapshot
     529                 :             :  * for the normal behavior of setting a new snapshot.  This parameter is
     530                 :             :  * presently ignored for non-PORTAL_ONE_SELECT portals (it's only intended
     531                 :             :  * to be used for cursors).
     532                 :             :  *
     533                 :             :  * On return, portal is ready to accept PortalRun() calls, and the result
     534                 :             :  * tupdesc (if any) is known.
     535                 :             :  */
     536                 :             : void
     537                 :      485267 : PortalStart(Portal portal, ParamListInfo params,
     538                 :             :             int eflags, Snapshot snapshot)
     539                 :             : {
     540                 :             :     Portal      saveActivePortal;
     541                 :             :     ResourceOwner saveResourceOwner;
     542                 :             :     MemoryContext savePortalContext;
     543                 :             :     MemoryContext oldContext;
     544                 :             :     QueryDesc  *queryDesc;
     545                 :             :     int         myeflags;
     546                 :             : 
     547                 :             :     Assert(PortalIsValid(portal));
     548                 :             :     Assert(portal->status == PORTAL_DEFINED);
     549                 :             : 
     550                 :             :     /*
     551                 :             :      * Set up global portal context pointers.
     552                 :             :      */
     553                 :      485267 :     saveActivePortal = ActivePortal;
     554                 :      485267 :     saveResourceOwner = CurrentResourceOwner;
     555                 :      485267 :     savePortalContext = PortalContext;
     556         [ +  + ]:      485267 :     PG_TRY();
     557                 :             :     {
     558                 :      485267 :         ActivePortal = portal;
     559         [ +  - ]:      485267 :         if (portal->resowner)
     560                 :      485267 :             CurrentResourceOwner = portal->resowner;
     561                 :      485267 :         PortalContext = portal->portalContext;
     562                 :             : 
     563                 :      485267 :         oldContext = MemoryContextSwitchTo(PortalContext);
     564                 :             : 
     565                 :             :         /* Must remember portal param list, if any */
     566                 :      485267 :         portal->portalParams = params;
     567                 :             : 
     568                 :             :         /*
     569                 :             :          * Determine the portal execution strategy
     570                 :             :          */
     571                 :      485267 :         portal->strategy = ChoosePortalStrategy(portal->stmts);
     572                 :             : 
     573                 :             :         /*
     574                 :             :          * Fire her up according to the strategy
     575                 :             :          */
     576   [ +  +  +  +  :      485267 :         switch (portal->strategy)
                      - ]
     577                 :             :         {
     578                 :      190584 :             case PORTAL_ONE_SELECT:
     579                 :             : 
     580                 :             :                 /* Must set snapshot before starting executor. */
     581         [ +  + ]:      190584 :                 if (snapshot)
     582                 :       14241 :                     PushActiveSnapshot(snapshot);
     583                 :             :                 else
     584                 :      176343 :                     PushActiveSnapshot(GetTransactionSnapshot());
     585                 :             : 
     586                 :             :                 /*
     587                 :             :                  * We could remember the snapshot in portal->portalSnapshot,
     588                 :             :                  * but presently there seems no need to, as this code path
     589                 :             :                  * cannot be used for non-atomic execution.  Hence there can't
     590                 :             :                  * be any commit/abort that might destroy the snapshot.  Since
     591                 :             :                  * we don't do that, there's also no need to force a
     592                 :             :                  * non-default nesting level for the snapshot.
     593                 :             :                  */
     594                 :             : 
     595                 :             :                 /*
     596                 :             :                  * Create QueryDesc in portal's context; for the moment, set
     597                 :             :                  * the destination to DestNone.
     598                 :             :                  */
     599                 :      190584 :                 queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
     600                 :             :                                             portal->sourceText,
     601                 :             :                                             GetActiveSnapshot(),
     602                 :             :                                             InvalidSnapshot,
     603                 :             :                                             None_Receiver,
     604                 :             :                                             params,
     605                 :             :                                             portal->queryEnv,
     606                 :             :                                             0);
     607                 :             : 
     608                 :             :                 /*
     609                 :             :                  * If it's a scrollable cursor, executor needs to support
     610                 :             :                  * REWIND and backwards scan, as well as whatever the caller
     611                 :             :                  * might've asked for.
     612                 :             :                  */
     613         [ +  + ]:      190584 :                 if (portal->cursorOptions & CURSOR_OPT_SCROLL)
     614                 :        2541 :                     myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
     615                 :             :                 else
     616                 :      188043 :                     myeflags = eflags;
     617                 :             : 
     618                 :             :                 /*
     619                 :             :                  * Call ExecutorStart to prepare the plan for execution
     620                 :             :                  */
     621                 :      190584 :                 ExecutorStart(queryDesc, myeflags);
     622                 :             : 
     623                 :             :                 /*
     624                 :             :                  * This tells PortalCleanup to shut down the executor
     625                 :             :                  */
     626                 :      190166 :                 portal->queryDesc = queryDesc;
     627                 :             : 
     628                 :             :                 /*
     629                 :             :                  * Remember tuple descriptor (computed by ExecutorStart)
     630                 :             :                  */
     631                 :      190166 :                 portal->tupDesc = queryDesc->tupDesc;
     632                 :             : 
     633                 :             :                 /*
     634                 :             :                  * Reset cursor position data to "start of query"
     635                 :             :                  */
     636                 :      190166 :                 portal->atStart = true;
     637                 :      190166 :                 portal->atEnd = false;   /* allow fetches */
     638                 :      190166 :                 portal->portalPos = 0;
     639                 :             : 
     640                 :      190166 :                 PopActiveSnapshot();
     641                 :      190166 :                 break;
     642                 :             : 
     643                 :        2343 :             case PORTAL_ONE_RETURNING:
     644                 :             :             case PORTAL_ONE_MOD_WITH:
     645                 :             : 
     646                 :             :                 /*
     647                 :             :                  * We don't start the executor until we are told to run the
     648                 :             :                  * portal.  We do need to set up the result tupdesc.
     649                 :             :                  */
     650                 :             :                 {
     651                 :             :                     PlannedStmt *pstmt;
     652                 :             : 
     653                 :        2343 :                     pstmt = PortalGetPrimaryStmt(portal);
     654                 :        2343 :                     portal->tupDesc =
     655                 :        2343 :                         ExecCleanTypeFromTL(pstmt->planTree->targetlist);
     656                 :             :                 }
     657                 :             : 
     658                 :             :                 /*
     659                 :             :                  * Reset cursor position data to "start of query"
     660                 :             :                  */
     661                 :        2343 :                 portal->atStart = true;
     662                 :        2343 :                 portal->atEnd = false;   /* allow fetches */
     663                 :        2343 :                 portal->portalPos = 0;
     664                 :        2343 :                 break;
     665                 :             : 
     666                 :       30356 :             case PORTAL_UTIL_SELECT:
     667                 :             : 
     668                 :             :                 /*
     669                 :             :                  * We don't set snapshot here, because PortalRunUtility will
     670                 :             :                  * take care of it if needed.
     671                 :             :                  */
     672                 :             :                 {
     673                 :       30356 :                     PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
     674                 :             : 
     675                 :             :                     Assert(pstmt->commandType == CMD_UTILITY);
     676                 :       30356 :                     portal->tupDesc = UtilityTupleDescriptor(pstmt->utilityStmt);
     677                 :             :                 }
     678                 :             : 
     679                 :             :                 /*
     680                 :             :                  * Reset cursor position data to "start of query"
     681                 :             :                  */
     682                 :       30338 :                 portal->atStart = true;
     683                 :       30338 :                 portal->atEnd = false;   /* allow fetches */
     684                 :       30338 :                 portal->portalPos = 0;
     685                 :       30338 :                 break;
     686                 :             : 
     687                 :      261984 :             case PORTAL_MULTI_QUERY:
     688                 :             :                 /* Need do nothing now */
     689                 :      261984 :                 portal->tupDesc = NULL;
     690                 :      261984 :                 break;
     691                 :             :         }
     692                 :             :     }
     693                 :         436 :     PG_CATCH();
     694                 :             :     {
     695                 :             :         /* Uncaught error while executing portal: mark it dead */
     696                 :         436 :         MarkPortalFailed(portal);
     697                 :             : 
     698                 :             :         /* Restore global vars and propagate error */
     699                 :         436 :         ActivePortal = saveActivePortal;
     700                 :         436 :         CurrentResourceOwner = saveResourceOwner;
     701                 :         436 :         PortalContext = savePortalContext;
     702                 :             : 
     703                 :         436 :         PG_RE_THROW();
     704                 :             :     }
     705         [ -  + ]:      484831 :     PG_END_TRY();
     706                 :             : 
     707                 :      484831 :     MemoryContextSwitchTo(oldContext);
     708                 :             : 
     709                 :      484831 :     ActivePortal = saveActivePortal;
     710                 :      484831 :     CurrentResourceOwner = saveResourceOwner;
     711                 :      484831 :     PortalContext = savePortalContext;
     712                 :             : 
     713                 :      484831 :     portal->status = PORTAL_READY;
     714                 :      484831 : }
     715                 :             : 
     716                 :             : /*
     717                 :             :  * PortalSetResultFormat
     718                 :             :  *      Select the format codes for a portal's output.
     719                 :             :  *
     720                 :             :  * This must be run after PortalStart for a portal that will be read by
     721                 :             :  * a DestRemote or DestRemoteExecute destination.  It is not presently needed
     722                 :             :  * for other destination types.
     723                 :             :  *
     724                 :             :  * formats[] is the client format request, as per Bind message conventions.
     725                 :             :  */
     726                 :             : void
     727                 :      465057 : PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
     728                 :             : {
     729                 :             :     int         natts;
     730                 :             :     int         i;
     731                 :             : 
     732                 :             :     /* Do nothing if portal won't return tuples */
     733         [ +  + ]:      465057 :     if (portal->tupDesc == NULL)
     734                 :      261913 :         return;
     735                 :      203144 :     natts = portal->tupDesc->natts;
     736                 :      203144 :     portal->formats = (int16 *)
     737                 :      203144 :         MemoryContextAlloc(portal->portalContext,
     738                 :             :                            natts * sizeof(int16));
     739         [ -  + ]:      203144 :     if (nFormats > 1)
     740                 :             :     {
     741                 :             :         /* format specified for each column */
     742         [ #  # ]:           0 :         if (nFormats != natts)
     743         [ #  # ]:           0 :             ereport(ERROR,
     744                 :             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
     745                 :             :                      errmsg("bind message has %d result formats but query has %d columns",
     746                 :             :                             nFormats, natts)));
     747                 :           0 :         memcpy(portal->formats, formats, natts * sizeof(int16));
     748                 :             :     }
     749         [ +  - ]:      203144 :     else if (nFormats > 0)
     750                 :             :     {
     751                 :             :         /* single format specified, use for all columns */
     752                 :      203144 :         int16       format1 = formats[0];
     753                 :             : 
     754         [ +  + ]:      821158 :         for (i = 0; i < natts; i++)
     755                 :      618014 :             portal->formats[i] = format1;
     756                 :             :     }
     757                 :             :     else
     758                 :             :     {
     759                 :             :         /* use default format for all columns */
     760         [ #  # ]:           0 :         for (i = 0; i < natts; i++)
     761                 :           0 :             portal->formats[i] = 0;
     762                 :             :     }
     763                 :             : }
     764                 :             : 
     765                 :             : /*
     766                 :             :  * PortalRun
     767                 :             :  *      Run a portal's query or queries.
     768                 :             :  *
     769                 :             :  * count <= 0 is interpreted as a no-op: the destination gets started up
     770                 :             :  * and shut down, but nothing else happens.  Also, count == FETCH_ALL is
     771                 :             :  * interpreted as "all rows".  Note that count is ignored in multi-query
     772                 :             :  * situations, where we always run the portal to completion.
     773                 :             :  *
     774                 :             :  * isTopLevel: true if query is being executed at backend "top level"
     775                 :             :  * (that is, directly from a client command message)
     776                 :             :  *
     777                 :             :  * dest: where to send output of primary (canSetTag) query
     778                 :             :  *
     779                 :             :  * altdest: where to send output of non-primary queries
     780                 :             :  *
     781                 :             :  * qc: where to store command completion status data.
     782                 :             :  *      May be NULL if caller doesn't want status data.
     783                 :             :  *
     784                 :             :  * Returns true if the portal's execution is complete, false if it was
     785                 :             :  * suspended due to exhaustion of the count parameter.
     786                 :             :  */
     787                 :             : bool
     788                 :      473703 : PortalRun(Portal portal, long count, bool isTopLevel,
     789                 :             :           DestReceiver *dest, DestReceiver *altdest,
     790                 :             :           QueryCompletion *qc)
     791                 :             : {
     792                 :             :     bool        result;
     793                 :             :     uint64      nprocessed;
     794                 :             :     ResourceOwner saveTopTransactionResourceOwner;
     795                 :             :     MemoryContext saveTopTransactionContext;
     796                 :             :     Portal      saveActivePortal;
     797                 :             :     ResourceOwner saveResourceOwner;
     798                 :             :     MemoryContext savePortalContext;
     799                 :             :     MemoryContext saveMemoryContext;
     800                 :             : 
     801                 :             :     Assert(PortalIsValid(portal));
     802                 :             : 
     803                 :             :     TRACE_POSTGRESQL_QUERY_EXECUTE_START();
     804                 :             : 
     805                 :             :     /* Initialize empty completion data */
     806         [ +  - ]:      473703 :     if (qc)
     807                 :      473703 :         InitializeQueryCompletion(qc);
     808                 :             : 
     809   [ -  +  -  - ]:      473703 :     if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
     810                 :             :     {
     811         [ #  # ]:           0 :         elog(DEBUG3, "PortalRun");
     812                 :             :         /* PORTAL_MULTI_QUERY logs its own stats per query */
     813                 :           0 :         ResetUsage();
     814                 :             :     }
     815                 :             : 
     816                 :             :     /*
     817                 :             :      * Check for improper portal use, and mark portal active.
     818                 :             :      */
     819                 :      473703 :     MarkPortalActive(portal);
     820                 :             : 
     821                 :             :     /*
     822                 :             :      * Set up global portal context pointers.
     823                 :             :      *
     824                 :             :      * We have to play a special game here to support utility commands like
     825                 :             :      * VACUUM and CLUSTER, which internally start and commit transactions.
     826                 :             :      * When we are called to execute such a command, CurrentResourceOwner will
     827                 :             :      * be pointing to the TopTransactionResourceOwner --- which will be
     828                 :             :      * destroyed and replaced in the course of the internal commit and
     829                 :             :      * restart.  So we need to be prepared to restore it as pointing to the
     830                 :             :      * exit-time TopTransactionResourceOwner.  (Ain't that ugly?  This idea of
     831                 :             :      * internally starting whole new transactions is not good.)
     832                 :             :      * CurrentMemoryContext has a similar problem, but the other pointers we
     833                 :             :      * save here will be NULL or pointing to longer-lived objects.
     834                 :             :      */
     835                 :      473703 :     saveTopTransactionResourceOwner = TopTransactionResourceOwner;
     836                 :      473703 :     saveTopTransactionContext = TopTransactionContext;
     837                 :      473703 :     saveActivePortal = ActivePortal;
     838                 :      473703 :     saveResourceOwner = CurrentResourceOwner;
     839                 :      473703 :     savePortalContext = PortalContext;
     840                 :      473703 :     saveMemoryContext = CurrentMemoryContext;
     841         [ +  + ]:      473703 :     PG_TRY();
     842                 :             :     {
     843                 :      473703 :         ActivePortal = portal;
     844         [ +  - ]:      473703 :         if (portal->resowner)
     845                 :      473703 :             CurrentResourceOwner = portal->resowner;
     846                 :      473703 :         PortalContext = portal->portalContext;
     847                 :             : 
     848                 :      473703 :         MemoryContextSwitchTo(PortalContext);
     849                 :             : 
     850      [ +  +  - ]:      473703 :         switch (portal->strategy)
     851                 :             :         {
     852                 :      211719 :             case PORTAL_ONE_SELECT:
     853                 :             :             case PORTAL_ONE_RETURNING:
     854                 :             :             case PORTAL_ONE_MOD_WITH:
     855                 :             :             case PORTAL_UTIL_SELECT:
     856                 :             : 
     857                 :             :                 /*
     858                 :             :                  * If we have not yet run the command, do so, storing its
     859                 :             :                  * results in the portal's tuplestore.  But we don't do that
     860                 :             :                  * for the PORTAL_ONE_SELECT case.
     861                 :             :                  */
     862   [ +  +  +  - ]:      211719 :                 if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
     863                 :       27229 :                     FillPortalStore(portal, isTopLevel);
     864                 :             : 
     865                 :             :                 /*
     866                 :             :                  * Now fetch desired portion of results.
     867                 :             :                  */
     868                 :      211233 :                 nprocessed = PortalRunSelect(portal, true, count, dest);
     869                 :             : 
     870                 :             :                 /*
     871                 :             :                  * If the portal result contains a command tag and the caller
     872                 :             :                  * gave us a pointer to store it, copy it and update the
     873                 :             :                  * rowcount.
     874                 :             :                  */
     875   [ +  -  +  - ]:      205781 :                 if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
     876                 :             :                 {
     877                 :      205781 :                     CopyQueryCompletion(qc, &portal->qc);
     878                 :      205781 :                     qc->nprocessed = nprocessed;
     879                 :             :                 }
     880                 :             : 
     881                 :             :                 /* Mark portal not active */
     882                 :      205781 :                 portal->status = PORTAL_READY;
     883                 :             : 
     884                 :             :                 /*
     885                 :             :                  * Since it's a forward fetch, say DONE iff atEnd is now true.
     886                 :             :                  */
     887                 :      205781 :                 result = portal->atEnd;
     888                 :      205781 :                 break;
     889                 :             : 
     890                 :      261984 :             case PORTAL_MULTI_QUERY:
     891                 :      261984 :                 PortalRunMulti(portal, isTopLevel, false,
     892                 :             :                                dest, altdest, qc);
     893                 :             : 
     894                 :             :                 /* Prevent portal's commands from being re-executed */
     895                 :      246947 :                 MarkPortalDone(portal);
     896                 :             : 
     897                 :             :                 /* Always complete at end of RunMulti */
     898                 :      246947 :                 result = true;
     899                 :      246947 :                 break;
     900                 :             : 
     901                 :           0 :             default:
     902         [ #  # ]:           0 :                 elog(ERROR, "unrecognized portal strategy: %d",
     903                 :             :                      (int) portal->strategy);
     904                 :             :                 result = false; /* keep compiler quiet */
     905                 :             :                 break;
     906                 :             :         }
     907                 :             :     }
     908                 :       20970 :     PG_CATCH();
     909                 :             :     {
     910                 :             :         /* Uncaught error while executing portal: mark it dead */
     911                 :       20970 :         MarkPortalFailed(portal);
     912                 :             : 
     913                 :             :         /* Restore global vars and propagate error */
     914         [ +  + ]:       20970 :         if (saveMemoryContext == saveTopTransactionContext)
     915                 :       20633 :             MemoryContextSwitchTo(TopTransactionContext);
     916                 :             :         else
     917                 :         337 :             MemoryContextSwitchTo(saveMemoryContext);
     918                 :       20970 :         ActivePortal = saveActivePortal;
     919         [ +  + ]:       20970 :         if (saveResourceOwner == saveTopTransactionResourceOwner)
     920                 :       20686 :             CurrentResourceOwner = TopTransactionResourceOwner;
     921                 :             :         else
     922                 :         284 :             CurrentResourceOwner = saveResourceOwner;
     923                 :       20970 :         PortalContext = savePortalContext;
     924                 :             : 
     925                 :       20970 :         PG_RE_THROW();
     926                 :             :     }
     927         [ -  + ]:      452728 :     PG_END_TRY();
     928                 :             : 
     929         [ +  + ]:      452728 :     if (saveMemoryContext == saveTopTransactionContext)
     930                 :      428300 :         MemoryContextSwitchTo(TopTransactionContext);
     931                 :             :     else
     932                 :       24428 :         MemoryContextSwitchTo(saveMemoryContext);
     933                 :      452728 :     ActivePortal = saveActivePortal;
     934         [ +  + ]:      452728 :     if (saveResourceOwner == saveTopTransactionResourceOwner)
     935                 :      439867 :         CurrentResourceOwner = TopTransactionResourceOwner;
     936                 :             :     else
     937                 :       12861 :         CurrentResourceOwner = saveResourceOwner;
     938                 :      452728 :     PortalContext = savePortalContext;
     939                 :             : 
     940   [ -  +  -  - ]:      452728 :     if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
     941                 :           0 :         ShowUsage("EXECUTOR STATISTICS");
     942                 :             : 
     943                 :             :     TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
     944                 :             : 
     945                 :      452728 :     return result;
     946                 :             : }
     947                 :             : 
     948                 :             : /*
     949                 :             :  * PortalRunSelect
     950                 :             :  *      Execute a portal's query in PORTAL_ONE_SELECT mode, and also
     951                 :             :  *      when fetching from a completed holdStore in PORTAL_ONE_RETURNING,
     952                 :             :  *      PORTAL_ONE_MOD_WITH, and PORTAL_UTIL_SELECT cases.
     953                 :             :  *
     954                 :             :  * This handles simple N-rows-forward-or-backward cases.  For more complex
     955                 :             :  * nonsequential access to a portal, see PortalRunFetch.
     956                 :             :  *
     957                 :             :  * count <= 0 is interpreted as a no-op: the destination gets started up
     958                 :             :  * and shut down, but nothing else happens.  Also, count == FETCH_ALL is
     959                 :             :  * interpreted as "all rows".  (cf FetchStmt.howMany)
     960                 :             :  *
     961                 :             :  * Caller must already have validated the Portal and done appropriate
     962                 :             :  * setup (cf. PortalRun).
     963                 :             :  *
     964                 :             :  * Returns number of rows processed (suitable for use in result tag)
     965                 :             :  */
     966                 :             : static uint64
     967                 :      245773 : PortalRunSelect(Portal portal,
     968                 :             :                 bool forward,
     969                 :             :                 long count,
     970                 :             :                 DestReceiver *dest)
     971                 :             : {
     972                 :             :     QueryDesc  *queryDesc;
     973                 :             :     ScanDirection direction;
     974                 :             :     uint64      nprocessed;
     975                 :             : 
     976                 :             :     /*
     977                 :             :      * NB: queryDesc will be NULL if we are fetching from a held cursor or a
     978                 :             :      * completed utility query; can't use it in that path.
     979                 :             :      */
     980                 :      245773 :     queryDesc = portal->queryDesc;
     981                 :             : 
     982                 :             :     /* Caller messed up if we have neither a ready query nor held data. */
     983                 :             :     Assert(queryDesc || portal->holdStore);
     984                 :             : 
     985                 :             :     /*
     986                 :             :      * Force the queryDesc destination to the right thing.  This supports
     987                 :             :      * MOVE, for example, which will pass in dest = DestNone.  This is okay to
     988                 :             :      * change as long as we do it on every fetch.  (The Executor must not
     989                 :             :      * assume that dest never changes.)
     990                 :             :      */
     991         [ +  + ]:      245773 :     if (queryDesc)
     992                 :      197448 :         queryDesc->dest = dest;
     993                 :             : 
     994                 :             :     /*
     995                 :             :      * Determine which direction to go in, and check to see if we're already
     996                 :             :      * at the end of the available tuples in that direction.  If so, set the
     997                 :             :      * direction to NoMovement to avoid trying to fetch any tuples.  (This
     998                 :             :      * check exists because not all plan node types are robust about being
     999                 :             :      * called again if they've already returned NULL once.)  Then call the
    1000                 :             :      * executor (we must not skip this, because the destination needs to see a
    1001                 :             :      * setup and shutdown even if no tuples are available).  Finally, update
    1002                 :             :      * the portal position state depending on the number of tuples that were
    1003                 :             :      * retrieved.
    1004                 :             :      */
    1005         [ +  + ]:      245773 :     if (forward)
    1006                 :             :     {
    1007   [ +  +  +  + ]:      245348 :         if (portal->atEnd || count <= 0)
    1008                 :             :         {
    1009                 :        2531 :             direction = NoMovementScanDirection;
    1010                 :        2531 :             count = 0;          /* don't pass negative count to executor */
    1011                 :             :         }
    1012                 :             :         else
    1013                 :      242817 :             direction = ForwardScanDirection;
    1014                 :             : 
    1015                 :             :         /* In the executor, zero count processes all rows */
    1016         [ +  + ]:      245348 :         if (count == FETCH_ALL)
    1017                 :      211461 :             count = 0;
    1018                 :             : 
    1019         [ +  + ]:      245348 :         if (portal->holdStore)
    1020                 :       48313 :             nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
    1021                 :             :         else
    1022                 :             :         {
    1023                 :      197035 :             PushActiveSnapshot(queryDesc->snapshot);
    1024                 :      197035 :             ExecutorRun(queryDesc, direction, (uint64) count);
    1025                 :      191634 :             nprocessed = queryDesc->estate->es_processed;
    1026                 :      191634 :             PopActiveSnapshot();
    1027                 :             :         }
    1028                 :             : 
    1029         [ +  + ]:      239856 :         if (!ScanDirectionIsNoMovement(direction))
    1030                 :             :         {
    1031         [ +  + ]:      237325 :             if (nprocessed > 0)
    1032                 :      198305 :                 portal->atStart = false; /* OK to go backward now */
    1033   [ +  +  +  + ]:      237325 :             if (count == 0 || nprocessed < (uint64) count)
    1034                 :      215320 :                 portal->atEnd = true;    /* we retrieved 'em all */
    1035                 :      237325 :             portal->portalPos += nprocessed;
    1036                 :             :         }
    1037                 :             :     }
    1038                 :             :     else
    1039                 :             :     {
    1040         [ +  + ]:         425 :         if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
    1041         [ +  - ]:          16 :             ereport(ERROR,
    1042                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1043                 :             :                      errmsg("cursor can only scan forward"),
    1044                 :             :                      errhint("Declare it with SCROLL option to enable backward scan.")));
    1045                 :             : 
    1046   [ +  +  -  + ]:         409 :         if (portal->atStart || count <= 0)
    1047                 :             :         {
    1048                 :          48 :             direction = NoMovementScanDirection;
    1049                 :          48 :             count = 0;          /* don't pass negative count to executor */
    1050                 :             :         }
    1051                 :             :         else
    1052                 :         361 :             direction = BackwardScanDirection;
    1053                 :             : 
    1054                 :             :         /* In the executor, zero count processes all rows */
    1055         [ +  + ]:         409 :         if (count == FETCH_ALL)
    1056                 :          42 :             count = 0;
    1057                 :             : 
    1058         [ +  + ]:         409 :         if (portal->holdStore)
    1059                 :           8 :             nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
    1060                 :             :         else
    1061                 :             :         {
    1062                 :         401 :             PushActiveSnapshot(queryDesc->snapshot);
    1063                 :         401 :             ExecutorRun(queryDesc, direction, (uint64) count);
    1064                 :         401 :             nprocessed = queryDesc->estate->es_processed;
    1065                 :         401 :             PopActiveSnapshot();
    1066                 :             :         }
    1067                 :             : 
    1068         [ +  + ]:         409 :         if (!ScanDirectionIsNoMovement(direction))
    1069                 :             :         {
    1070   [ +  +  +  + ]:         361 :             if (nprocessed > 0 && portal->atEnd)
    1071                 :             :             {
    1072                 :         111 :                 portal->atEnd = false;   /* OK to go forward now */
    1073                 :         111 :                 portal->portalPos++; /* adjust for endpoint case */
    1074                 :             :             }
    1075   [ +  +  +  + ]:         361 :             if (count == 0 || nprocessed < (uint64) count)
    1076                 :             :             {
    1077                 :         126 :                 portal->atStart = true; /* we retrieved 'em all */
    1078                 :         126 :                 portal->portalPos = 0;
    1079                 :             :             }
    1080                 :             :             else
    1081                 :             :             {
    1082                 :         235 :                 portal->portalPos -= nprocessed;
    1083                 :             :             }
    1084                 :             :         }
    1085                 :             :     }
    1086                 :             : 
    1087                 :      240265 :     return nprocessed;
    1088                 :             : }
    1089                 :             : 
    1090                 :             : /*
    1091                 :             :  * FillPortalStore
    1092                 :             :  *      Run the query and load result tuples into the portal's tuple store.
    1093                 :             :  *
    1094                 :             :  * This is used for PORTAL_ONE_RETURNING, PORTAL_ONE_MOD_WITH, and
    1095                 :             :  * PORTAL_UTIL_SELECT cases only.
    1096                 :             :  */
    1097                 :             : static void
    1098                 :       32681 : FillPortalStore(Portal portal, bool isTopLevel)
    1099                 :             : {
    1100                 :             :     DestReceiver *treceiver;
    1101                 :             :     QueryCompletion qc;
    1102                 :             : 
    1103                 :       32681 :     InitializeQueryCompletion(&qc);
    1104                 :       32681 :     PortalCreateHoldStore(portal);
    1105                 :       32681 :     treceiver = CreateDestReceiver(DestTuplestore);
    1106                 :       32681 :     SetTuplestoreDestReceiverParams(treceiver,
    1107                 :             :                                     portal->holdStore,
    1108                 :             :                                     portal->holdContext,
    1109                 :             :                                     false,
    1110                 :             :                                     portal->tupDesc,
    1111                 :             :                                     gettext_noop("query result type does not match portal result type"));
    1112                 :             : 
    1113      [ +  +  - ]:       32681 :     switch (portal->strategy)
    1114                 :             :     {
    1115                 :        2343 :         case PORTAL_ONE_RETURNING:
    1116                 :             :         case PORTAL_ONE_MOD_WITH:
    1117                 :             : 
    1118                 :             :             /*
    1119                 :             :              * Run the portal to completion just as for the default
    1120                 :             :              * PORTAL_MULTI_QUERY case, but send the primary query's output to
    1121                 :             :              * the tuplestore.  Auxiliary query outputs are discarded. Set the
    1122                 :             :              * portal's holdSnapshot to the snapshot used (or a copy of it).
    1123                 :             :              */
    1124                 :        2343 :             PortalRunMulti(portal, isTopLevel, true,
    1125                 :             :                            treceiver, None_Receiver, &qc);
    1126                 :        2093 :             break;
    1127                 :             : 
    1128                 :       30338 :         case PORTAL_UTIL_SELECT:
    1129                 :       30338 :             PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
    1130                 :             :                              isTopLevel, true, treceiver, &qc);
    1131                 :       30098 :             break;
    1132                 :             : 
    1133                 :           0 :         default:
    1134         [ #  # ]:           0 :             elog(ERROR, "unsupported portal strategy: %d",
    1135                 :             :                  (int) portal->strategy);
    1136                 :             :             break;
    1137                 :             :     }
    1138                 :             : 
    1139                 :             :     /* Override portal completion data with actual command results */
    1140         [ +  + ]:       32191 :     if (qc.commandTag != CMDTAG_UNKNOWN)
    1141                 :       13982 :         CopyQueryCompletion(&portal->qc, &qc);
    1142                 :             : 
    1143                 :       32191 :     treceiver->rDestroy(treceiver);
    1144                 :       32191 : }
    1145                 :             : 
    1146                 :             : /*
    1147                 :             :  * RunFromStore
    1148                 :             :  *      Fetch tuples from the portal's tuple store.
    1149                 :             :  *
    1150                 :             :  * Calling conventions are similar to ExecutorRun, except that we
    1151                 :             :  * do not depend on having a queryDesc or estate.  Therefore we return the
    1152                 :             :  * number of tuples processed as the result, not in estate->es_processed.
    1153                 :             :  *
    1154                 :             :  * One difference from ExecutorRun is that the destination receiver functions
    1155                 :             :  * are run in the caller's memory context (since we have no estate).  Watch
    1156                 :             :  * out for memory leaks.
    1157                 :             :  */
    1158                 :             : static uint64
    1159                 :       48321 : RunFromStore(Portal portal, ScanDirection direction, uint64 count,
    1160                 :             :              DestReceiver *dest)
    1161                 :             : {
    1162                 :       48321 :     uint64      current_tuple_count = 0;
    1163                 :             :     TupleTableSlot *slot;
    1164                 :             : 
    1165                 :       48321 :     slot = MakeSingleTupleTableSlot(portal->tupDesc, &TTSOpsMinimalTuple);
    1166                 :             : 
    1167                 :       48321 :     dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
    1168                 :             : 
    1169         [ +  + ]:       48321 :     if (ScanDirectionIsNoMovement(direction))
    1170                 :             :     {
    1171                 :             :         /* do nothing except start/stop the destination */
    1172                 :             :     }
    1173                 :             :     else
    1174                 :             :     {
    1175                 :       46555 :         bool        forward = ScanDirectionIsForward(direction);
    1176                 :             : 
    1177                 :             :         for (;;)
    1178                 :      272479 :         {
    1179                 :             :             MemoryContext oldcontext;
    1180                 :             :             bool        ok;
    1181                 :             : 
    1182                 :      319034 :             oldcontext = MemoryContextSwitchTo(portal->holdContext);
    1183                 :             : 
    1184                 :      319034 :             ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
    1185                 :             :                                          slot);
    1186                 :             : 
    1187                 :      319034 :             MemoryContextSwitchTo(oldcontext);
    1188                 :             : 
    1189         [ +  + ]:      319034 :             if (!ok)
    1190                 :       32132 :                 break;
    1191                 :             : 
    1192                 :             :             /*
    1193                 :             :              * If we are not able to send the tuple, we assume the destination
    1194                 :             :              * has closed and no more tuples can be sent. If that's the case,
    1195                 :             :              * end the loop.
    1196                 :             :              */
    1197         [ -  + ]:      286902 :             if (!dest->receiveSlot(slot, dest))
    1198                 :           0 :                 break;
    1199                 :             : 
    1200                 :      286811 :             ExecClearTuple(slot);
    1201                 :             : 
    1202                 :             :             /*
    1203                 :             :              * check our tuple count.. if we've processed the proper number
    1204                 :             :              * then quit, else loop again and process more tuples. Zero count
    1205                 :             :              * means no limit.
    1206                 :             :              */
    1207                 :      286811 :             current_tuple_count++;
    1208   [ +  +  +  + ]:      286811 :             if (count && count == current_tuple_count)
    1209                 :       14332 :                 break;
    1210                 :             :         }
    1211                 :             :     }
    1212                 :             : 
    1213                 :       48230 :     dest->rShutdown(dest);
    1214                 :             : 
    1215                 :       48230 :     ExecDropSingleTupleTableSlot(slot);
    1216                 :             : 
    1217                 :       48230 :     return current_tuple_count;
    1218                 :             : }
    1219                 :             : 
    1220                 :             : /*
    1221                 :             :  * PortalRunUtility
    1222                 :             :  *      Execute a utility statement inside a portal.
    1223                 :             :  */
    1224                 :             : static void
    1225                 :      238497 : PortalRunUtility(Portal portal, PlannedStmt *pstmt,
    1226                 :             :                  bool isTopLevel, bool setHoldSnapshot,
    1227                 :             :                  DestReceiver *dest, QueryCompletion *qc)
    1228                 :             : {
    1229                 :             :     /*
    1230                 :             :      * Set snapshot if utility stmt needs one.
    1231                 :             :      */
    1232         [ +  + ]:      238497 :     if (PlannedStmtRequiresSnapshot(pstmt))
    1233                 :             :     {
    1234                 :      186581 :         Snapshot    snapshot = GetTransactionSnapshot();
    1235                 :             : 
    1236                 :             :         /* If told to, register the snapshot we're using and save in portal */
    1237         [ +  + ]:      186581 :         if (setHoldSnapshot)
    1238                 :             :         {
    1239                 :       26051 :             snapshot = RegisterSnapshot(snapshot);
    1240                 :       26051 :             portal->holdSnapshot = snapshot;
    1241                 :             :         }
    1242                 :             : 
    1243                 :             :         /*
    1244                 :             :          * In any case, make the snapshot active and remember it in portal.
    1245                 :             :          * Because the portal now references the snapshot, we must tell
    1246                 :             :          * snapmgr.c that the snapshot belongs to the portal's transaction
    1247                 :             :          * level, else we risk portalSnapshot becoming a dangling pointer.
    1248                 :             :          */
    1249                 :      186581 :         PushActiveSnapshotWithLevel(snapshot, portal->createLevel);
    1250                 :             :         /* PushActiveSnapshotWithLevel might have copied the snapshot */
    1251                 :      186581 :         portal->portalSnapshot = GetActiveSnapshot();
    1252                 :             :     }
    1253                 :             :     else
    1254                 :       51916 :         portal->portalSnapshot = NULL;
    1255                 :             : 
    1256                 :      238497 :     ProcessUtility(pstmt,
    1257                 :             :                    portal->sourceText,
    1258                 :      238497 :                    (portal->cplan != NULL), /* protect tree if in plancache */
    1259                 :      238497 :                    isTopLevel ? PROCESS_UTILITY_TOPLEVEL : PROCESS_UTILITY_QUERY,
    1260                 :             :                    portal->portalParams,
    1261                 :             :                    portal->queryEnv,
    1262                 :             :                    dest,
    1263                 :             :                    qc);
    1264                 :             : 
    1265                 :             :     /* Some utility statements may change context on us */
    1266                 :      226790 :     MemoryContextSwitchTo(portal->portalContext);
    1267                 :             : 
    1268                 :             :     /*
    1269                 :             :      * Some utility commands (e.g., VACUUM, WAIT FOR) pop the ActiveSnapshot
    1270                 :             :      * stack from under us, so don't complain if it's now empty.  Otherwise,
    1271                 :             :      * our snapshot should be the top one; pop it.  Note that this could be a
    1272                 :             :      * different snapshot from the one we made above; see
    1273                 :             :      * EnsurePortalSnapshotExists.
    1274                 :             :      */
    1275   [ +  +  +  - ]:      226790 :     if (portal->portalSnapshot != NULL && ActiveSnapshotSet())
    1276                 :             :     {
    1277                 :             :         Assert(portal->portalSnapshot == GetActiveSnapshot());
    1278                 :      168398 :         PopActiveSnapshot();
    1279                 :             :     }
    1280                 :      226790 :     portal->portalSnapshot = NULL;
    1281                 :      226790 : }
    1282                 :             : 
    1283                 :             : /*
    1284                 :             :  * PortalRunMulti
    1285                 :             :  *      Execute a portal's queries in the general case (multi queries
    1286                 :             :  *      or non-SELECT-like queries)
    1287                 :             :  */
    1288                 :             : static void
    1289                 :      264327 : PortalRunMulti(Portal portal,
    1290                 :             :                bool isTopLevel, bool setHoldSnapshot,
    1291                 :             :                DestReceiver *dest, DestReceiver *altdest,
    1292                 :             :                QueryCompletion *qc)
    1293                 :             : {
    1294                 :      264327 :     bool        active_snapshot_set = false;
    1295                 :             :     ListCell   *stmtlist_item;
    1296                 :             : 
    1297                 :             :     /*
    1298                 :             :      * If the destination is DestRemoteExecute, change to DestNone.  The
    1299                 :             :      * reason is that the client won't be expecting any tuples, and indeed has
    1300                 :             :      * no way to know what they are, since there is no provision for Describe
    1301                 :             :      * to send a RowDescription message when this portal execution strategy is
    1302                 :             :      * in effect.  This presently will only affect SELECT commands added to
    1303                 :             :      * non-SELECT queries by rewrite rules: such commands will be executed,
    1304                 :             :      * but the results will be discarded unless you use "simple Query"
    1305                 :             :      * protocol.
    1306                 :             :      */
    1307         [ +  + ]:      264327 :     if (dest->mydest == DestRemoteExecute)
    1308                 :        6468 :         dest = None_Receiver;
    1309         [ +  + ]:      264327 :     if (altdest->mydest == DestRemoteExecute)
    1310                 :        6468 :         altdest = None_Receiver;
    1311                 :             : 
    1312                 :             :     /*
    1313                 :             :      * Loop to handle the individual queries generated from a single parsetree
    1314                 :             :      * by analysis and rewrite.
    1315                 :             :      */
    1316   [ +  -  +  +  :      513783 :     foreach(stmtlist_item, portal->stmts)
                   +  + ]
    1317                 :             :     {
    1318                 :      264743 :         PlannedStmt *pstmt = lfirst_node(PlannedStmt, stmtlist_item);
    1319                 :             : 
    1320                 :             :         /*
    1321                 :             :          * If we got a cancel signal in prior command, quit
    1322                 :             :          */
    1323         [ -  + ]:      264743 :         CHECK_FOR_INTERRUPTS();
    1324                 :             : 
    1325         [ +  + ]:      264743 :         if (pstmt->utilityStmt == NULL)
    1326                 :             :         {
    1327                 :             :             /*
    1328                 :             :              * process a plannable query.
    1329                 :             :              */
    1330                 :             :             TRACE_POSTGRESQL_QUERY_EXECUTE_START();
    1331                 :             : 
    1332         [ -  + ]:       56584 :             if (log_executor_stats)
    1333                 :           0 :                 ResetUsage();
    1334                 :             : 
    1335                 :             :             /*
    1336                 :             :              * Must always have a snapshot for plannable queries.  First time
    1337                 :             :              * through, take a new snapshot; for subsequent queries in the
    1338                 :             :              * same portal, just update the snapshot's copy of the command
    1339                 :             :              * counter.
    1340                 :             :              */
    1341         [ +  + ]:       56584 :             if (!active_snapshot_set)
    1342                 :             :             {
    1343                 :       56168 :                 Snapshot    snapshot = GetTransactionSnapshot();
    1344                 :             : 
    1345                 :             :                 /* If told to, register the snapshot and save in portal */
    1346         [ +  + ]:       56168 :                 if (setHoldSnapshot)
    1347                 :             :                 {
    1348                 :        2343 :                     snapshot = RegisterSnapshot(snapshot);
    1349                 :        2343 :                     portal->holdSnapshot = snapshot;
    1350                 :             :                 }
    1351                 :             : 
    1352                 :             :                 /*
    1353                 :             :                  * We can't have the holdSnapshot also be the active one,
    1354                 :             :                  * because UpdateActiveSnapshotCommandId would complain.  So
    1355                 :             :                  * force an extra snapshot copy.  Plain PushActiveSnapshot
    1356                 :             :                  * would have copied the transaction snapshot anyway, so this
    1357                 :             :                  * only adds a copy step when setHoldSnapshot is true.  (It's
    1358                 :             :                  * okay for the command ID of the active snapshot to diverge
    1359                 :             :                  * from what holdSnapshot has.)
    1360                 :             :                  */
    1361                 :       56168 :                 PushCopiedSnapshot(snapshot);
    1362                 :             : 
    1363                 :             :                 /*
    1364                 :             :                  * As for PORTAL_ONE_SELECT portals, it does not seem
    1365                 :             :                  * necessary to maintain portal->portalSnapshot here.
    1366                 :             :                  */
    1367                 :             : 
    1368                 :       56168 :                 active_snapshot_set = true;
    1369                 :             :             }
    1370                 :             :             else
    1371                 :         416 :                 UpdateActiveSnapshotCommandId();
    1372                 :             : 
    1373         [ +  + ]:       56584 :             if (pstmt->canSetTag)
    1374                 :             :             {
    1375                 :             :                 /* statement can set tag string */
    1376                 :       56140 :                 ProcessQuery(pstmt,
    1377                 :             :                              portal->sourceText,
    1378                 :             :                              portal->portalParams,
    1379                 :             :                              portal->queryEnv,
    1380                 :             :                              dest, qc);
    1381                 :             :             }
    1382                 :             :             else
    1383                 :             :             {
    1384                 :             :                 /* stmt added by rewrite cannot set tag */
    1385                 :         444 :                 ProcessQuery(pstmt,
    1386                 :             :                              portal->sourceText,
    1387                 :             :                              portal->portalParams,
    1388                 :             :                              portal->queryEnv,
    1389                 :             :                              altdest, NULL);
    1390                 :             :             }
    1391                 :             : 
    1392         [ -  + ]:       52764 :             if (log_executor_stats)
    1393                 :           0 :                 ShowUsage("EXECUTOR STATISTICS");
    1394                 :             : 
    1395                 :             :             TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
    1396                 :             :         }
    1397                 :             :         else
    1398                 :             :         {
    1399                 :             :             /*
    1400                 :             :              * process utility functions (create, destroy, etc..)
    1401                 :             :              *
    1402                 :             :              * We must not set a snapshot here for utility commands (if one is
    1403                 :             :              * needed, PortalRunUtility will do it).  If a utility command is
    1404                 :             :              * alone in a portal then everything's fine.  The only case where
    1405                 :             :              * a utility command can be part of a longer list is that rules
    1406                 :             :              * are allowed to include NotifyStmt.  NotifyStmt doesn't care
    1407                 :             :              * whether it has a snapshot or not, so we just leave the current
    1408                 :             :              * snapshot alone if we have one.
    1409                 :             :              */
    1410         [ +  - ]:      208159 :             if (pstmt->canSetTag)
    1411                 :             :             {
    1412                 :             :                 Assert(!active_snapshot_set);
    1413                 :             :                 /* statement can set tag string */
    1414                 :      208159 :                 PortalRunUtility(portal, pstmt, isTopLevel, false,
    1415                 :             :                                  dest, qc);
    1416                 :             :             }
    1417                 :             :             else
    1418                 :             :             {
    1419                 :             :                 Assert(IsA(pstmt->utilityStmt, NotifyStmt));
    1420                 :             :                 /* stmt added by rewrite cannot set tag */
    1421                 :           0 :                 PortalRunUtility(portal, pstmt, isTopLevel, false,
    1422                 :             :                                  altdest, NULL);
    1423                 :             :             }
    1424                 :             :         }
    1425                 :             : 
    1426                 :             :         /*
    1427                 :             :          * Clear subsidiary contexts to recover temporary memory.
    1428                 :             :          */
    1429                 :             :         Assert(portal->portalContext == CurrentMemoryContext);
    1430                 :             : 
    1431                 :      249456 :         MemoryContextDeleteChildren(portal->portalContext);
    1432                 :             : 
    1433                 :             :         /*
    1434                 :             :          * Avoid crashing if portal->stmts has been reset.  This can only
    1435                 :             :          * occur if a CALL or DO utility statement executed an internal
    1436                 :             :          * COMMIT/ROLLBACK (cf PortalReleaseCachedPlan).  The CALL or DO must
    1437                 :             :          * have been the only statement in the portal, so there's nothing left
    1438                 :             :          * for us to do; but we don't want to dereference a now-dangling list
    1439                 :             :          * pointer.
    1440                 :             :          */
    1441         [ -  + ]:      249456 :         if (portal->stmts == NIL)
    1442                 :           0 :             break;
    1443                 :             : 
    1444                 :             :         /*
    1445                 :             :          * Increment command counter between queries, but not after the last
    1446                 :             :          * one.
    1447                 :             :          */
    1448         [ +  + ]:      249456 :         if (lnext(portal->stmts, stmtlist_item) != NULL)
    1449                 :         416 :             CommandCounterIncrement();
    1450                 :             :     }
    1451                 :             : 
    1452                 :             :     /* Pop the snapshot if we pushed one. */
    1453         [ +  + ]:      249040 :     if (active_snapshot_set)
    1454                 :       52348 :         PopActiveSnapshot();
    1455                 :             : 
    1456                 :             :     /*
    1457                 :             :      * If a command tag was requested and we did not fill in a run-time-
    1458                 :             :      * determined tag above, copy the parse-time tag from the Portal.  (There
    1459                 :             :      * might not be any tag there either, in edge cases such as empty prepared
    1460                 :             :      * statements.  That's OK.)
    1461                 :             :      */
    1462         [ +  - ]:      249040 :     if (qc &&
    1463         [ +  + ]:      249040 :         qc->commandTag == CMDTAG_UNKNOWN &&
    1464         [ +  - ]:      188977 :         portal->qc.commandTag != CMDTAG_UNKNOWN)
    1465                 :      188977 :         CopyQueryCompletion(qc, &portal->qc);
    1466                 :      249040 : }
    1467                 :             : 
    1468                 :             : /*
    1469                 :             :  * PortalRunFetch
    1470                 :             :  *      Variant form of PortalRun that supports SQL FETCH directions.
    1471                 :             :  *
    1472                 :             :  * Note: we presently assume that no callers of this want isTopLevel = true.
    1473                 :             :  *
    1474                 :             :  * count <= 0 is interpreted as a no-op: the destination gets started up
    1475                 :             :  * and shut down, but nothing else happens.  Also, count == FETCH_ALL is
    1476                 :             :  * interpreted as "all rows".  (cf FetchStmt.howMany)
    1477                 :             :  *
    1478                 :             :  * Returns number of rows processed (suitable for use in result tag)
    1479                 :             :  */
    1480                 :             : uint64
    1481                 :       34493 : PortalRunFetch(Portal portal,
    1482                 :             :                FetchDirection fdirection,
    1483                 :             :                long count,
    1484                 :             :                DestReceiver *dest)
    1485                 :             : {
    1486                 :             :     uint64      result;
    1487                 :             :     Portal      saveActivePortal;
    1488                 :             :     ResourceOwner saveResourceOwner;
    1489                 :             :     MemoryContext savePortalContext;
    1490                 :             :     MemoryContext oldContext;
    1491                 :             : 
    1492                 :             :     Assert(PortalIsValid(portal));
    1493                 :             : 
    1494                 :             :     /*
    1495                 :             :      * Check for improper portal use, and mark portal active.
    1496                 :             :      */
    1497                 :       34493 :     MarkPortalActive(portal);
    1498                 :             : 
    1499                 :             :     /*
    1500                 :             :      * Set up global portal context pointers.
    1501                 :             :      */
    1502                 :       34481 :     saveActivePortal = ActivePortal;
    1503                 :       34481 :     saveResourceOwner = CurrentResourceOwner;
    1504                 :       34481 :     savePortalContext = PortalContext;
    1505         [ +  + ]:       34481 :     PG_TRY();
    1506                 :             :     {
    1507                 :       34481 :         ActivePortal = portal;
    1508         [ +  + ]:       34481 :         if (portal->resowner)
    1509                 :       34280 :             CurrentResourceOwner = portal->resowner;
    1510                 :       34481 :         PortalContext = portal->portalContext;
    1511                 :             : 
    1512                 :       34481 :         oldContext = MemoryContextSwitchTo(PortalContext);
    1513                 :             : 
    1514      [ +  +  - ]:       34481 :         switch (portal->strategy)
    1515                 :             :         {
    1516                 :       13096 :             case PORTAL_ONE_SELECT:
    1517                 :       13096 :                 result = DoPortalRunFetch(portal, fdirection, count, dest);
    1518                 :       13036 :                 break;
    1519                 :             : 
    1520                 :       21385 :             case PORTAL_ONE_RETURNING:
    1521                 :             :             case PORTAL_ONE_MOD_WITH:
    1522                 :             :             case PORTAL_UTIL_SELECT:
    1523                 :             : 
    1524                 :             :                 /*
    1525                 :             :                  * If we have not yet run the command, do so, storing its
    1526                 :             :                  * results in the portal's tuplestore.
    1527                 :             :                  */
    1528         [ +  + ]:       21385 :                 if (!portal->holdStore)
    1529                 :        5452 :                     FillPortalStore(portal, false /* isTopLevel */ );
    1530                 :             : 
    1531                 :             :                 /*
    1532                 :             :                  * Now fetch desired portion of results.
    1533                 :             :                  */
    1534                 :       21381 :                 result = DoPortalRunFetch(portal, fdirection, count, dest);
    1535                 :       21381 :                 break;
    1536                 :             : 
    1537                 :           0 :             default:
    1538         [ #  # ]:           0 :                 elog(ERROR, "unsupported portal strategy");
    1539                 :             :                 result = 0;     /* keep compiler quiet */
    1540                 :             :                 break;
    1541                 :             :         }
    1542                 :             :     }
    1543                 :          64 :     PG_CATCH();
    1544                 :             :     {
    1545                 :             :         /* Uncaught error while executing portal: mark it dead */
    1546                 :          64 :         MarkPortalFailed(portal);
    1547                 :             : 
    1548                 :             :         /* Restore global vars and propagate error */
    1549                 :          64 :         ActivePortal = saveActivePortal;
    1550                 :          64 :         CurrentResourceOwner = saveResourceOwner;
    1551                 :          64 :         PortalContext = savePortalContext;
    1552                 :             : 
    1553                 :          64 :         PG_RE_THROW();
    1554                 :             :     }
    1555         [ -  + ]:       34417 :     PG_END_TRY();
    1556                 :             : 
    1557                 :       34417 :     MemoryContextSwitchTo(oldContext);
    1558                 :             : 
    1559                 :             :     /* Mark portal not active */
    1560                 :       34417 :     portal->status = PORTAL_READY;
    1561                 :             : 
    1562                 :       34417 :     ActivePortal = saveActivePortal;
    1563                 :       34417 :     CurrentResourceOwner = saveResourceOwner;
    1564                 :       34417 :     PortalContext = savePortalContext;
    1565                 :             : 
    1566                 :       34417 :     return result;
    1567                 :             : }
    1568                 :             : 
    1569                 :             : /*
    1570                 :             :  * DoPortalRunFetch
    1571                 :             :  *      Guts of PortalRunFetch --- the portal context is already set up
    1572                 :             :  *
    1573                 :             :  * Here, count < 0 typically reverses the direction.  Also, count == FETCH_ALL
    1574                 :             :  * is interpreted as "all rows".  (cf FetchStmt.howMany)
    1575                 :             :  *
    1576                 :             :  * Returns number of rows processed (suitable for use in result tag)
    1577                 :             :  */
    1578                 :             : static uint64
    1579                 :       34477 : DoPortalRunFetch(Portal portal,
    1580                 :             :                  FetchDirection fdirection,
    1581                 :             :                  long count,
    1582                 :             :                  DestReceiver *dest)
    1583                 :             : {
    1584                 :             :     bool        forward;
    1585                 :             : 
    1586                 :             :     Assert(portal->strategy == PORTAL_ONE_SELECT ||
    1587                 :             :            portal->strategy == PORTAL_ONE_RETURNING ||
    1588                 :             :            portal->strategy == PORTAL_ONE_MOD_WITH ||
    1589                 :             :            portal->strategy == PORTAL_UTIL_SELECT);
    1590                 :             : 
    1591                 :             :     /*
    1592                 :             :      * Note: we disallow backwards fetch (including re-fetch of current row)
    1593                 :             :      * for NO SCROLL cursors, but we interpret that very loosely: you can use
    1594                 :             :      * any of the FetchDirection options, so long as the end result is to move
    1595                 :             :      * forwards by at least one row.  Currently it's sufficient to check for
    1596                 :             :      * NO SCROLL in DoPortalRewind() and in the forward == false path in
    1597                 :             :      * PortalRunSelect(); but someday we might prefer to account for that
    1598                 :             :      * restriction explicitly here.
    1599                 :             :      */
    1600   [ +  +  +  +  :       34477 :     switch (fdirection)
                      - ]
    1601                 :             :     {
    1602                 :       33900 :         case FETCH_FORWARD:
    1603         [ +  + ]:       33900 :             if (count < 0)
    1604                 :             :             {
    1605                 :           2 :                 fdirection = FETCH_BACKWARD;
    1606                 :           2 :                 count = -count;
    1607                 :             :             }
    1608                 :             :             /* fall out of switch to share code with FETCH_BACKWARD */
    1609                 :       33900 :             break;
    1610                 :         353 :         case FETCH_BACKWARD:
    1611         [ +  + ]:         353 :             if (count < 0)
    1612                 :             :             {
    1613                 :           1 :                 fdirection = FETCH_FORWARD;
    1614                 :           1 :                 count = -count;
    1615                 :             :             }
    1616                 :             :             /* fall out of switch to share code with FETCH_FORWARD */
    1617                 :         353 :             break;
    1618                 :         165 :         case FETCH_ABSOLUTE:
    1619         [ +  + ]:         165 :             if (count > 0)
    1620                 :             :             {
    1621                 :             :                 /*
    1622                 :             :                  * Definition: Rewind to start, advance count-1 rows, return
    1623                 :             :                  * next row (if any).
    1624                 :             :                  *
    1625                 :             :                  * In practice, if the goal is less than halfway back to the
    1626                 :             :                  * start, it's better to scan from where we are.
    1627                 :             :                  *
    1628                 :             :                  * Also, if current portalPos is outside the range of "long",
    1629                 :             :                  * do it the hard way to avoid possible overflow of the count
    1630                 :             :                  * argument to PortalRunSelect.  We must exclude exactly
    1631                 :             :                  * LONG_MAX, as well, lest the count look like FETCH_ALL.
    1632                 :             :                  *
    1633                 :             :                  * In any case, we arrange to fetch the target row going
    1634                 :             :                  * forwards.
    1635                 :             :                  */
    1636         [ +  + ]:         119 :                 if ((uint64) (count - 1) <= portal->portalPos / 2 ||
    1637         [ -  + ]:          25 :                     portal->portalPos >= (uint64) LONG_MAX)
    1638                 :             :                 {
    1639                 :          94 :                     DoPortalRewind(portal);
    1640         [ -  + ]:          90 :                     if (count > 1)
    1641                 :           0 :                         PortalRunSelect(portal, true, count - 1,
    1642                 :             :                                         None_Receiver);
    1643                 :             :                 }
    1644                 :             :                 else
    1645                 :             :                 {
    1646                 :          25 :                     long        pos = (long) portal->portalPos;
    1647                 :             : 
    1648         [ -  + ]:          25 :                     if (portal->atEnd)
    1649                 :           0 :                         pos++;  /* need one extra fetch if off end */
    1650         [ +  + ]:          25 :                     if (count <= pos)
    1651                 :           8 :                         PortalRunSelect(portal, false, pos - count + 1,
    1652                 :             :                                         None_Receiver);
    1653         [ +  + ]:          17 :                     else if (count > pos + 1)
    1654                 :           8 :                         PortalRunSelect(portal, true, count - pos - 1,
    1655                 :             :                                         None_Receiver);
    1656                 :             :                 }
    1657                 :         111 :                 return PortalRunSelect(portal, true, 1L, dest);
    1658                 :             :             }
    1659         [ +  + ]:          46 :             else if (count < 0)
    1660                 :             :             {
    1661                 :             :                 /*
    1662                 :             :                  * Definition: Advance to end, back up abs(count)-1 rows,
    1663                 :             :                  * return prior row (if any).  We could optimize this if we
    1664                 :             :                  * knew in advance where the end was, but typically we won't.
    1665                 :             :                  * (Is it worth considering case where count > half of size of
    1666                 :             :                  * query?  We could rewind once we know the size ...)
    1667                 :             :                  */
    1668                 :          38 :                 PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
    1669         [ -  + ]:          38 :                 if (count < -1)
    1670                 :           0 :                     PortalRunSelect(portal, false, -count - 1, None_Receiver);
    1671                 :          38 :                 return PortalRunSelect(portal, false, 1L, dest);
    1672                 :             :             }
    1673                 :             :             else
    1674                 :             :             {
    1675                 :             :                 /* count == 0 */
    1676                 :             :                 /* Rewind to start, return zero rows */
    1677                 :           8 :                 DoPortalRewind(portal);
    1678                 :           8 :                 return PortalRunSelect(portal, true, 0L, dest);
    1679                 :             :             }
    1680                 :             :             break;
    1681                 :          59 :         case FETCH_RELATIVE:
    1682         [ +  + ]:          59 :             if (count > 0)
    1683                 :             :             {
    1684                 :             :                 /*
    1685                 :             :                  * Definition: advance count-1 rows, return next row (if any).
    1686                 :             :                  */
    1687         [ +  + ]:          26 :                 if (count > 1)
    1688                 :          17 :                     PortalRunSelect(portal, true, count - 1, None_Receiver);
    1689                 :          26 :                 return PortalRunSelect(portal, true, 1L, dest);
    1690                 :             :             }
    1691         [ +  + ]:          33 :             else if (count < 0)
    1692                 :             :             {
    1693                 :             :                 /*
    1694                 :             :                  * Definition: back up abs(count)-1 rows, return prior row (if
    1695                 :             :                  * any).
    1696                 :             :                  */
    1697         [ +  + ]:          21 :                 if (count < -1)
    1698                 :          12 :                     PortalRunSelect(portal, false, -count - 1, None_Receiver);
    1699                 :          21 :                 return PortalRunSelect(portal, false, 1L, dest);
    1700                 :             :             }
    1701                 :             :             else
    1702                 :             :             {
    1703                 :             :                 /* count == 0 */
    1704                 :             :                 /* Same as FETCH FORWARD 0, so fall out of switch */
    1705                 :          12 :                 fdirection = FETCH_FORWARD;
    1706                 :             :             }
    1707                 :          12 :             break;
    1708                 :           0 :         default:
    1709         [ #  # ]:           0 :             elog(ERROR, "bogus direction");
    1710                 :             :             break;
    1711                 :             :     }
    1712                 :             : 
    1713                 :             :     /*
    1714                 :             :      * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
    1715                 :             :      * >= 0.
    1716                 :             :      */
    1717                 :       34265 :     forward = (fdirection == FETCH_FORWARD);
    1718                 :             : 
    1719                 :             :     /*
    1720                 :             :      * Zero count means to re-fetch the current row, if any (per SQL)
    1721                 :             :      */
    1722         [ +  + ]:       34265 :     if (count == 0)
    1723                 :             :     {
    1724                 :             :         bool        on_row;
    1725                 :             : 
    1726                 :             :         /* Are we sitting on a row? */
    1727   [ +  -  +  - ]:          12 :         on_row = (!portal->atStart && !portal->atEnd);
    1728                 :             : 
    1729         [ -  + ]:          12 :         if (dest->mydest == DestNone)
    1730                 :             :         {
    1731                 :             :             /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
    1732                 :           0 :             return on_row ? 1 : 0;
    1733                 :             :         }
    1734                 :             :         else
    1735                 :             :         {
    1736                 :             :             /*
    1737                 :             :              * If we are sitting on a row, back up one so we can re-fetch it.
    1738                 :             :              * If we are not sitting on a row, we still have to start up and
    1739                 :             :              * shut down the executor so that the destination is initialized
    1740                 :             :              * and shut down correctly; so keep going.  To PortalRunSelect,
    1741                 :             :              * count == 0 means we will retrieve no row.
    1742                 :             :              */
    1743         [ +  - ]:          12 :             if (on_row)
    1744                 :             :             {
    1745                 :          12 :                 PortalRunSelect(portal, false, 1L, None_Receiver);
    1746                 :             :                 /* Set up to fetch one row forward */
    1747                 :           8 :                 count = 1;
    1748                 :           8 :                 forward = true;
    1749                 :             :             }
    1750                 :             :         }
    1751                 :             :     }
    1752                 :             : 
    1753                 :             :     /*
    1754                 :             :      * Optimize MOVE BACKWARD ALL into a Rewind.
    1755                 :             :      */
    1756   [ +  +  +  +  :       34261 :     if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
                   +  + ]
    1757                 :             :     {
    1758                 :          20 :         uint64      result = portal->portalPos;
    1759                 :             : 
    1760   [ +  +  +  + ]:          20 :         if (result > 0 && !portal->atEnd)
    1761                 :           4 :             result--;
    1762                 :          20 :         DoPortalRewind(portal);
    1763                 :          20 :         return result;
    1764                 :             :     }
    1765                 :             : 
    1766                 :       34241 :     return PortalRunSelect(portal, forward, count, dest);
    1767                 :             : }
    1768                 :             : 
    1769                 :             : /*
    1770                 :             :  * DoPortalRewind - rewind a Portal to starting point
    1771                 :             :  */
    1772                 :             : static void
    1773                 :         122 : DoPortalRewind(Portal portal)
    1774                 :             : {
    1775                 :             :     QueryDesc  *queryDesc;
    1776                 :             : 
    1777                 :             :     /*
    1778                 :             :      * No work is needed if we've not advanced nor attempted to advance the
    1779                 :             :      * cursor (and we don't want to throw a NO SCROLL error in this case).
    1780                 :             :      */
    1781   [ +  +  +  - ]:         122 :     if (portal->atStart && !portal->atEnd)
    1782                 :          44 :         return;
    1783                 :             : 
    1784                 :             :     /* Otherwise, cursor must allow scrolling */
    1785         [ +  + ]:          78 :     if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
    1786         [ +  - ]:           4 :         ereport(ERROR,
    1787                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1788                 :             :                  errmsg("cursor can only scan forward"),
    1789                 :             :                  errhint("Declare it with SCROLL option to enable backward scan.")));
    1790                 :             : 
    1791                 :             :     /* Rewind holdStore, if we have one */
    1792         [ +  + ]:          74 :     if (portal->holdStore)
    1793                 :             :     {
    1794                 :             :         MemoryContext oldcontext;
    1795                 :             : 
    1796                 :          28 :         oldcontext = MemoryContextSwitchTo(portal->holdContext);
    1797                 :          28 :         tuplestore_rescan(portal->holdStore);
    1798                 :          28 :         MemoryContextSwitchTo(oldcontext);
    1799                 :             :     }
    1800                 :             : 
    1801                 :             :     /* Rewind executor, if active */
    1802                 :          74 :     queryDesc = portal->queryDesc;
    1803         [ +  + ]:          74 :     if (queryDesc)
    1804                 :             :     {
    1805                 :          46 :         PushActiveSnapshot(queryDesc->snapshot);
    1806                 :          46 :         ExecutorRewind(queryDesc);
    1807                 :          46 :         PopActiveSnapshot();
    1808                 :             :     }
    1809                 :             : 
    1810                 :          74 :     portal->atStart = true;
    1811                 :          74 :     portal->atEnd = false;
    1812                 :          74 :     portal->portalPos = 0;
    1813                 :             : }
    1814                 :             : 
    1815                 :             : /*
    1816                 :             :  * PlannedStmtRequiresSnapshot - what it says on the tin
    1817                 :             :  */
    1818                 :             : bool
    1819                 :      319681 : PlannedStmtRequiresSnapshot(PlannedStmt *pstmt)
    1820                 :             : {
    1821                 :      319681 :     Node       *utilityStmt = pstmt->utilityStmt;
    1822                 :             : 
    1823                 :             :     /* If it's not a utility statement, it definitely needs a snapshot */
    1824         [ +  + ]:      319681 :     if (utilityStmt == NULL)
    1825                 :       60848 :         return true;
    1826                 :             : 
    1827                 :             :     /*
    1828                 :             :      * Most utility statements need a snapshot, and the default presumption
    1829                 :             :      * about new ones should be that they do too.  Hence, enumerate those that
    1830                 :             :      * do not need one.
    1831                 :             :      *
    1832                 :             :      * Transaction control, LOCK, and SET must *not* set a snapshot, since
    1833                 :             :      * they need to be executable at the start of a transaction-snapshot-mode
    1834                 :             :      * transaction without freezing a snapshot.  By extension we allow SHOW
    1835                 :             :      * not to set a snapshot.  The other stmts listed are just efficiency
    1836                 :             :      * hacks.  Beware of listing anything that can modify the database --- if,
    1837                 :             :      * say, it has to update an index with expressions that invoke
    1838                 :             :      * user-defined functions, then it had better have a snapshot.
    1839                 :             :      */
    1840         [ +  + ]:      258833 :     if (IsA(utilityStmt, TransactionStmt) ||
    1841         [ +  + ]:      231209 :         IsA(utilityStmt, LockStmt) ||
    1842         [ +  + ]:      230584 :         IsA(utilityStmt, VariableSetStmt) ||
    1843         [ +  + ]:      204498 :         IsA(utilityStmt, VariableShowStmt) ||
    1844         [ +  + ]:      203933 :         IsA(utilityStmt, ConstraintsSetStmt) ||
    1845                 :             :     /* efficiency hacks from here down */
    1846         [ +  + ]:      203862 :         IsA(utilityStmt, FetchStmt) ||
    1847         [ +  + ]:      199224 :         IsA(utilityStmt, ListenStmt) ||
    1848         [ +  + ]:      199172 :         IsA(utilityStmt, NotifyStmt) ||
    1849         [ +  + ]:      199110 :         IsA(utilityStmt, UnlistenStmt) ||
    1850         [ +  + ]:      199048 :         IsA(utilityStmt, CheckPointStmt) ||
    1851         [ +  + ]:      198567 :         IsA(utilityStmt, WaitStmt))
    1852                 :       60563 :         return false;
    1853                 :             : 
    1854                 :      198270 :     return true;
    1855                 :             : }
    1856                 :             : 
    1857                 :             : /*
    1858                 :             :  * EnsurePortalSnapshotExists - recreate Portal-level snapshot, if needed
    1859                 :             :  *
    1860                 :             :  * Generally, we will have an active snapshot whenever we are executing
    1861                 :             :  * inside a Portal, unless the Portal's query is one of the utility
    1862                 :             :  * statements exempted from that rule (see PlannedStmtRequiresSnapshot).
    1863                 :             :  * However, procedures and DO blocks can commit or abort the transaction,
    1864                 :             :  * and thereby destroy all snapshots.  This function can be called to
    1865                 :             :  * re-establish the Portal-level snapshot when none exists.
    1866                 :             :  */
    1867                 :             : void
    1868                 :      305863 : EnsurePortalSnapshotExists(void)
    1869                 :             : {
    1870                 :             :     Portal      portal;
    1871                 :             : 
    1872                 :             :     /*
    1873                 :             :      * Nothing to do if a snapshot is set.  (We take it on faith that the
    1874                 :             :      * outermost active snapshot belongs to some Portal; or if there is no
    1875                 :             :      * Portal, it's somebody else's responsibility to manage things.)
    1876                 :             :      */
    1877         [ +  + ]:      305863 :     if (ActiveSnapshotSet())
    1878                 :      303498 :         return;
    1879                 :             : 
    1880                 :             :     /* Otherwise, we'd better have an active Portal */
    1881                 :        2365 :     portal = ActivePortal;
    1882         [ -  + ]:        2365 :     if (unlikely(portal == NULL))
    1883         [ #  # ]:           0 :         elog(ERROR, "cannot execute SQL without an outer snapshot or portal");
    1884                 :             :     Assert(portal->portalSnapshot == NULL);
    1885                 :             : 
    1886                 :             :     /*
    1887                 :             :      * Create a new snapshot, make it active, and remember it in portal.
    1888                 :             :      * Because the portal now references the snapshot, we must tell snapmgr.c
    1889                 :             :      * that the snapshot belongs to the portal's transaction level, else we
    1890                 :             :      * risk portalSnapshot becoming a dangling pointer.
    1891                 :             :      */
    1892                 :        2365 :     PushActiveSnapshotWithLevel(GetTransactionSnapshot(), portal->createLevel);
    1893                 :             :     /* PushActiveSnapshotWithLevel might have copied the snapshot */
    1894                 :        2365 :     portal->portalSnapshot = GetActiveSnapshot();
    1895                 :             : }
        

Generated by: LCOV version 2.0-1