LCOV - differential code coverage report
Current view: top level - src/backend/tcop - pquery.c (source / functions) Coverage Total Hit LBC UBC CBC
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 92.1 % 570 525 45 525
Current Date: 2024-04-14 14:21:10 Functions: 100.0 % 19 19 19
Baseline: 16@8cea358b128 Branches: 74.5 % 419 312 1 106 312
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed (240..) days: 92.1 % 570 525 45 525
Function coverage date bins:
(240..) days: 100.0 % 19 19 19
Branch coverage date bins:
(240..) days: 74.5 % 419 312 1 106 312

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

Generated by: LCOV version 2.1-beta2-3-g6141622