LCOV - code coverage report
Current view: top level - src/backend/executor - spi.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 71.1 % 1243 884
Test Date: 2026-11-24 10:15:57 Functions: 81.0 % 84 68
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 55.0 % 773 425

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * spi.c
       4                 :             :  *              Server Programming Interface
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/executor/spi.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include "access/htup_details.h"
      18                 :             : #include "access/printtup.h"
      19                 :             : #include "access/sysattr.h"
      20                 :             : #include "access/xact.h"
      21                 :             : #include "catalog/heap.h"
      22                 :             : #include "catalog/pg_type.h"
      23                 :             : #include "commands/trigger.h"
      24                 :             : #include "executor/executor.h"
      25                 :             : #include "executor/spi_priv.h"
      26                 :             : #include "tcop/pquery.h"
      27                 :             : #include "tcop/utility.h"
      28                 :             : #include "utils/builtins.h"
      29                 :             : #include "utils/datum.h"
      30                 :             : #include "utils/lsyscache.h"
      31                 :             : #include "utils/memutils.h"
      32                 :             : #include "utils/rel.h"
      33                 :             : #include "utils/snapmgr.h"
      34                 :             : #include "utils/syscache.h"
      35                 :             : #include "utils/tuplestore.h"
      36                 :             : #include "utils/typcache.h"
      37                 :             : 
      38                 :             : 
      39                 :             : /*
      40                 :             :  * These global variables are part of the API for various SPI functions
      41                 :             :  * (a horrible API choice, but it's too late now).  To reduce the risk of
      42                 :             :  * interference between different SPI callers, we save and restore them
      43                 :             :  * when entering/exiting a SPI nesting level.
      44                 :             :  */
      45                 :             : uint64      SPI_processed = 0;
      46                 :             : SPITupleTable *SPI_tuptable = NULL;
      47                 :             : int         SPI_result = 0;
      48                 :             : 
      49                 :             : static _SPI_connection *_SPI_stack = NULL;
      50                 :             : static _SPI_connection *_SPI_current = NULL;
      51                 :             : static int  _SPI_stack_depth = 0;   /* allocated size of _SPI_stack */
      52                 :             : static int  _SPI_connected = -1;    /* current stack index */
      53                 :             : 
      54                 :             : typedef struct SPICallbackArg
      55                 :             : {
      56                 :             :     const char *query;
      57                 :             :     RawParseMode mode;
      58                 :             : } SPICallbackArg;
      59                 :             : 
      60                 :             : static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
      61                 :             :                                        ParamListInfo paramLI, bool read_only);
      62                 :             : 
      63                 :             : static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan);
      64                 :             : 
      65                 :             : static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan);
      66                 :             : 
      67                 :             : static int  _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
      68                 :             :                               Snapshot snapshot, Snapshot crosscheck_snapshot,
      69                 :             :                               bool fire_triggers);
      70                 :             : 
      71                 :             : static ParamListInfo _SPI_convert_params(int nargs, const Oid *argtypes,
      72                 :             :                                          const Datum *Values, const char *Nulls);
      73                 :             : 
      74                 :             : static int  _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount);
      75                 :             : 
      76                 :             : static void _SPI_error_callback(void *arg);
      77                 :             : 
      78                 :             : static void _SPI_cursor_operation(Portal portal,
      79                 :             :                                   FetchDirection direction, long count,
      80                 :             :                                   DestReceiver *dest);
      81                 :             : 
      82                 :             : static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan);
      83                 :             : static SPIPlanPtr _SPI_save_plan(SPIPlanPtr plan);
      84                 :             : 
      85                 :             : static int  _SPI_begin_call(bool use_exec);
      86                 :             : static int  _SPI_end_call(bool use_exec);
      87                 :             : static MemoryContext _SPI_execmem(void);
      88                 :             : static MemoryContext _SPI_procmem(void);
      89                 :             : static bool _SPI_checktuples(void);
      90                 :             : 
      91                 :             : 
      92                 :             : /* =================== interface functions =================== */
      93                 :             : 
      94                 :             : int
      95                 :        9612 : SPI_connect(void)
      96                 :             : {
      97                 :        9612 :     return SPI_connect_ext(0);
      98                 :             : }
      99                 :             : 
     100                 :             : int
     101                 :       76282 : SPI_connect_ext(int options)
     102                 :             : {
     103                 :             :     int         newdepth;
     104                 :             : 
     105                 :             :     /* Enlarge stack if necessary */
     106         [ +  + ]:       76282 :     if (_SPI_stack == NULL)
     107                 :             :     {
     108   [ +  -  -  + ]:        1165 :         if (_SPI_connected != -1 || _SPI_stack_depth != 0)
     109         [ #  # ]:           0 :             elog(ERROR, "SPI stack corrupted");
     110                 :        1165 :         newdepth = 16;
     111                 :        1165 :         _SPI_stack = (_SPI_connection *)
     112                 :        1165 :             MemoryContextAlloc(TopMemoryContext,
     113                 :             :                                newdepth * sizeof(_SPI_connection));
     114                 :        1165 :         _SPI_stack_depth = newdepth;
     115                 :             :     }
     116                 :             :     else
     117                 :             :     {
     118   [ +  -  -  + ]:       75117 :         if (_SPI_stack_depth <= 0 || _SPI_stack_depth <= _SPI_connected)
     119         [ #  # ]:           0 :             elog(ERROR, "SPI stack corrupted");
     120         [ +  + ]:       75117 :         if (_SPI_stack_depth == _SPI_connected + 1)
     121                 :             :         {
     122                 :          13 :             newdepth = _SPI_stack_depth * 2;
     123                 :          13 :             _SPI_stack = repalloc_array(_SPI_stack, _SPI_connection, newdepth);
     124                 :          13 :             _SPI_stack_depth = newdepth;
     125                 :             :         }
     126                 :             :     }
     127                 :             : 
     128                 :             :     /* Enter new stack level */
     129                 :       76282 :     _SPI_connected++;
     130                 :             :     Assert(_SPI_connected >= 0 && _SPI_connected < _SPI_stack_depth);
     131                 :             : 
     132                 :       76282 :     _SPI_current = &(_SPI_stack[_SPI_connected]);
     133                 :       76282 :     _SPI_current->processed = 0;
     134                 :       76282 :     _SPI_current->tuptable = NULL;
     135                 :       76282 :     _SPI_current->execSubid = InvalidSubTransactionId;
     136                 :       76282 :     slist_init(&_SPI_current->tuptables);
     137                 :       76282 :     _SPI_current->procCxt = NULL;    /* in case we fail to create 'em */
     138                 :       76282 :     _SPI_current->execCxt = NULL;
     139                 :       76282 :     _SPI_current->connectSubid = GetCurrentSubTransactionId();
     140                 :       76282 :     _SPI_current->queryEnv = NULL;
     141                 :       76282 :     _SPI_current->atomic = (options & SPI_OPT_NONATOMIC ? false : true);
     142                 :       76282 :     _SPI_current->internal_xact = false;
     143                 :       76282 :     _SPI_current->outer_processed = SPI_processed;
     144                 :       76282 :     _SPI_current->outer_tuptable = SPI_tuptable;
     145                 :       76282 :     _SPI_current->outer_result = SPI_result;
     146                 :             : 
     147                 :             :     /*
     148                 :             :      * Create memory contexts for this procedure
     149                 :             :      *
     150                 :             :      * In atomic contexts (the normal case), we use TopTransactionContext,
     151                 :             :      * otherwise PortalContext, so that it lives across transaction
     152                 :             :      * boundaries.
     153                 :             :      *
     154                 :             :      * XXX It could be better to use PortalContext as the parent context in
     155                 :             :      * all cases, but we may not be inside a portal (consider deferred-trigger
     156                 :             :      * execution).  Perhaps CurTransactionContext could be an option?  For now
     157                 :             :      * it doesn't matter because we clean up explicitly in AtEOSubXact_SPI();
     158                 :             :      * but see also AtEOXact_SPI().
     159                 :             :      */
     160         [ +  + ]:       76282 :     _SPI_current->procCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : PortalContext,
     161                 :             :                                                   "SPI Proc",
     162                 :             :                                                   ALLOCSET_DEFAULT_SIZES);
     163         [ +  + ]:       76282 :     _SPI_current->execCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : _SPI_current->procCxt,
     164                 :             :                                                   "SPI Exec",
     165                 :             :                                                   ALLOCSET_DEFAULT_SIZES);
     166                 :             :     /* ... and switch to procedure's context */
     167                 :       76282 :     _SPI_current->savedcxt = MemoryContextSwitchTo(_SPI_current->procCxt);
     168                 :             : 
     169                 :             :     /*
     170                 :             :      * Reset API global variables so that current caller cannot accidentally
     171                 :             :      * depend on state of an outer caller.
     172                 :             :      */
     173                 :       76282 :     SPI_processed = 0;
     174                 :       76282 :     SPI_tuptable = NULL;
     175                 :       76282 :     SPI_result = 0;
     176                 :             : 
     177                 :       76282 :     return SPI_OK_CONNECT;
     178                 :             : }
     179                 :             : 
     180                 :             : int
     181                 :       74157 : SPI_finish(void)
     182                 :             : {
     183                 :             :     int         res;
     184                 :             : 
     185                 :       74157 :     res = _SPI_begin_call(false);   /* just check we're connected */
     186         [ -  + ]:       74157 :     if (res < 0)
     187                 :           0 :         return res;
     188                 :             : 
     189                 :             :     /* Restore memory context as it was before procedure call */
     190                 :       74157 :     MemoryContextSwitchTo(_SPI_current->savedcxt);
     191                 :             : 
     192                 :             :     /* queryEnv will become invalid; drop portals that need it */
     193         [ +  + ]:       74157 :     if (_SPI_current->queryEnv != NULL)
     194                 :         375 :         DropQueryEnvPortals(_SPI_current->queryEnv);
     195                 :             : 
     196                 :             :     /* Release memory used in procedure call (including tuptables) */
     197                 :       74157 :     MemoryContextDelete(_SPI_current->execCxt);
     198                 :       74157 :     _SPI_current->execCxt = NULL;
     199                 :       74157 :     MemoryContextDelete(_SPI_current->procCxt);
     200                 :       74157 :     _SPI_current->procCxt = NULL;
     201                 :             : 
     202                 :             :     /*
     203                 :             :      * Restore outer API variables, especially SPI_tuptable which is probably
     204                 :             :      * pointing at a just-deleted tuptable
     205                 :             :      */
     206                 :       74157 :     SPI_processed = _SPI_current->outer_processed;
     207                 :       74157 :     SPI_tuptable = _SPI_current->outer_tuptable;
     208                 :       74157 :     SPI_result = _SPI_current->outer_result;
     209                 :             : 
     210                 :             :     /* Exit stack level */
     211                 :       74157 :     _SPI_connected--;
     212         [ +  + ]:       74157 :     if (_SPI_connected < 0)
     213                 :       63699 :         _SPI_current = NULL;
     214                 :             :     else
     215                 :       10458 :         _SPI_current = &(_SPI_stack[_SPI_connected]);
     216                 :             : 
     217                 :       74157 :     return SPI_OK_FINISH;
     218                 :             : }
     219                 :             : 
     220                 :             : /*
     221                 :             :  * SPI_start_transaction is a no-op, kept for backwards compatibility.
     222                 :             :  * SPI callers are *always* inside a transaction.
     223                 :             :  */
     224                 :             : void
     225                 :           0 : SPI_start_transaction(void)
     226                 :             : {
     227                 :           0 : }
     228                 :             : 
     229                 :             : static void
     230                 :        2223 : _SPI_commit(bool chain)
     231                 :             : {
     232                 :        2223 :     MemoryContext oldcontext = CurrentMemoryContext;
     233                 :             :     SavedTransactionCharacteristics savetc;
     234                 :             : 
     235                 :             :     /*
     236                 :             :      * Complain if we are in a context that doesn't permit transaction
     237                 :             :      * termination.  (Note: here and _SPI_rollback should be the only places
     238                 :             :      * that throw ERRCODE_INVALID_TRANSACTION_TERMINATION, so that callers can
     239                 :             :      * test for that with security that they know what happened.)
     240                 :             :      */
     241         [ +  + ]:        2223 :     if (_SPI_current->atomic)
     242         [ +  - ]:          16 :         ereport(ERROR,
     243                 :             :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
     244                 :             :                  errmsg("invalid transaction termination")));
     245                 :             : 
     246                 :             :     /*
     247                 :             :      * This restriction is required by PLs implemented on top of SPI.  They
     248                 :             :      * use subtransactions to establish exception blocks that are supposed to
     249                 :             :      * be rolled back together if there is an error.  Terminating the
     250                 :             :      * top-level transaction in such a block violates that idea.  A future PL
     251                 :             :      * implementation might have different ideas about this, in which case
     252                 :             :      * this restriction would have to be refined or the check possibly be
     253                 :             :      * moved out of SPI into the PLs.  Note however that the code below relies
     254                 :             :      * on not being within a subtransaction.
     255                 :             :      */
     256         [ +  + ]:        2207 :     if (IsSubTransaction())
     257         [ +  - ]:           3 :         ereport(ERROR,
     258                 :             :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
     259                 :             :                  errmsg("cannot commit while a subtransaction is active")));
     260                 :             : 
     261         [ +  + ]:        2204 :     if (chain)
     262                 :          74 :         SaveTransactionCharacteristics(&savetc);
     263                 :             : 
     264                 :             :     /* Catch any error occurring during the COMMIT */
     265         [ +  + ]:        2204 :     PG_TRY();
     266                 :             :     {
     267                 :             :         /* Protect current SPI stack entry against deletion */
     268                 :        2204 :         _SPI_current->internal_xact = true;
     269                 :             : 
     270                 :             :         /*
     271                 :             :          * Hold any pinned portals that any PLs might be using.  We have to do
     272                 :             :          * this before changing transaction state, since this will run
     273                 :             :          * user-defined code that might throw an error.
     274                 :             :          */
     275                 :        2204 :         HoldPinnedPortals();
     276                 :             : 
     277                 :             :         /* Release snapshots associated with portals */
     278                 :        2203 :         ForgetPortalSnapshots();
     279                 :             : 
     280                 :             :         /* Do the deed */
     281                 :        2203 :         CommitTransactionCommand();
     282                 :             : 
     283                 :             :         /* Immediately start a new transaction */
     284                 :        2196 :         StartTransactionCommand();
     285         [ +  + ]:        2196 :         if (chain)
     286                 :          74 :             RestoreTransactionCharacteristics(&savetc);
     287                 :             : 
     288                 :        2196 :         MemoryContextSwitchTo(oldcontext);
     289                 :             : 
     290                 :        2196 :         _SPI_current->internal_xact = false;
     291                 :             :     }
     292                 :           8 :     PG_CATCH();
     293                 :             :     {
     294                 :             :         ErrorData  *edata;
     295                 :             : 
     296                 :             :         /* Save error info in caller's context */
     297                 :           8 :         MemoryContextSwitchTo(oldcontext);
     298                 :           8 :         edata = CopyErrorData();
     299                 :           8 :         FlushErrorState();
     300                 :             : 
     301                 :             :         /*
     302                 :             :          * Abort the failed transaction.  If this fails too, we'll just
     303                 :             :          * propagate the error out ... there's not that much we can do.
     304                 :             :          */
     305                 :           8 :         AbortCurrentTransaction();
     306                 :             : 
     307                 :             :         /* ... and start a new one */
     308                 :           8 :         StartTransactionCommand();
     309         [ -  + ]:           8 :         if (chain)
     310                 :           0 :             RestoreTransactionCharacteristics(&savetc);
     311                 :             : 
     312                 :           8 :         MemoryContextSwitchTo(oldcontext);
     313                 :             : 
     314                 :           8 :         _SPI_current->internal_xact = false;
     315                 :             : 
     316                 :             :         /* Now that we've cleaned up the transaction, re-throw the error */
     317                 :           8 :         ReThrowError(edata);
     318                 :             :     }
     319         [ -  + ]:        2196 :     PG_END_TRY();
     320                 :        2196 : }
     321                 :             : 
     322                 :             : void
     323                 :        2149 : SPI_commit(void)
     324                 :             : {
     325                 :        2149 :     _SPI_commit(false);
     326                 :        2122 : }
     327                 :             : 
     328                 :             : void
     329                 :          74 : SPI_commit_and_chain(void)
     330                 :             : {
     331                 :          74 :     _SPI_commit(true);
     332                 :          74 : }
     333                 :             : 
     334                 :             : static void
     335                 :         138 : _SPI_rollback(bool chain)
     336                 :             : {
     337                 :         138 :     MemoryContext oldcontext = CurrentMemoryContext;
     338                 :             :     SavedTransactionCharacteristics savetc;
     339                 :             : 
     340                 :             :     /* see comments in _SPI_commit() */
     341         [ -  + ]:         138 :     if (_SPI_current->atomic)
     342         [ #  # ]:           0 :         ereport(ERROR,
     343                 :             :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
     344                 :             :                  errmsg("invalid transaction termination")));
     345                 :             : 
     346                 :             :     /* see comments in _SPI_commit() */
     347         [ +  + ]:         138 :     if (IsSubTransaction())
     348         [ +  - ]:           2 :         ereport(ERROR,
     349                 :             :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
     350                 :             :                  errmsg("cannot roll back while a subtransaction is active")));
     351                 :             : 
     352         [ +  + ]:         136 :     if (chain)
     353                 :          38 :         SaveTransactionCharacteristics(&savetc);
     354                 :             : 
     355                 :             :     /* Catch any error occurring during the ROLLBACK */
     356         [ +  + ]:         136 :     PG_TRY();
     357                 :             :     {
     358                 :             :         /* Protect current SPI stack entry against deletion */
     359                 :         136 :         _SPI_current->internal_xact = true;
     360                 :             : 
     361                 :             :         /*
     362                 :             :          * Hold any pinned portals that any PLs might be using.  We have to do
     363                 :             :          * this before changing transaction state, since this will run
     364                 :             :          * user-defined code that might throw an error, and in any case
     365                 :             :          * couldn't be run in an already-aborted transaction.
     366                 :             :          */
     367                 :         136 :         HoldPinnedPortals();
     368                 :             : 
     369                 :             :         /* Release snapshots associated with portals */
     370                 :         134 :         ForgetPortalSnapshots();
     371                 :             : 
     372                 :             :         /* Do the deed */
     373                 :         134 :         AbortCurrentTransaction();
     374                 :             : 
     375                 :             :         /* Immediately start a new transaction */
     376                 :         134 :         StartTransactionCommand();
     377         [ +  + ]:         134 :         if (chain)
     378                 :          38 :             RestoreTransactionCharacteristics(&savetc);
     379                 :             : 
     380                 :         134 :         MemoryContextSwitchTo(oldcontext);
     381                 :             : 
     382                 :         134 :         _SPI_current->internal_xact = false;
     383                 :             :     }
     384                 :           2 :     PG_CATCH();
     385                 :             :     {
     386                 :             :         ErrorData  *edata;
     387                 :             : 
     388                 :             :         /* Save error info in caller's context */
     389                 :           2 :         MemoryContextSwitchTo(oldcontext);
     390                 :           2 :         edata = CopyErrorData();
     391                 :           2 :         FlushErrorState();
     392                 :             : 
     393                 :             :         /*
     394                 :             :          * Try again to abort the failed transaction.  If this fails too,
     395                 :             :          * we'll just propagate the error out ... there's not that much we can
     396                 :             :          * do.
     397                 :             :          */
     398                 :           2 :         AbortCurrentTransaction();
     399                 :             : 
     400                 :             :         /* ... and start a new one */
     401                 :           2 :         StartTransactionCommand();
     402         [ -  + ]:           2 :         if (chain)
     403                 :           0 :             RestoreTransactionCharacteristics(&savetc);
     404                 :             : 
     405                 :           2 :         MemoryContextSwitchTo(oldcontext);
     406                 :             : 
     407                 :           2 :         _SPI_current->internal_xact = false;
     408                 :             : 
     409                 :             :         /* Now that we've cleaned up the transaction, re-throw the error */
     410                 :           2 :         ReThrowError(edata);
     411                 :             :     }
     412         [ -  + ]:         134 :     PG_END_TRY();
     413                 :         134 : }
     414                 :             : 
     415                 :             : void
     416                 :         100 : SPI_rollback(void)
     417                 :             : {
     418                 :         100 :     _SPI_rollback(false);
     419                 :          96 : }
     420                 :             : 
     421                 :             : void
     422                 :          38 : SPI_rollback_and_chain(void)
     423                 :             : {
     424                 :          38 :     _SPI_rollback(true);
     425                 :          38 : }
     426                 :             : 
     427                 :             : /*
     428                 :             :  * Clean up SPI state at transaction commit or abort.
     429                 :             :  */
     430                 :             : void
     431                 :      664172 : AtEOXact_SPI(bool isCommit)
     432                 :             : {
     433                 :      664172 :     bool        found = false;
     434                 :             : 
     435                 :             :     /*
     436                 :             :      * Pop stack entries, stopping if we find one marked internal_xact (that
     437                 :             :      * one belongs to the caller of SPI_commit or SPI_rollback).
     438                 :             :      */
     439         [ +  + ]:      665856 :     while (_SPI_connected >= 0)
     440                 :             :     {
     441                 :        4024 :         _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
     442                 :             : 
     443         [ +  + ]:        4024 :         if (connection->internal_xact)
     444                 :        2340 :             break;
     445                 :             : 
     446                 :        1684 :         found = true;
     447                 :             : 
     448                 :             :         /*
     449                 :             :          * We need not release the procedure's memory contexts explicitly, as
     450                 :             :          * they'll go away automatically when their parent context does; see
     451                 :             :          * notes in SPI_connect_ext.
     452                 :             :          */
     453                 :             : 
     454                 :             :         /*
     455                 :             :          * Restore outer global variables and pop the stack entry.  Unlike
     456                 :             :          * SPI_finish(), we don't risk switching to memory contexts that might
     457                 :             :          * be already gone.
     458                 :             :          */
     459                 :        1684 :         SPI_processed = connection->outer_processed;
     460                 :        1684 :         SPI_tuptable = connection->outer_tuptable;
     461                 :        1684 :         SPI_result = connection->outer_result;
     462                 :             : 
     463                 :        1684 :         _SPI_connected--;
     464         [ +  + ]:        1684 :         if (_SPI_connected < 0)
     465                 :        1636 :             _SPI_current = NULL;
     466                 :             :         else
     467                 :          48 :             _SPI_current = &(_SPI_stack[_SPI_connected]);
     468                 :             :     }
     469                 :             : 
     470                 :             :     /* We should only find entries to pop during an ABORT. */
     471   [ +  +  -  + ]:      664172 :     if (found && isCommit)
     472         [ #  # ]:           0 :         ereport(WARNING,
     473                 :             :                 (errcode(ERRCODE_WARNING),
     474                 :             :                  errmsg("transaction left non-empty SPI stack"),
     475                 :             :                  errhint("Check for missing \"SPI_finish\" calls.")));
     476                 :      664172 : }
     477                 :             : 
     478                 :             : /*
     479                 :             :  * Clean up SPI state at subtransaction commit or abort.
     480                 :             :  *
     481                 :             :  * During commit, there shouldn't be any unclosed entries remaining from
     482                 :             :  * the current subtransaction; we emit a warning if any are found.
     483                 :             :  */
     484                 :             : void
     485                 :       23152 : AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
     486                 :             : {
     487                 :       23152 :     bool        found = false;
     488                 :             : 
     489         [ +  + ]:       23593 :     while (_SPI_connected >= 0)
     490                 :             :     {
     491                 :       20749 :         _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
     492                 :             : 
     493         [ +  + ]:       20749 :         if (connection->connectSubid != mySubid)
     494                 :       20308 :             break;              /* couldn't be any underneath it either */
     495                 :             : 
     496         [ -  + ]:         441 :         if (connection->internal_xact)
     497                 :           0 :             break;
     498                 :             : 
     499                 :         441 :         found = true;
     500                 :             : 
     501                 :             :         /*
     502                 :             :          * Release procedure memory explicitly (see note in SPI_connect)
     503                 :             :          */
     504         [ +  - ]:         441 :         if (connection->execCxt)
     505                 :             :         {
     506                 :         441 :             MemoryContextDelete(connection->execCxt);
     507                 :         441 :             connection->execCxt = NULL;
     508                 :             :         }
     509         [ +  - ]:         441 :         if (connection->procCxt)
     510                 :             :         {
     511                 :         441 :             MemoryContextDelete(connection->procCxt);
     512                 :         441 :             connection->procCxt = NULL;
     513                 :             :         }
     514                 :             : 
     515                 :             :         /*
     516                 :             :          * Restore outer global variables and pop the stack entry.  Unlike
     517                 :             :          * SPI_finish(), we don't risk switching to memory contexts that might
     518                 :             :          * be already gone.
     519                 :             :          */
     520                 :         441 :         SPI_processed = connection->outer_processed;
     521                 :         441 :         SPI_tuptable = connection->outer_tuptable;
     522                 :         441 :         SPI_result = connection->outer_result;
     523                 :             : 
     524                 :         441 :         _SPI_connected--;
     525         [ +  + ]:         441 :         if (_SPI_connected < 0)
     526                 :          88 :             _SPI_current = NULL;
     527                 :             :         else
     528                 :         353 :             _SPI_current = &(_SPI_stack[_SPI_connected]);
     529                 :             :     }
     530                 :             : 
     531   [ +  +  -  + ]:       23152 :     if (found && isCommit)
     532         [ #  # ]:           0 :         ereport(WARNING,
     533                 :             :                 (errcode(ERRCODE_WARNING),
     534                 :             :                  errmsg("subtransaction left non-empty SPI stack"),
     535                 :             :                  errhint("Check for missing \"SPI_finish\" calls.")));
     536                 :             : 
     537                 :             :     /*
     538                 :             :      * If we are aborting a subtransaction and there is an open SPI context
     539                 :             :      * surrounding the subxact, clean up to prevent memory leakage.
     540                 :             :      */
     541   [ +  +  +  + ]:       23152 :     if (_SPI_current && !isCommit)
     542                 :             :     {
     543                 :             :         slist_mutable_iter siter;
     544                 :             : 
     545                 :             :         /*
     546                 :             :          * Throw away executor state if current executor operation was started
     547                 :             :          * within current subxact (essentially, force a _SPI_end_call(true)).
     548                 :             :          */
     549         [ +  + ]:        3770 :         if (_SPI_current->execSubid >= mySubid)
     550                 :             :         {
     551                 :        3214 :             _SPI_current->execSubid = InvalidSubTransactionId;
     552                 :        3214 :             MemoryContextReset(_SPI_current->execCxt);
     553                 :             :         }
     554                 :             : 
     555                 :             :         /* throw away any tuple tables created within current subxact */
     556   [ +  +  +  +  :        9296 :         slist_foreach_modify(siter, &_SPI_current->tuptables)
                   +  + ]
     557                 :             :         {
     558                 :             :             SPITupleTable *tuptable;
     559                 :             : 
     560                 :        5526 :             tuptable = slist_container(SPITupleTable, next, siter.cur);
     561         [ +  + ]:        5526 :             if (tuptable->subid >= mySubid)
     562                 :             :             {
     563                 :             :                 /*
     564                 :             :                  * If we used SPI_freetuptable() here, its internal search of
     565                 :             :                  * the tuptables list would make this operation O(N^2).
     566                 :             :                  * Instead, just free the tuptable manually.  This should
     567                 :             :                  * match what SPI_freetuptable() does.
     568                 :             :                  */
     569                 :        2970 :                 slist_delete_current(&siter);
     570         [ +  + ]:        2970 :                 if (tuptable == _SPI_current->tuptable)
     571                 :        2966 :                     _SPI_current->tuptable = NULL;
     572         [ +  + ]:        2970 :                 if (tuptable == SPI_tuptable)
     573                 :           4 :                     SPI_tuptable = NULL;
     574                 :        2970 :                 MemoryContextDelete(tuptable->tuptabcxt);
     575                 :             :             }
     576                 :             :         }
     577                 :             :     }
     578                 :       23152 : }
     579                 :             : 
     580                 :             : /*
     581                 :             :  * Are we executing inside a procedure (that is, a nonatomic SPI context)?
     582                 :             :  */
     583                 :             : bool
     584                 :      658022 : SPI_inside_nonatomic_context(void)
     585                 :             : {
     586         [ +  + ]:      658022 :     if (_SPI_current == NULL)
     587                 :      655682 :         return false;           /* not in any SPI context at all */
     588                 :             :     /* these tests must match _SPI_commit's opinion of what's atomic: */
     589         [ -  + ]:        2340 :     if (_SPI_current->atomic)
     590                 :           0 :         return false;           /* it's atomic (ie function not procedure) */
     591         [ -  + ]:        2340 :     if (IsSubTransaction())
     592                 :           0 :         return false;           /* if within subtransaction, it's atomic */
     593                 :        2340 :     return true;
     594                 :             : }
     595                 :             : 
     596                 :             : 
     597                 :             : /* Parse, plan, and execute a query string */
     598                 :             : int
     599                 :         860 : SPI_execute(const char *src, bool read_only, long tcount)
     600                 :             : {
     601                 :             :     _SPI_plan   plan;
     602                 :             :     SPIExecuteOptions options;
     603                 :             :     int         res;
     604                 :             : 
     605   [ +  -  -  + ]:         860 :     if (src == NULL || tcount < 0)
     606                 :           0 :         return SPI_ERROR_ARGUMENT;
     607                 :             : 
     608                 :         860 :     res = _SPI_begin_call(true);
     609         [ -  + ]:         860 :     if (res < 0)
     610                 :           0 :         return res;
     611                 :             : 
     612                 :         860 :     memset(&plan, 0, sizeof(_SPI_plan));
     613                 :         860 :     plan.magic = _SPI_PLAN_MAGIC;
     614                 :         860 :     plan.parse_mode = RAW_PARSE_DEFAULT;
     615                 :         860 :     plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
     616                 :             : 
     617                 :         860 :     _SPI_prepare_oneshot_plan(src, &plan);
     618                 :             : 
     619                 :         852 :     memset(&options, 0, sizeof(options));
     620                 :         852 :     options.read_only = read_only;
     621                 :         852 :     options.tcount = tcount;
     622                 :             : 
     623                 :         852 :     res = _SPI_execute_plan(&plan, &options,
     624                 :             :                             InvalidSnapshot, InvalidSnapshot,
     625                 :             :                             true);
     626                 :             : 
     627                 :         825 :     _SPI_end_call(true);
     628                 :         825 :     return res;
     629                 :             : }
     630                 :             : 
     631                 :             : /* Obsolete version of SPI_execute */
     632                 :             : int
     633                 :         325 : SPI_exec(const char *src, long tcount)
     634                 :             : {
     635                 :         325 :     return SPI_execute(src, false, tcount);
     636                 :             : }
     637                 :             : 
     638                 :             : /* Parse, plan, and execute a query string, with extensible options */
     639                 :             : int
     640                 :       13471 : SPI_execute_extended(const char *src,
     641                 :             :                      const SPIExecuteOptions *options)
     642                 :             : {
     643                 :             :     int         res;
     644                 :             :     _SPI_plan   plan;
     645                 :             : 
     646   [ +  -  -  + ]:       13471 :     if (src == NULL || options == NULL)
     647                 :           0 :         return SPI_ERROR_ARGUMENT;
     648                 :             : 
     649                 :       13471 :     res = _SPI_begin_call(true);
     650         [ -  + ]:       13471 :     if (res < 0)
     651                 :           0 :         return res;
     652                 :             : 
     653                 :       13471 :     memset(&plan, 0, sizeof(_SPI_plan));
     654                 :       13471 :     plan.magic = _SPI_PLAN_MAGIC;
     655                 :       13471 :     plan.parse_mode = RAW_PARSE_DEFAULT;
     656                 :       13471 :     plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
     657         [ +  + ]:       13471 :     if (options->params)
     658                 :             :     {
     659                 :         289 :         plan.parserSetup = options->params->parserSetup;
     660                 :         289 :         plan.parserSetupArg = options->params->parserSetupArg;
     661                 :             :     }
     662                 :             : 
     663                 :       13471 :     _SPI_prepare_oneshot_plan(src, &plan);
     664                 :             : 
     665                 :       13471 :     res = _SPI_execute_plan(&plan, options,
     666                 :             :                             InvalidSnapshot, InvalidSnapshot,
     667                 :             :                             true);
     668                 :             : 
     669                 :       13297 :     _SPI_end_call(true);
     670                 :       13297 :     return res;
     671                 :             : }
     672                 :             : 
     673                 :             : /* Execute a previously prepared plan */
     674                 :             : int
     675                 :        2645 : SPI_execute_plan(SPIPlanPtr plan, const Datum *Values, const char *Nulls,
     676                 :             :                  bool read_only, long tcount)
     677                 :             : {
     678                 :             :     SPIExecuteOptions options;
     679                 :             :     int         res;
     680                 :             : 
     681   [ +  -  +  -  :        2645 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
                   -  + ]
     682                 :           0 :         return SPI_ERROR_ARGUMENT;
     683                 :             : 
     684   [ +  +  -  + ]:        2645 :     if (plan->nargs > 0 && Values == NULL)
     685                 :           0 :         return SPI_ERROR_PARAM;
     686                 :             : 
     687                 :        2645 :     res = _SPI_begin_call(true);
     688         [ -  + ]:        2645 :     if (res < 0)
     689                 :           0 :         return res;
     690                 :             : 
     691                 :        2645 :     memset(&options, 0, sizeof(options));
     692                 :        2645 :     options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
     693                 :             :                                          Values, Nulls);
     694                 :        2645 :     options.read_only = read_only;
     695                 :        2645 :     options.tcount = tcount;
     696                 :             : 
     697                 :        2645 :     res = _SPI_execute_plan(plan, &options,
     698                 :             :                             InvalidSnapshot, InvalidSnapshot,
     699                 :             :                             true);
     700                 :             : 
     701                 :        2643 :     _SPI_end_call(true);
     702                 :        2643 :     return res;
     703                 :             : }
     704                 :             : 
     705                 :             : /* Obsolete version of SPI_execute_plan */
     706                 :             : int
     707                 :           0 : SPI_execp(SPIPlanPtr plan, const Datum *Values, const char *Nulls, long tcount)
     708                 :             : {
     709                 :           0 :     return SPI_execute_plan(plan, Values, Nulls, false, tcount);
     710                 :             : }
     711                 :             : 
     712                 :             : /* Execute a previously prepared plan */
     713                 :             : int
     714                 :        1748 : SPI_execute_plan_extended(SPIPlanPtr plan,
     715                 :             :                           const SPIExecuteOptions *options)
     716                 :             : {
     717                 :             :     int         res;
     718                 :             : 
     719   [ +  -  +  -  :        1748 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || options == NULL)
                   -  + ]
     720                 :           0 :         return SPI_ERROR_ARGUMENT;
     721                 :             : 
     722                 :        1748 :     res = _SPI_begin_call(true);
     723         [ -  + ]:        1748 :     if (res < 0)
     724                 :           0 :         return res;
     725                 :             : 
     726                 :        1748 :     res = _SPI_execute_plan(plan, options,
     727                 :             :                             InvalidSnapshot, InvalidSnapshot,
     728                 :             :                             true);
     729                 :             : 
     730                 :        1738 :     _SPI_end_call(true);
     731                 :        1738 :     return res;
     732                 :             : }
     733                 :             : 
     734                 :             : /* Execute a previously prepared plan */
     735                 :             : int
     736                 :       63692 : SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params,
     737                 :             :                                 bool read_only, long tcount)
     738                 :             : {
     739                 :             :     SPIExecuteOptions options;
     740                 :             :     int         res;
     741                 :             : 
     742   [ +  -  +  -  :       63692 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
                   -  + ]
     743                 :           0 :         return SPI_ERROR_ARGUMENT;
     744                 :             : 
     745                 :       63692 :     res = _SPI_begin_call(true);
     746         [ -  + ]:       63692 :     if (res < 0)
     747                 :           0 :         return res;
     748                 :             : 
     749                 :       63692 :     memset(&options, 0, sizeof(options));
     750                 :       63692 :     options.params = params;
     751                 :       63692 :     options.read_only = read_only;
     752                 :       63692 :     options.tcount = tcount;
     753                 :             : 
     754                 :       63692 :     res = _SPI_execute_plan(plan, &options,
     755                 :             :                             InvalidSnapshot, InvalidSnapshot,
     756                 :             :                             true);
     757                 :             : 
     758                 :       60516 :     _SPI_end_call(true);
     759                 :       60516 :     return res;
     760                 :             : }
     761                 :             : 
     762                 :             : /*
     763                 :             :  * SPI_execute_snapshot -- identical to SPI_execute_plan, except that we allow
     764                 :             :  * the caller to specify exactly which snapshots to use, which will be
     765                 :             :  * registered here.  Also, the caller may specify that AFTER triggers should be
     766                 :             :  * queued as part of the outer query rather than being fired immediately at the
     767                 :             :  * end of the command.
     768                 :             :  *
     769                 :             :  * This is currently not documented in spi.sgml because it is only intended
     770                 :             :  * for use by RI triggers.
     771                 :             :  *
     772                 :             :  * Passing snapshot == InvalidSnapshot will select the normal behavior of
     773                 :             :  * fetching a new snapshot for each query.
     774                 :             :  */
     775                 :             : int
     776                 :        3565 : SPI_execute_snapshot(SPIPlanPtr plan,
     777                 :             :                      const Datum *Values, const char *Nulls,
     778                 :             :                      Snapshot snapshot, Snapshot crosscheck_snapshot,
     779                 :             :                      bool read_only, bool fire_triggers, long tcount)
     780                 :             : {
     781                 :             :     SPIExecuteOptions options;
     782                 :             :     int         res;
     783                 :             : 
     784   [ +  -  +  -  :        3565 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
                   -  + ]
     785                 :           0 :         return SPI_ERROR_ARGUMENT;
     786                 :             : 
     787   [ +  +  -  + ]:        3565 :     if (plan->nargs > 0 && Values == NULL)
     788                 :           0 :         return SPI_ERROR_PARAM;
     789                 :             : 
     790                 :        3565 :     res = _SPI_begin_call(true);
     791         [ -  + ]:        3565 :     if (res < 0)
     792                 :           0 :         return res;
     793                 :             : 
     794                 :        3565 :     memset(&options, 0, sizeof(options));
     795                 :        3565 :     options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
     796                 :             :                                          Values, Nulls);
     797                 :        3565 :     options.read_only = read_only;
     798                 :        3565 :     options.tcount = tcount;
     799                 :             : 
     800                 :        3565 :     res = _SPI_execute_plan(plan, &options,
     801                 :             :                             snapshot, crosscheck_snapshot,
     802                 :             :                             fire_triggers);
     803                 :             : 
     804                 :        3411 :     _SPI_end_call(true);
     805                 :        3411 :     return res;
     806                 :             : }
     807                 :             : 
     808                 :             : /*
     809                 :             :  * SPI_execute_with_args -- plan and execute a query with supplied arguments
     810                 :             :  *
     811                 :             :  * This is functionally equivalent to SPI_prepare followed by
     812                 :             :  * SPI_execute_plan.
     813                 :             :  */
     814                 :             : int
     815                 :           0 : SPI_execute_with_args(const char *src,
     816                 :             :                       int nargs, const Oid *argtypes,
     817                 :             :                       const Datum *Values, const char *Nulls,
     818                 :             :                       bool read_only, long tcount)
     819                 :             : {
     820                 :             :     int         res;
     821                 :             :     _SPI_plan   plan;
     822                 :             :     ParamListInfo paramLI;
     823                 :             :     SPIExecuteOptions options;
     824                 :             : 
     825   [ #  #  #  #  :           0 :     if (src == NULL || nargs < 0 || tcount < 0)
                   #  # ]
     826                 :           0 :         return SPI_ERROR_ARGUMENT;
     827                 :             : 
     828   [ #  #  #  #  :           0 :     if (nargs > 0 && (argtypes == NULL || Values == NULL))
                   #  # ]
     829                 :           0 :         return SPI_ERROR_PARAM;
     830                 :             : 
     831                 :           0 :     res = _SPI_begin_call(true);
     832         [ #  # ]:           0 :     if (res < 0)
     833                 :           0 :         return res;
     834                 :             : 
     835                 :           0 :     memset(&plan, 0, sizeof(_SPI_plan));
     836                 :           0 :     plan.magic = _SPI_PLAN_MAGIC;
     837                 :           0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
     838                 :           0 :     plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
     839                 :           0 :     plan.nargs = nargs;
     840                 :           0 :     plan.argtypes = argtypes;
     841                 :           0 :     plan.parserSetup = NULL;
     842                 :           0 :     plan.parserSetupArg = NULL;
     843                 :             : 
     844                 :           0 :     paramLI = _SPI_convert_params(nargs, argtypes,
     845                 :             :                                   Values, Nulls);
     846                 :             : 
     847                 :           0 :     _SPI_prepare_oneshot_plan(src, &plan);
     848                 :             : 
     849                 :           0 :     memset(&options, 0, sizeof(options));
     850                 :           0 :     options.params = paramLI;
     851                 :           0 :     options.read_only = read_only;
     852                 :           0 :     options.tcount = tcount;
     853                 :             : 
     854                 :           0 :     res = _SPI_execute_plan(&plan, &options,
     855                 :             :                             InvalidSnapshot, InvalidSnapshot,
     856                 :             :                             true);
     857                 :             : 
     858                 :           0 :     _SPI_end_call(true);
     859                 :           0 :     return res;
     860                 :             : }
     861                 :             : 
     862                 :             : SPIPlanPtr
     863                 :        2608 : SPI_prepare(const char *src, int nargs, const Oid *argtypes)
     864                 :             : {
     865                 :        2608 :     return SPI_prepare_cursor(src, nargs, argtypes, 0);
     866                 :             : }
     867                 :             : 
     868                 :             : SPIPlanPtr
     869                 :        2608 : SPI_prepare_cursor(const char *src, int nargs, const Oid *argtypes,
     870                 :             :                    int cursorOptions)
     871                 :             : {
     872                 :             :     _SPI_plan   plan;
     873                 :             :     SPIPlanPtr  result;
     874                 :             : 
     875   [ +  -  +  -  :        2608 :     if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
             +  +  -  + ]
     876                 :             :     {
     877                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
     878                 :           0 :         return NULL;
     879                 :             :     }
     880                 :             : 
     881                 :        2608 :     SPI_result = _SPI_begin_call(true);
     882         [ -  + ]:        2608 :     if (SPI_result < 0)
     883                 :           0 :         return NULL;
     884                 :             : 
     885                 :        2608 :     memset(&plan, 0, sizeof(_SPI_plan));
     886                 :        2608 :     plan.magic = _SPI_PLAN_MAGIC;
     887                 :        2608 :     plan.parse_mode = RAW_PARSE_DEFAULT;
     888                 :        2608 :     plan.cursor_options = cursorOptions;
     889                 :        2608 :     plan.nargs = nargs;
     890                 :        2608 :     plan.argtypes = argtypes;
     891                 :        2608 :     plan.parserSetup = NULL;
     892                 :        2608 :     plan.parserSetupArg = NULL;
     893                 :             : 
     894                 :        2608 :     _SPI_prepare_plan(src, &plan);
     895                 :             : 
     896                 :             :     /* copy plan to procedure context */
     897                 :        2607 :     result = _SPI_make_plan_non_temp(&plan);
     898                 :             : 
     899                 :        2607 :     _SPI_end_call(true);
     900                 :             : 
     901                 :        2607 :     return result;
     902                 :             : }
     903                 :             : 
     904                 :             : SPIPlanPtr
     905                 :       18737 : SPI_prepare_extended(const char *src,
     906                 :             :                      const SPIPrepareOptions *options)
     907                 :             : {
     908                 :             :     _SPI_plan   plan;
     909                 :             :     SPIPlanPtr  result;
     910                 :             : 
     911   [ +  -  -  + ]:       18737 :     if (src == NULL || options == NULL)
     912                 :             :     {
     913                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
     914                 :           0 :         return NULL;
     915                 :             :     }
     916                 :             : 
     917                 :       18737 :     SPI_result = _SPI_begin_call(true);
     918         [ -  + ]:       18737 :     if (SPI_result < 0)
     919                 :           0 :         return NULL;
     920                 :             : 
     921                 :       18737 :     memset(&plan, 0, sizeof(_SPI_plan));
     922                 :       18737 :     plan.magic = _SPI_PLAN_MAGIC;
     923                 :       18737 :     plan.parse_mode = options->parseMode;
     924                 :       18737 :     plan.cursor_options = options->cursorOptions;
     925                 :       18737 :     plan.nargs = 0;
     926                 :       18737 :     plan.argtypes = NULL;
     927                 :       18737 :     plan.parserSetup = options->parserSetup;
     928                 :       18737 :     plan.parserSetupArg = options->parserSetupArg;
     929                 :             : 
     930                 :       18737 :     _SPI_prepare_plan(src, &plan);
     931                 :             : 
     932                 :             :     /* copy plan to procedure context */
     933                 :       18676 :     result = _SPI_make_plan_non_temp(&plan);
     934                 :             : 
     935                 :       18676 :     _SPI_end_call(true);
     936                 :             : 
     937                 :       18676 :     return result;
     938                 :             : }
     939                 :             : 
     940                 :             : SPIPlanPtr
     941                 :           0 : SPI_prepare_params(const char *src,
     942                 :             :                    ParserSetupHook parserSetup,
     943                 :             :                    void *parserSetupArg,
     944                 :             :                    int cursorOptions)
     945                 :             : {
     946                 :             :     _SPI_plan   plan;
     947                 :             :     SPIPlanPtr  result;
     948                 :             : 
     949         [ #  # ]:           0 :     if (src == NULL)
     950                 :             :     {
     951                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
     952                 :           0 :         return NULL;
     953                 :             :     }
     954                 :             : 
     955                 :           0 :     SPI_result = _SPI_begin_call(true);
     956         [ #  # ]:           0 :     if (SPI_result < 0)
     957                 :           0 :         return NULL;
     958                 :             : 
     959                 :           0 :     memset(&plan, 0, sizeof(_SPI_plan));
     960                 :           0 :     plan.magic = _SPI_PLAN_MAGIC;
     961                 :           0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
     962                 :           0 :     plan.cursor_options = cursorOptions;
     963                 :           0 :     plan.nargs = 0;
     964                 :           0 :     plan.argtypes = NULL;
     965                 :           0 :     plan.parserSetup = parserSetup;
     966                 :           0 :     plan.parserSetupArg = parserSetupArg;
     967                 :             : 
     968                 :           0 :     _SPI_prepare_plan(src, &plan);
     969                 :             : 
     970                 :             :     /* copy plan to procedure context */
     971                 :           0 :     result = _SPI_make_plan_non_temp(&plan);
     972                 :             : 
     973                 :           0 :     _SPI_end_call(true);
     974                 :             : 
     975                 :           0 :     return result;
     976                 :             : }
     977                 :             : 
     978                 :             : int
     979                 :       20290 : SPI_keepplan(SPIPlanPtr plan)
     980                 :             : {
     981                 :             :     ListCell   *lc;
     982                 :             : 
     983   [ +  -  +  - ]:       20290 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
     984   [ +  -  -  + ]:       20290 :         plan->saved || plan->oneshot)
     985                 :           0 :         return SPI_ERROR_ARGUMENT;
     986                 :             : 
     987                 :             :     /*
     988                 :             :      * Mark it saved, reparent it under CacheMemoryContext, and mark all the
     989                 :             :      * component CachedPlanSources as saved.  This sequence cannot fail
     990                 :             :      * partway through, so there's no risk of long-term memory leakage.
     991                 :             :      */
     992                 :       20290 :     plan->saved = true;
     993                 :       20290 :     MemoryContextSetParent(plan->plancxt, CacheMemoryContext);
     994                 :             : 
     995   [ +  -  +  +  :       40580 :     foreach(lc, plan->plancache_list)
                   +  + ]
     996                 :             :     {
     997                 :       20290 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
     998                 :             : 
     999                 :       20290 :         SaveCachedPlan(plansource);
    1000                 :             :     }
    1001                 :             : 
    1002                 :       20290 :     return 0;
    1003                 :             : }
    1004                 :             : 
    1005                 :             : SPIPlanPtr
    1006                 :           0 : SPI_saveplan(SPIPlanPtr plan)
    1007                 :             : {
    1008                 :             :     SPIPlanPtr  newplan;
    1009                 :             : 
    1010   [ #  #  #  # ]:           0 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
    1011                 :             :     {
    1012                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1013                 :           0 :         return NULL;
    1014                 :             :     }
    1015                 :             : 
    1016                 :           0 :     SPI_result = _SPI_begin_call(false);    /* don't change context */
    1017         [ #  # ]:           0 :     if (SPI_result < 0)
    1018                 :           0 :         return NULL;
    1019                 :             : 
    1020                 :           0 :     newplan = _SPI_save_plan(plan);
    1021                 :             : 
    1022                 :           0 :     SPI_result = _SPI_end_call(false);
    1023                 :             : 
    1024                 :           0 :     return newplan;
    1025                 :             : }
    1026                 :             : 
    1027                 :             : int
    1028                 :        5569 : SPI_freeplan(SPIPlanPtr plan)
    1029                 :             : {
    1030                 :             :     ListCell   *lc;
    1031                 :             : 
    1032   [ +  -  -  + ]:        5569 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
    1033                 :           0 :         return SPI_ERROR_ARGUMENT;
    1034                 :             : 
    1035                 :             :     /* Release the plancache entries */
    1036   [ +  -  +  +  :       11138 :     foreach(lc, plan->plancache_list)
                   +  + ]
    1037                 :             :     {
    1038                 :        5569 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
    1039                 :             : 
    1040                 :        5569 :         DropCachedPlan(plansource);
    1041                 :             :     }
    1042                 :             : 
    1043                 :             :     /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
    1044                 :        5569 :     MemoryContextDelete(plan->plancxt);
    1045                 :             : 
    1046                 :        5569 :     return 0;
    1047                 :             : }
    1048                 :             : 
    1049                 :             : HeapTuple
    1050                 :        1413 : SPI_copytuple(HeapTuple tuple)
    1051                 :             : {
    1052                 :             :     MemoryContext oldcxt;
    1053                 :             :     HeapTuple   ctuple;
    1054                 :             : 
    1055         [ -  + ]:        1413 :     if (tuple == NULL)
    1056                 :             :     {
    1057                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1058                 :           0 :         return NULL;
    1059                 :             :     }
    1060                 :             : 
    1061         [ -  + ]:        1413 :     if (_SPI_current == NULL)
    1062                 :             :     {
    1063                 :           0 :         SPI_result = SPI_ERROR_UNCONNECTED;
    1064                 :           0 :         return NULL;
    1065                 :             :     }
    1066                 :             : 
    1067                 :        1413 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
    1068                 :             : 
    1069                 :        1413 :     ctuple = heap_copytuple(tuple);
    1070                 :             : 
    1071                 :        1413 :     MemoryContextSwitchTo(oldcxt);
    1072                 :             : 
    1073                 :        1413 :     return ctuple;
    1074                 :             : }
    1075                 :             : 
    1076                 :             : HeapTupleHeader
    1077                 :       11278 : SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
    1078                 :             : {
    1079                 :             :     MemoryContext oldcxt;
    1080                 :             :     HeapTupleHeader dtup;
    1081                 :             : 
    1082   [ +  -  -  + ]:       11278 :     if (tuple == NULL || tupdesc == NULL)
    1083                 :             :     {
    1084                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1085                 :           0 :         return NULL;
    1086                 :             :     }
    1087                 :             : 
    1088         [ -  + ]:       11278 :     if (_SPI_current == NULL)
    1089                 :             :     {
    1090                 :           0 :         SPI_result = SPI_ERROR_UNCONNECTED;
    1091                 :           0 :         return NULL;
    1092                 :             :     }
    1093                 :             : 
    1094                 :             :     /* For RECORD results, make sure a typmod has been assigned */
    1095         [ +  + ]:       11278 :     if (tupdesc->tdtypeid == RECORDOID &&
    1096         [ -  + ]:        3261 :         tupdesc->tdtypmod < 0)
    1097                 :           0 :         assign_record_type_typmod(tupdesc);
    1098                 :             : 
    1099                 :       11278 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
    1100                 :             : 
    1101                 :             :     /*
    1102                 :             :      * NB: This could "launder" an "outdated" input tuple, stamping it with
    1103                 :             :      * the current version of the tupledesc used here. But we can't really do
    1104                 :             :      * a good job protecting against that here, because we don't have the
    1105                 :             :      * "original" tupledesc to check against. Existing callers all seem fine.
    1106                 :             :      */
    1107                 :             : 
    1108                 :       11278 :     dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
    1109                 :             : 
    1110                 :       11278 :     MemoryContextSwitchTo(oldcxt);
    1111                 :             : 
    1112                 :       11278 :     return dtup;
    1113                 :             : }
    1114                 :             : 
    1115                 :             : HeapTuple
    1116                 :           0 : SPI_modifytuple(Relation rel, HeapTuple tuple, int natts, const int *attnum,
    1117                 :             :                 const Datum *Values, const char *Nulls)
    1118                 :             : {
    1119                 :             :     MemoryContext oldcxt;
    1120                 :             :     HeapTuple   mtuple;
    1121                 :             :     int         numberOfAttributes;
    1122                 :             :     Datum      *v;
    1123                 :             :     bool       *n;
    1124                 :             :     int         i;
    1125                 :             : 
    1126   [ #  #  #  #  :           0 :     if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
          #  #  #  #  #  
                      # ]
    1127                 :             :     {
    1128                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1129                 :           0 :         return NULL;
    1130                 :             :     }
    1131                 :             : 
    1132         [ #  # ]:           0 :     if (_SPI_current == NULL)
    1133                 :             :     {
    1134                 :           0 :         SPI_result = SPI_ERROR_UNCONNECTED;
    1135                 :           0 :         return NULL;
    1136                 :             :     }
    1137                 :             : 
    1138                 :           0 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
    1139                 :             : 
    1140                 :           0 :     SPI_result = 0;
    1141                 :             : 
    1142                 :           0 :     numberOfAttributes = rel->rd_att->natts;
    1143                 :           0 :     v = palloc_array(Datum, numberOfAttributes);
    1144                 :           0 :     n = palloc_array(bool, numberOfAttributes);
    1145                 :             : 
    1146                 :             :     /* fetch old values and nulls */
    1147                 :           0 :     heap_deform_tuple(tuple, rel->rd_att, v, n);
    1148                 :             : 
    1149                 :             :     /* replace values and nulls */
    1150         [ #  # ]:           0 :     for (i = 0; i < natts; i++)
    1151                 :             :     {
    1152   [ #  #  #  # ]:           0 :         if (attnum[i] <= 0 || attnum[i] > numberOfAttributes)
    1153                 :             :             break;
    1154                 :           0 :         v[attnum[i] - 1] = Values[i];
    1155   [ #  #  #  # ]:           0 :         n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n');
    1156                 :             :     }
    1157                 :             : 
    1158         [ #  # ]:           0 :     if (i == natts)             /* no errors in *attnum */
    1159                 :             :     {
    1160                 :           0 :         mtuple = heap_form_tuple(rel->rd_att, v, n);
    1161                 :             : 
    1162                 :             :         /*
    1163                 :             :          * Copy the identification info of the old tuple: t_self, and OID (if
    1164                 :             :          * any). If the source is not a versioned tuple and has a valid
    1165                 :             :          * t_ctid, also copy t_ctid, which makes mtuple an unversioned datum.
    1166                 :             :          *
    1167                 :             :          * This is not optimal behavior, but this function is effectively
    1168                 :             :          * unused (there seem to be no out-of-core extensions using it when
    1169                 :             :          * building against a recent PG and there's no in-core user), so it
    1170                 :             :          * doesn't seem worth doing more.
    1171                 :             :          */
    1172   [ #  #  #  # ]:           0 :         if (!HeapTupleHeaderIsVersionedDatum(tuple->t_data) &&
    1173                 :           0 :             ItemPointerIsValid(&tuple->t_data->t_ctid))
    1174                 :           0 :             mtuple->t_data->t_ctid = tuple->t_data->t_ctid;
    1175                 :           0 :         mtuple->t_self = tuple->t_self;
    1176                 :           0 :         mtuple->t_tableOid = tuple->t_tableOid;
    1177                 :             :     }
    1178                 :             :     else
    1179                 :             :     {
    1180                 :           0 :         mtuple = NULL;
    1181                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1182                 :             :     }
    1183                 :             : 
    1184                 :           0 :     pfree(v);
    1185                 :           0 :     pfree(n);
    1186                 :             : 
    1187                 :           0 :     MemoryContextSwitchTo(oldcxt);
    1188                 :             : 
    1189                 :           0 :     return mtuple;
    1190                 :             : }
    1191                 :             : 
    1192                 :             : int
    1193                 :       13109 : SPI_fnumber(TupleDesc tupdesc, const char *fname)
    1194                 :             : {
    1195                 :             :     int         res;
    1196                 :             :     const FormData_pg_attribute *sysatt;
    1197                 :             : 
    1198         [ +  + ]:       70933 :     for (res = 0; res < tupdesc->natts; res++)
    1199                 :             :     {
    1200                 :       70926 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, res);
    1201                 :             : 
    1202         [ +  + ]:       70926 :         if (namestrcmp(&attr->attname, fname) == 0 &&
    1203         [ +  - ]:       13102 :             !attr->attisdropped)
    1204                 :       13102 :             return res + 1;
    1205                 :             :     }
    1206                 :             : 
    1207                 :           7 :     sysatt = SystemAttributeByName(fname);
    1208         [ -  + ]:           7 :     if (sysatt != NULL)
    1209                 :           0 :         return sysatt->attnum;
    1210                 :             : 
    1211                 :             :     /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
    1212                 :           7 :     return SPI_ERROR_NOATTRIBUTE;
    1213                 :             : }
    1214                 :             : 
    1215                 :             : char *
    1216                 :         644 : SPI_fname(TupleDesc tupdesc, int fnumber)
    1217                 :             : {
    1218                 :             :     const FormData_pg_attribute *att;
    1219                 :             : 
    1220                 :         644 :     SPI_result = 0;
    1221                 :             : 
    1222   [ +  -  +  -  :         644 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                   -  + ]
    1223                 :             :         fnumber <= FirstLowInvalidHeapAttributeNumber)
    1224                 :             :     {
    1225                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1226                 :           0 :         return NULL;
    1227                 :             :     }
    1228                 :             : 
    1229         [ +  - ]:         644 :     if (fnumber > 0)
    1230                 :         644 :         att = TupleDescAttr(tupdesc, fnumber - 1);
    1231                 :             :     else
    1232                 :           0 :         att = SystemAttributeDefinition(fnumber);
    1233                 :             : 
    1234                 :         644 :     return pstrdup(NameStr(att->attname));
    1235                 :             : }
    1236                 :             : 
    1237                 :             : char *
    1238                 :        5609 : SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
    1239                 :             : {
    1240                 :             :     Datum       val;
    1241                 :             :     bool        isnull;
    1242                 :             :     Oid         typoid,
    1243                 :             :                 foutoid;
    1244                 :             :     bool        typisvarlena;
    1245                 :             : 
    1246                 :        5609 :     SPI_result = 0;
    1247                 :             : 
    1248   [ +  -  +  -  :        5609 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                   -  + ]
    1249                 :             :         fnumber <= FirstLowInvalidHeapAttributeNumber)
    1250                 :             :     {
    1251                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1252                 :           0 :         return NULL;
    1253                 :             :     }
    1254                 :             : 
    1255                 :        5609 :     val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
    1256         [ +  + ]:        5609 :     if (isnull)
    1257                 :          66 :         return NULL;
    1258                 :             : 
    1259         [ +  - ]:        5543 :     if (fnumber > 0)
    1260                 :        5543 :         typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
    1261                 :             :     else
    1262                 :           0 :         typoid = (SystemAttributeDefinition(fnumber))->atttypid;
    1263                 :             : 
    1264                 :        5543 :     getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
    1265                 :             : 
    1266                 :        5543 :     return OidOutputFunctionCall(foutoid, val);
    1267                 :             : }
    1268                 :             : 
    1269                 :             : Datum
    1270                 :       36104 : SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
    1271                 :             : {
    1272                 :       36104 :     SPI_result = 0;
    1273                 :             : 
    1274   [ +  -  +  -  :       36104 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                   -  + ]
    1275                 :             :         fnumber <= FirstLowInvalidHeapAttributeNumber)
    1276                 :             :     {
    1277                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1278                 :           0 :         *isnull = true;
    1279                 :           0 :         return (Datum) 0;
    1280                 :             :     }
    1281                 :             : 
    1282                 :       36104 :     return heap_getattr(tuple, fnumber, tupdesc, isnull);
    1283                 :             : }
    1284                 :             : 
    1285                 :             : char *
    1286                 :           0 : SPI_gettype(TupleDesc tupdesc, int fnumber)
    1287                 :             : {
    1288                 :             :     Oid         typoid;
    1289                 :             :     HeapTuple   typeTuple;
    1290                 :             :     char       *result;
    1291                 :             : 
    1292                 :           0 :     SPI_result = 0;
    1293                 :             : 
    1294   [ #  #  #  #  :           0 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                   #  # ]
    1295                 :             :         fnumber <= FirstLowInvalidHeapAttributeNumber)
    1296                 :             :     {
    1297                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1298                 :           0 :         return NULL;
    1299                 :             :     }
    1300                 :             : 
    1301         [ #  # ]:           0 :     if (fnumber > 0)
    1302                 :           0 :         typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
    1303                 :             :     else
    1304                 :           0 :         typoid = (SystemAttributeDefinition(fnumber))->atttypid;
    1305                 :             : 
    1306                 :           0 :     typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
    1307                 :             : 
    1308         [ #  # ]:           0 :     if (!HeapTupleIsValid(typeTuple))
    1309                 :             :     {
    1310                 :           0 :         SPI_result = SPI_ERROR_TYPUNKNOWN;
    1311                 :           0 :         return NULL;
    1312                 :             :     }
    1313                 :             : 
    1314                 :           0 :     result = pstrdup(NameStr(((Form_pg_type) GETSTRUCT(typeTuple))->typname));
    1315                 :           0 :     ReleaseSysCache(typeTuple);
    1316                 :           0 :     return result;
    1317                 :             : }
    1318                 :             : 
    1319                 :             : /*
    1320                 :             :  * Get the data type OID for a column.
    1321                 :             :  *
    1322                 :             :  * There's nothing similar for typmod and typcollation.  The rare consumers
    1323                 :             :  * thereof should inspect the TupleDesc directly.
    1324                 :             :  */
    1325                 :             : Oid
    1326                 :         782 : SPI_gettypeid(TupleDesc tupdesc, int fnumber)
    1327                 :             : {
    1328                 :         782 :     SPI_result = 0;
    1329                 :             : 
    1330   [ +  -  +  -  :         782 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                   -  + ]
    1331                 :             :         fnumber <= FirstLowInvalidHeapAttributeNumber)
    1332                 :             :     {
    1333                 :           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
    1334                 :           0 :         return InvalidOid;
    1335                 :             :     }
    1336                 :             : 
    1337         [ +  - ]:         782 :     if (fnumber > 0)
    1338                 :         782 :         return TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
    1339                 :             :     else
    1340                 :           0 :         return (SystemAttributeDefinition(fnumber))->atttypid;
    1341                 :             : }
    1342                 :             : 
    1343                 :             : char *
    1344                 :         187 : SPI_getrelname(Relation rel)
    1345                 :             : {
    1346                 :         187 :     return pstrdup(RelationGetRelationName(rel));
    1347                 :             : }
    1348                 :             : 
    1349                 :             : char *
    1350                 :         143 : SPI_getnspname(Relation rel)
    1351                 :             : {
    1352                 :         143 :     return get_namespace_name(RelationGetNamespace(rel));
    1353                 :             : }
    1354                 :             : 
    1355                 :             : void *
    1356                 :          28 : SPI_palloc(Size size)
    1357                 :             : {
    1358         [ -  + ]:          28 :     if (_SPI_current == NULL)
    1359         [ #  # ]:           0 :         elog(ERROR, "SPI_palloc called while not connected to SPI");
    1360                 :             : 
    1361                 :          28 :     return MemoryContextAlloc(_SPI_current->savedcxt, size);
    1362                 :             : }
    1363                 :             : 
    1364                 :             : void *
    1365                 :           0 : SPI_repalloc(void *pointer, Size size)
    1366                 :             : {
    1367                 :             :     /* No longer need to worry which context chunk was in... */
    1368                 :           0 :     return repalloc(pointer, size);
    1369                 :             : }
    1370                 :             : 
    1371                 :             : void
    1372                 :           0 : SPI_pfree(void *pointer)
    1373                 :             : {
    1374                 :             :     /* No longer need to worry which context chunk was in... */
    1375                 :           0 :     pfree(pointer);
    1376                 :           0 : }
    1377                 :             : 
    1378                 :             : Datum
    1379                 :        3737 : SPI_datumTransfer(Datum value, bool typByVal, int typLen)
    1380                 :             : {
    1381                 :             :     MemoryContext oldcxt;
    1382                 :             :     Datum       result;
    1383                 :             : 
    1384         [ -  + ]:        3737 :     if (_SPI_current == NULL)
    1385         [ #  # ]:           0 :         elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
    1386                 :             : 
    1387                 :        3737 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
    1388                 :             : 
    1389                 :        3737 :     result = datumTransfer(value, typByVal, typLen);
    1390                 :             : 
    1391                 :        3737 :     MemoryContextSwitchTo(oldcxt);
    1392                 :             : 
    1393                 :        3737 :     return result;
    1394                 :             : }
    1395                 :             : 
    1396                 :             : void
    1397                 :           0 : SPI_freetuple(HeapTuple tuple)
    1398                 :             : {
    1399                 :             :     /* No longer need to worry which context tuple was in... */
    1400                 :           0 :     heap_freetuple(tuple);
    1401                 :           0 : }
    1402                 :             : 
    1403                 :             : void
    1404                 :      142679 : SPI_freetuptable(SPITupleTable *tuptable)
    1405                 :             : {
    1406                 :      142679 :     bool        found = false;
    1407                 :             : 
    1408                 :             :     /* ignore call if NULL pointer */
    1409         [ +  + ]:      142679 :     if (tuptable == NULL)
    1410                 :       88552 :         return;
    1411                 :             : 
    1412                 :             :     /*
    1413                 :             :      * Search only the topmost SPI context for a matching tuple table.
    1414                 :             :      */
    1415         [ +  - ]:       54127 :     if (_SPI_current != NULL)
    1416                 :             :     {
    1417                 :             :         slist_mutable_iter siter;
    1418                 :             : 
    1419                 :             :         /* find tuptable in active list, then remove it */
    1420   [ +  -  +  -  :       54129 :         slist_foreach_modify(siter, &_SPI_current->tuptables)
                   +  - ]
    1421                 :             :         {
    1422                 :             :             SPITupleTable *tt;
    1423                 :             : 
    1424                 :       54129 :             tt = slist_container(SPITupleTable, next, siter.cur);
    1425         [ +  + ]:       54129 :             if (tt == tuptable)
    1426                 :             :             {
    1427                 :       54127 :                 slist_delete_current(&siter);
    1428                 :       54127 :                 found = true;
    1429                 :       54127 :                 break;
    1430                 :             :             }
    1431                 :             :         }
    1432                 :             :     }
    1433                 :             : 
    1434                 :             :     /*
    1435                 :             :      * Refuse the deletion if we didn't find it in the topmost SPI context.
    1436                 :             :      * This is primarily a guard against double deletion, but might prevent
    1437                 :             :      * other errors as well.  Since the worst consequence of not deleting a
    1438                 :             :      * tuptable would be a transient memory leak, this is just a WARNING.
    1439                 :             :      */
    1440         [ -  + ]:       54127 :     if (!found)
    1441                 :             :     {
    1442         [ #  # ]:           0 :         elog(WARNING, "attempt to delete invalid SPITupleTable %p", tuptable);
    1443                 :           0 :         return;
    1444                 :             :     }
    1445                 :             : 
    1446                 :             :     /* for safety, reset global variables that might point at tuptable */
    1447         [ -  + ]:       54127 :     if (tuptable == _SPI_current->tuptable)
    1448                 :           0 :         _SPI_current->tuptable = NULL;
    1449         [ +  + ]:       54127 :     if (tuptable == SPI_tuptable)
    1450                 :       48884 :         SPI_tuptable = NULL;
    1451                 :             : 
    1452                 :             :     /* release all memory belonging to tuptable */
    1453                 :       54127 :     MemoryContextDelete(tuptable->tuptabcxt);
    1454                 :             : }
    1455                 :             : 
    1456                 :             : 
    1457                 :             : /*
    1458                 :             :  * SPI_cursor_open()
    1459                 :             :  *
    1460                 :             :  *  Open a prepared SPI plan as a portal
    1461                 :             :  */
    1462                 :             : Portal
    1463                 :         133 : SPI_cursor_open(const char *name, SPIPlanPtr plan,
    1464                 :             :                 const Datum *Values, const char *Nulls,
    1465                 :             :                 bool read_only)
    1466                 :             : {
    1467                 :             :     Portal      portal;
    1468                 :             :     ParamListInfo paramLI;
    1469                 :             : 
    1470                 :             :     /* build transient ParamListInfo in caller's context */
    1471                 :         133 :     paramLI = _SPI_convert_params(plan->nargs, plan->argtypes,
    1472                 :             :                                   Values, Nulls);
    1473                 :             : 
    1474                 :         133 :     portal = SPI_cursor_open_internal(name, plan, paramLI, read_only);
    1475                 :             : 
    1476                 :             :     /* done with the transient ParamListInfo */
    1477         [ +  + ]:         133 :     if (paramLI)
    1478                 :           4 :         pfree(paramLI);
    1479                 :             : 
    1480                 :         133 :     return portal;
    1481                 :             : }
    1482                 :             : 
    1483                 :             : 
    1484                 :             : /*
    1485                 :             :  * SPI_cursor_open_with_args()
    1486                 :             :  *
    1487                 :             :  * Parse and plan a query and open it as a portal.
    1488                 :             :  */
    1489                 :             : Portal
    1490                 :           0 : SPI_cursor_open_with_args(const char *name,
    1491                 :             :                           const char *src,
    1492                 :             :                           int nargs, const Oid *argtypes,
    1493                 :             :                           const Datum *Values, const char *Nulls,
    1494                 :             :                           bool read_only, int cursorOptions)
    1495                 :             : {
    1496                 :             :     Portal      result;
    1497                 :             :     _SPI_plan   plan;
    1498                 :             :     ParamListInfo paramLI;
    1499                 :             : 
    1500   [ #  #  #  # ]:           0 :     if (src == NULL || nargs < 0)
    1501         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_open_with_args called with invalid arguments");
    1502                 :             : 
    1503   [ #  #  #  #  :           0 :     if (nargs > 0 && (argtypes == NULL || Values == NULL))
                   #  # ]
    1504         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_open_with_args called with missing parameters");
    1505                 :             : 
    1506                 :           0 :     SPI_result = _SPI_begin_call(true);
    1507         [ #  # ]:           0 :     if (SPI_result < 0)
    1508         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_open_with_args called while not connected");
    1509                 :             : 
    1510                 :           0 :     memset(&plan, 0, sizeof(_SPI_plan));
    1511                 :           0 :     plan.magic = _SPI_PLAN_MAGIC;
    1512                 :           0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
    1513                 :           0 :     plan.cursor_options = cursorOptions;
    1514                 :           0 :     plan.nargs = nargs;
    1515                 :           0 :     plan.argtypes = argtypes;
    1516                 :           0 :     plan.parserSetup = NULL;
    1517                 :           0 :     plan.parserSetupArg = NULL;
    1518                 :             : 
    1519                 :             :     /* build transient ParamListInfo in executor context */
    1520                 :           0 :     paramLI = _SPI_convert_params(nargs, argtypes,
    1521                 :             :                                   Values, Nulls);
    1522                 :             : 
    1523                 :           0 :     _SPI_prepare_plan(src, &plan);
    1524                 :             : 
    1525                 :             :     /* We needn't copy the plan; SPI_cursor_open_internal will do so */
    1526                 :             : 
    1527                 :           0 :     result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
    1528                 :             : 
    1529                 :             :     /* And clean up */
    1530                 :           0 :     _SPI_end_call(true);
    1531                 :             : 
    1532                 :           0 :     return result;
    1533                 :             : }
    1534                 :             : 
    1535                 :             : 
    1536                 :             : /*
    1537                 :             :  * SPI_cursor_open_with_paramlist()
    1538                 :             :  *
    1539                 :             :  *  Same as SPI_cursor_open except that parameters (if any) are passed
    1540                 :             :  *  as a ParamListInfo, which supports dynamic parameter set determination
    1541                 :             :  */
    1542                 :             : Portal
    1543                 :        1838 : SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan,
    1544                 :             :                                ParamListInfo params, bool read_only)
    1545                 :             : {
    1546                 :        1838 :     return SPI_cursor_open_internal(name, plan, params, read_only);
    1547                 :             : }
    1548                 :             : 
    1549                 :             : /* Parse a query and open it as a cursor */
    1550                 :             : Portal
    1551                 :        6370 : SPI_cursor_parse_open(const char *name,
    1552                 :             :                       const char *src,
    1553                 :             :                       const SPIParseOpenOptions *options)
    1554                 :             : {
    1555                 :             :     Portal      result;
    1556                 :             :     _SPI_plan   plan;
    1557                 :             : 
    1558   [ +  -  -  + ]:        6370 :     if (src == NULL || options == NULL)
    1559         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_parse_open called with invalid arguments");
    1560                 :             : 
    1561                 :        6370 :     SPI_result = _SPI_begin_call(true);
    1562         [ -  + ]:        6370 :     if (SPI_result < 0)
    1563         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_parse_open called while not connected");
    1564                 :             : 
    1565                 :        6370 :     memset(&plan, 0, sizeof(_SPI_plan));
    1566                 :        6370 :     plan.magic = _SPI_PLAN_MAGIC;
    1567                 :        6370 :     plan.parse_mode = RAW_PARSE_DEFAULT;
    1568                 :        6370 :     plan.cursor_options = options->cursorOptions;
    1569         [ +  + ]:        6370 :     if (options->params)
    1570                 :             :     {
    1571                 :           8 :         plan.parserSetup = options->params->parserSetup;
    1572                 :           8 :         plan.parserSetupArg = options->params->parserSetupArg;
    1573                 :             :     }
    1574                 :             : 
    1575                 :        6370 :     _SPI_prepare_plan(src, &plan);
    1576                 :             : 
    1577                 :             :     /* We needn't copy the plan; SPI_cursor_open_internal will do so */
    1578                 :             : 
    1579                 :        6370 :     result = SPI_cursor_open_internal(name, &plan,
    1580                 :        6370 :                                       options->params, options->read_only);
    1581                 :             : 
    1582                 :             :     /* And clean up */
    1583                 :        6370 :     _SPI_end_call(true);
    1584                 :             : 
    1585                 :        6370 :     return result;
    1586                 :             : }
    1587                 :             : 
    1588                 :             : 
    1589                 :             : /*
    1590                 :             :  * SPI_cursor_open_internal()
    1591                 :             :  *
    1592                 :             :  *  Common code for SPI_cursor_open variants
    1593                 :             :  */
    1594                 :             : static Portal
    1595                 :        8341 : SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
    1596                 :             :                          ParamListInfo paramLI, bool read_only)
    1597                 :             : {
    1598                 :             :     CachedPlanSource *plansource;
    1599                 :             :     CachedPlan *cplan;
    1600                 :             :     List       *stmt_list;
    1601                 :             :     char       *query_string;
    1602                 :             :     Snapshot    snapshot;
    1603                 :             :     MemoryContext oldcontext;
    1604                 :             :     Portal      portal;
    1605                 :             :     SPICallbackArg spicallbackarg;
    1606                 :             :     ErrorContextCallback spierrcontext;
    1607                 :             : 
    1608                 :             :     /*
    1609                 :             :      * Check that the plan is something the Portal code will special-case as
    1610                 :             :      * returning one tupleset.
    1611                 :             :      */
    1612         [ -  + ]:        8341 :     if (!SPI_is_cursor_plan(plan))
    1613                 :             :     {
    1614                 :             :         /* try to give a good error message */
    1615                 :             :         const char *cmdtag;
    1616                 :             : 
    1617         [ #  # ]:           0 :         if (list_length(plan->plancache_list) != 1)
    1618         [ #  # ]:           0 :             ereport(ERROR,
    1619                 :             :                     (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
    1620                 :             :                      errmsg("cannot open multi-query plan as cursor")));
    1621                 :           0 :         plansource = (CachedPlanSource *) linitial(plan->plancache_list);
    1622                 :             :         /* A SELECT that fails SPI_is_cursor_plan() must be SELECT INTO */
    1623         [ #  # ]:           0 :         if (plansource->commandTag == CMDTAG_SELECT)
    1624                 :           0 :             cmdtag = "SELECT INTO";
    1625                 :             :         else
    1626                 :           0 :             cmdtag = GetCommandTagName(plansource->commandTag);
    1627         [ #  # ]:           0 :         ereport(ERROR,
    1628                 :             :                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
    1629                 :             :         /* translator: %s is name of a SQL command, eg INSERT */
    1630                 :             :                  errmsg("cannot open %s query as cursor", cmdtag)));
    1631                 :             :     }
    1632                 :             : 
    1633                 :             :     Assert(list_length(plan->plancache_list) == 1);
    1634                 :        8341 :     plansource = (CachedPlanSource *) linitial(plan->plancache_list);
    1635                 :             : 
    1636                 :             :     /* Push the SPI stack */
    1637         [ -  + ]:        8341 :     if (_SPI_begin_call(true) < 0)
    1638         [ #  # ]:           0 :         elog(ERROR, "SPI_cursor_open called while not connected");
    1639                 :             : 
    1640                 :             :     /* Reset SPI result (note we deliberately don't touch lastoid) */
    1641                 :        8341 :     SPI_processed = 0;
    1642                 :        8341 :     SPI_tuptable = NULL;
    1643                 :        8341 :     _SPI_current->processed = 0;
    1644                 :        8341 :     _SPI_current->tuptable = NULL;
    1645                 :             : 
    1646                 :             :     /* Create the portal */
    1647   [ +  +  -  + ]:        8341 :     if (name == NULL || name[0] == '\0')
    1648                 :             :     {
    1649                 :             :         /* Use a random nonconflicting name */
    1650                 :        8281 :         portal = CreateNewPortal();
    1651                 :             :     }
    1652                 :             :     else
    1653                 :             :     {
    1654                 :             :         /* In this path, error if portal of same name already exists */
    1655                 :          60 :         portal = CreatePortal(name, false, false);
    1656                 :             :     }
    1657                 :             : 
    1658                 :             :     /* Copy the plan's query string into the portal */
    1659                 :        8341 :     query_string = MemoryContextStrdup(portal->portalContext,
    1660                 :             :                                        plansource->query_string);
    1661                 :             : 
    1662                 :             :     /*
    1663                 :             :      * Setup error traceback support for ereport(), in case GetCachedPlan
    1664                 :             :      * throws an error.
    1665                 :             :      */
    1666                 :        8341 :     spicallbackarg.query = plansource->query_string;
    1667                 :        8341 :     spicallbackarg.mode = plan->parse_mode;
    1668                 :        8341 :     spierrcontext.callback = _SPI_error_callback;
    1669                 :        8341 :     spierrcontext.arg = &spicallbackarg;
    1670                 :        8341 :     spierrcontext.previous = error_context_stack;
    1671                 :        8341 :     error_context_stack = &spierrcontext;
    1672                 :             : 
    1673                 :             :     /*
    1674                 :             :      * Note: for a saved plan, we mustn't have any failure occur between
    1675                 :             :      * GetCachedPlan and PortalDefineQuery; that would result in leaking our
    1676                 :             :      * plancache refcount.
    1677                 :             :      */
    1678                 :             : 
    1679                 :             :     /* Replan if needed, and increment plan refcount for portal */
    1680                 :        8341 :     cplan = GetCachedPlan(plansource, paramLI, NULL, _SPI_current->queryEnv);
    1681                 :        8337 :     stmt_list = cplan->stmt_list;
    1682                 :             : 
    1683         [ +  + ]:        8337 :     if (!plan->saved)
    1684                 :             :     {
    1685                 :             :         /*
    1686                 :             :          * We don't want the portal to depend on an unsaved CachedPlanSource,
    1687                 :             :          * so must copy the plan into the portal's context.  An error here
    1688                 :             :          * will result in leaking our refcount on the plan, but it doesn't
    1689                 :             :          * matter because the plan is unsaved and hence transient anyway.
    1690                 :             :          */
    1691                 :        6497 :         oldcontext = MemoryContextSwitchTo(portal->portalContext);
    1692                 :        6497 :         stmt_list = copyObject(stmt_list);
    1693                 :        6497 :         MemoryContextSwitchTo(oldcontext);
    1694                 :        6497 :         ReleaseCachedPlan(cplan, NULL);
    1695                 :        6497 :         cplan = NULL;           /* portal shouldn't depend on cplan */
    1696                 :             :     }
    1697                 :             : 
    1698                 :             :     /*
    1699                 :             :      * Set up the portal.
    1700                 :             :      */
    1701                 :        8337 :     PortalDefineQuery(portal,
    1702                 :             :                       NULL,     /* no statement name */
    1703                 :             :                       query_string,
    1704                 :             :                       plansource->commandTag,
    1705                 :             :                       stmt_list,
    1706                 :             :                       cplan);
    1707                 :             : 
    1708                 :             :     /*
    1709                 :             :      * Set up options for portal.  Default SCROLL type is chosen the same way
    1710                 :             :      * as PerformCursorOpen does it.
    1711                 :             :      */
    1712                 :        8337 :     portal->cursorOptions = plan->cursor_options;
    1713         [ +  + ]:        8337 :     if (!(portal->cursorOptions & (CURSOR_OPT_SCROLL | CURSOR_OPT_NO_SCROLL)))
    1714                 :             :     {
    1715         [ +  - ]:         298 :         if (list_length(stmt_list) == 1 &&
    1716         [ +  - ]:         298 :             linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
    1717   [ +  +  +  + ]:         587 :             linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
    1718                 :         289 :             ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
    1719                 :         264 :             portal->cursorOptions |= CURSOR_OPT_SCROLL;
    1720                 :             :         else
    1721                 :          34 :             portal->cursorOptions |= CURSOR_OPT_NO_SCROLL;
    1722                 :             :     }
    1723                 :             : 
    1724                 :             :     /*
    1725                 :             :      * Disallow SCROLL with SELECT FOR UPDATE.  This is not redundant with the
    1726                 :             :      * check in transformDeclareCursorStmt because the cursor options might
    1727                 :             :      * not have come through there.
    1728                 :             :      */
    1729         [ +  + ]:        8337 :     if (portal->cursorOptions & CURSOR_OPT_SCROLL)
    1730                 :             :     {
    1731         [ +  - ]:         281 :         if (list_length(stmt_list) == 1 &&
    1732         [ +  - ]:         281 :             linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
    1733         [ -  + ]:         281 :             linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
    1734         [ #  # ]:           0 :             ereport(ERROR,
    1735                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1736                 :             :                      errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
    1737                 :             :                      errdetail("Scrollable cursors must be READ ONLY.")));
    1738                 :             :     }
    1739                 :             : 
    1740                 :             :     /* Make current query environment available to portal at execution time. */
    1741                 :        8337 :     portal->queryEnv = _SPI_current->queryEnv;
    1742                 :             : 
    1743                 :             :     /*
    1744                 :             :      * If told to be read-only, we'd better check for read-only queries. This
    1745                 :             :      * can't be done earlier because we need to look at the finished, planned
    1746                 :             :      * queries.  (In particular, we don't want to do it between GetCachedPlan
    1747                 :             :      * and PortalDefineQuery, because throwing an error between those steps
    1748                 :             :      * would result in leaking our plancache refcount.)
    1749                 :             :      */
    1750         [ +  + ]:        8337 :     if (read_only)
    1751                 :             :     {
    1752                 :             :         ListCell   *lc;
    1753                 :             : 
    1754   [ +  -  +  +  :         216 :         foreach(lc, stmt_list)
                   +  + ]
    1755                 :             :         {
    1756                 :         112 :             PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
    1757                 :             : 
    1758         [ +  + ]:         112 :             if (!CommandIsReadOnly(pstmt))
    1759         [ +  - ]:           8 :                 ereport(ERROR,
    1760                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1761                 :             :                 /* translator: %s is a SQL statement name */
    1762                 :             :                          errmsg("%s is not allowed in a non-volatile function",
    1763                 :             :                                 CreateCommandName((Node *) pstmt))));
    1764                 :             :         }
    1765                 :             :     }
    1766                 :             : 
    1767                 :             :     /* Set up the snapshot to use. */
    1768         [ +  + ]:        8329 :     if (read_only)
    1769                 :         104 :         snapshot = GetActiveSnapshot();
    1770                 :             :     else
    1771                 :             :     {
    1772                 :        8225 :         CommandCounterIncrement();
    1773                 :        8225 :         snapshot = GetTransactionSnapshot();
    1774                 :             :     }
    1775                 :             : 
    1776                 :             :     /*
    1777                 :             :      * If the plan has parameters, copy them into the portal.  Note that this
    1778                 :             :      * must be done after revalidating the plan, because in dynamic parameter
    1779                 :             :      * cases the set of parameters could have changed during re-parsing.
    1780                 :             :      */
    1781         [ +  + ]:        8329 :     if (paramLI)
    1782                 :             :     {
    1783                 :         461 :         oldcontext = MemoryContextSwitchTo(portal->portalContext);
    1784                 :         461 :         paramLI = copyParamList(paramLI);
    1785                 :         461 :         MemoryContextSwitchTo(oldcontext);
    1786                 :             :     }
    1787                 :             : 
    1788                 :             :     /*
    1789                 :             :      * Start portal execution.
    1790                 :             :      */
    1791                 :        8329 :     PortalStart(portal, paramLI, 0, snapshot);
    1792                 :             : 
    1793                 :             :     Assert(portal->strategy != PORTAL_MULTI_QUERY);
    1794                 :             : 
    1795                 :             :     /* Pop the error context stack */
    1796                 :        8325 :     error_context_stack = spierrcontext.previous;
    1797                 :             : 
    1798                 :             :     /* Pop the SPI stack */
    1799                 :        8325 :     _SPI_end_call(true);
    1800                 :             : 
    1801                 :             :     /* Return the created portal */
    1802                 :        8325 :     return portal;
    1803                 :             : }
    1804                 :             : 
    1805                 :             : 
    1806                 :             : /*
    1807                 :             :  * SPI_cursor_find()
    1808                 :             :  *
    1809                 :             :  *  Find the portal of an existing open cursor
    1810                 :             :  */
    1811                 :             : Portal
    1812                 :         414 : SPI_cursor_find(const char *name)
    1813                 :             : {
    1814                 :         414 :     return GetPortalByName(name);
    1815                 :             : }
    1816                 :             : 
    1817                 :             : 
    1818                 :             : /*
    1819                 :             :  * SPI_cursor_fetch()
    1820                 :             :  *
    1821                 :             :  *  Fetch rows in a cursor
    1822                 :             :  */
    1823                 :             : void
    1824                 :       29625 : SPI_cursor_fetch(Portal portal, bool forward, long count)
    1825                 :             : {
    1826                 :       29625 :     _SPI_cursor_operation(portal,
    1827                 :       29625 :                           forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
    1828                 :             :                           CreateDestReceiver(DestSPI));
    1829                 :             :     /* we know that the DestSPI receiver doesn't need a destroy call */
    1830                 :       29616 : }
    1831                 :             : 
    1832                 :             : 
    1833                 :             : /*
    1834                 :             :  * SPI_cursor_move()
    1835                 :             :  *
    1836                 :             :  *  Move in a cursor
    1837                 :             :  */
    1838                 :             : void
    1839                 :           0 : SPI_cursor_move(Portal portal, bool forward, long count)
    1840                 :             : {
    1841                 :           0 :     _SPI_cursor_operation(portal,
    1842                 :           0 :                           forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
    1843                 :             :                           None_Receiver);
    1844                 :           0 : }
    1845                 :             : 
    1846                 :             : 
    1847                 :             : /*
    1848                 :             :  * SPI_scroll_cursor_fetch()
    1849                 :             :  *
    1850                 :             :  *  Fetch rows in a scrollable cursor
    1851                 :             :  */
    1852                 :             : void
    1853                 :         221 : SPI_scroll_cursor_fetch(Portal portal, FetchDirection direction, long count)
    1854                 :             : {
    1855                 :         221 :     _SPI_cursor_operation(portal,
    1856                 :             :                           direction, count,
    1857                 :             :                           CreateDestReceiver(DestSPI));
    1858                 :             :     /* we know that the DestSPI receiver doesn't need a destroy call */
    1859                 :         213 : }
    1860                 :             : 
    1861                 :             : 
    1862                 :             : /*
    1863                 :             :  * SPI_scroll_cursor_move()
    1864                 :             :  *
    1865                 :             :  *  Move in a scrollable cursor
    1866                 :             :  */
    1867                 :             : void
    1868                 :          28 : SPI_scroll_cursor_move(Portal portal, FetchDirection direction, long count)
    1869                 :             : {
    1870                 :          28 :     _SPI_cursor_operation(portal, direction, count, None_Receiver);
    1871                 :          28 : }
    1872                 :             : 
    1873                 :             : 
    1874                 :             : /*
    1875                 :             :  * SPI_cursor_close()
    1876                 :             :  *
    1877                 :             :  *  Close a cursor
    1878                 :             :  */
    1879                 :             : void
    1880                 :        8224 : SPI_cursor_close(Portal portal)
    1881                 :             : {
    1882         [ -  + ]:        8224 :     if (!PortalIsValid(portal))
    1883         [ #  # ]:           0 :         elog(ERROR, "invalid portal in SPI cursor operation");
    1884                 :             : 
    1885                 :        8224 :     PortalDrop(portal, false);
    1886                 :        8224 : }
    1887                 :             : 
    1888                 :             : /*
    1889                 :             :  * Returns the Oid representing the type id for argument at argIndex. First
    1890                 :             :  * parameter is at index zero.
    1891                 :             :  */
    1892                 :             : Oid
    1893                 :           0 : SPI_getargtypeid(SPIPlanPtr plan, int argIndex)
    1894                 :             : {
    1895   [ #  #  #  #  :           0 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
                   #  # ]
    1896         [ #  # ]:           0 :         argIndex < 0 || argIndex >= plan->nargs)
    1897                 :             :     {
    1898                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1899                 :           0 :         return InvalidOid;
    1900                 :             :     }
    1901                 :           0 :     return plan->argtypes[argIndex];
    1902                 :             : }
    1903                 :             : 
    1904                 :             : /*
    1905                 :             :  * Returns the number of arguments for the prepared plan.
    1906                 :             :  */
    1907                 :             : int
    1908                 :           0 : SPI_getargcount(SPIPlanPtr plan)
    1909                 :             : {
    1910   [ #  #  #  # ]:           0 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
    1911                 :             :     {
    1912                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1913                 :           0 :         return -1;
    1914                 :             :     }
    1915                 :           0 :     return plan->nargs;
    1916                 :             : }
    1917                 :             : 
    1918                 :             : /*
    1919                 :             :  * Returns true if the plan contains exactly one command
    1920                 :             :  * and that command returns tuples to the caller (eg, SELECT or
    1921                 :             :  * INSERT ... RETURNING, but not SELECT ... INTO). In essence,
    1922                 :             :  * the result indicates if the command can be used with SPI_cursor_open
    1923                 :             :  *
    1924                 :             :  * Parameters
    1925                 :             :  *    plan: A plan previously prepared using SPI_prepare
    1926                 :             :  */
    1927                 :             : bool
    1928                 :        8341 : SPI_is_cursor_plan(SPIPlanPtr plan)
    1929                 :             : {
    1930                 :             :     CachedPlanSource *plansource;
    1931                 :             : 
    1932   [ +  -  -  + ]:        8341 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
    1933                 :             :     {
    1934                 :           0 :         SPI_result = SPI_ERROR_ARGUMENT;
    1935                 :           0 :         return false;
    1936                 :             :     }
    1937                 :             : 
    1938         [ -  + ]:        8341 :     if (list_length(plan->plancache_list) != 1)
    1939                 :             :     {
    1940                 :           0 :         SPI_result = 0;
    1941                 :           0 :         return false;           /* not exactly 1 pre-rewrite command */
    1942                 :             :     }
    1943                 :        8341 :     plansource = (CachedPlanSource *) linitial(plan->plancache_list);
    1944                 :             : 
    1945                 :             :     /*
    1946                 :             :      * We used to force revalidation of the cached plan here, but that seems
    1947                 :             :      * unnecessary: invalidation could mean a change in the rowtype of the
    1948                 :             :      * tuples returned by a plan, but not whether it returns tuples at all.
    1949                 :             :      */
    1950                 :        8341 :     SPI_result = 0;
    1951                 :             : 
    1952                 :             :     /* Does it return tuples? */
    1953         [ +  - ]:        8341 :     if (plansource->resultDesc)
    1954                 :        8341 :         return true;
    1955                 :             : 
    1956                 :           0 :     return false;
    1957                 :             : }
    1958                 :             : 
    1959                 :             : /*
    1960                 :             :  * SPI_plan_is_valid --- test whether a SPI plan is currently valid
    1961                 :             :  * (that is, not marked as being in need of revalidation).
    1962                 :             :  *
    1963                 :             :  * See notes for CachedPlanIsValid before using this.
    1964                 :             :  */
    1965                 :             : bool
    1966                 :        1675 : SPI_plan_is_valid(SPIPlanPtr plan)
    1967                 :             : {
    1968                 :             :     ListCell   *lc;
    1969                 :             : 
    1970                 :             :     Assert(plan->magic == _SPI_PLAN_MAGIC);
    1971                 :             : 
    1972   [ +  -  +  +  :        3073 :     foreach(lc, plan->plancache_list)
                   +  + ]
    1973                 :             :     {
    1974                 :        1675 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
    1975                 :             : 
    1976         [ +  + ]:        1675 :         if (!CachedPlanIsValid(plansource))
    1977                 :         277 :             return false;
    1978                 :             :     }
    1979                 :        1398 :     return true;
    1980                 :             : }
    1981                 :             : 
    1982                 :             : /*
    1983                 :             :  * SPI_result_code_string --- convert any SPI return code to a string
    1984                 :             :  *
    1985                 :             :  * This is often useful in error messages.  Most callers will probably
    1986                 :             :  * only pass negative (error-case) codes, but for generality we recognize
    1987                 :             :  * the success codes too.
    1988                 :             :  */
    1989                 :             : const char *
    1990                 :          60 : SPI_result_code_string(int code)
    1991                 :             : {
    1992                 :             :     static char buf[64];
    1993                 :             : 
    1994   [ -  -  -  -  :          60 :     switch (code)
          -  -  +  -  -  
          -  -  -  -  -  
          -  +  +  -  +  
          -  -  -  -  -  
          -  -  -  -  -  
                -  -  - ]
    1995                 :             :     {
    1996                 :           0 :         case SPI_ERROR_CONNECT:
    1997                 :           0 :             return "SPI_ERROR_CONNECT";
    1998                 :           0 :         case SPI_ERROR_COPY:
    1999                 :           0 :             return "SPI_ERROR_COPY";
    2000                 :           0 :         case SPI_ERROR_OPUNKNOWN:
    2001                 :           0 :             return "SPI_ERROR_OPUNKNOWN";
    2002                 :           0 :         case SPI_ERROR_UNCONNECTED:
    2003                 :           0 :             return "SPI_ERROR_UNCONNECTED";
    2004                 :           0 :         case SPI_ERROR_ARGUMENT:
    2005                 :           0 :             return "SPI_ERROR_ARGUMENT";
    2006                 :           0 :         case SPI_ERROR_PARAM:
    2007                 :           0 :             return "SPI_ERROR_PARAM";
    2008                 :           3 :         case SPI_ERROR_TRANSACTION:
    2009                 :           3 :             return "SPI_ERROR_TRANSACTION";
    2010                 :           0 :         case SPI_ERROR_NOATTRIBUTE:
    2011                 :           0 :             return "SPI_ERROR_NOATTRIBUTE";
    2012                 :           0 :         case SPI_ERROR_NOOUTFUNC:
    2013                 :           0 :             return "SPI_ERROR_NOOUTFUNC";
    2014                 :           0 :         case SPI_ERROR_TYPUNKNOWN:
    2015                 :           0 :             return "SPI_ERROR_TYPUNKNOWN";
    2016                 :           0 :         case SPI_ERROR_REL_DUPLICATE:
    2017                 :           0 :             return "SPI_ERROR_REL_DUPLICATE";
    2018                 :           0 :         case SPI_ERROR_REL_NOT_FOUND:
    2019                 :           0 :             return "SPI_ERROR_REL_NOT_FOUND";
    2020                 :           0 :         case SPI_OK_CONNECT:
    2021                 :           0 :             return "SPI_OK_CONNECT";
    2022                 :           0 :         case SPI_OK_FINISH:
    2023                 :           0 :             return "SPI_OK_FINISH";
    2024                 :           0 :         case SPI_OK_FETCH:
    2025                 :           0 :             return "SPI_OK_FETCH";
    2026                 :           1 :         case SPI_OK_UTILITY:
    2027                 :           1 :             return "SPI_OK_UTILITY";
    2028                 :          11 :         case SPI_OK_SELECT:
    2029                 :          11 :             return "SPI_OK_SELECT";
    2030                 :           0 :         case SPI_OK_SELINTO:
    2031                 :           0 :             return "SPI_OK_SELINTO";
    2032                 :          45 :         case SPI_OK_INSERT:
    2033                 :          45 :             return "SPI_OK_INSERT";
    2034                 :           0 :         case SPI_OK_DELETE:
    2035                 :           0 :             return "SPI_OK_DELETE";
    2036                 :           0 :         case SPI_OK_UPDATE:
    2037                 :           0 :             return "SPI_OK_UPDATE";
    2038                 :           0 :         case SPI_OK_CURSOR:
    2039                 :           0 :             return "SPI_OK_CURSOR";
    2040                 :           0 :         case SPI_OK_INSERT_RETURNING:
    2041                 :           0 :             return "SPI_OK_INSERT_RETURNING";
    2042                 :           0 :         case SPI_OK_DELETE_RETURNING:
    2043                 :           0 :             return "SPI_OK_DELETE_RETURNING";
    2044                 :           0 :         case SPI_OK_UPDATE_RETURNING:
    2045                 :           0 :             return "SPI_OK_UPDATE_RETURNING";
    2046                 :           0 :         case SPI_OK_REWRITTEN:
    2047                 :           0 :             return "SPI_OK_REWRITTEN";
    2048                 :           0 :         case SPI_OK_REL_REGISTER:
    2049                 :           0 :             return "SPI_OK_REL_REGISTER";
    2050                 :           0 :         case SPI_OK_REL_UNREGISTER:
    2051                 :           0 :             return "SPI_OK_REL_UNREGISTER";
    2052                 :           0 :         case SPI_OK_TD_REGISTER:
    2053                 :           0 :             return "SPI_OK_TD_REGISTER";
    2054                 :           0 :         case SPI_OK_MERGE:
    2055                 :           0 :             return "SPI_OK_MERGE";
    2056                 :           0 :         case SPI_OK_MERGE_RETURNING:
    2057                 :           0 :             return "SPI_OK_MERGE_RETURNING";
    2058                 :             :     }
    2059                 :             :     /* Unrecognized code ... return something useful ... */
    2060                 :           0 :     sprintf(buf, "Unrecognized SPI code %d", code);
    2061                 :           0 :     return buf;
    2062                 :             : }
    2063                 :             : 
    2064                 :             : /*
    2065                 :             :  * SPI_plan_get_plan_sources --- get a SPI plan's underlying list of
    2066                 :             :  * CachedPlanSources.
    2067                 :             :  *
    2068                 :             :  * CAUTION: there is no check on whether the CachedPlanSources are up-to-date.
    2069                 :             :  *
    2070                 :             :  * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
    2071                 :             :  * look directly into the SPIPlan for itself).  It's not documented in
    2072                 :             :  * spi.sgml because we'd just as soon not have too many places using this.
    2073                 :             :  */
    2074                 :             : List *
    2075                 :       40101 : SPI_plan_get_plan_sources(SPIPlanPtr plan)
    2076                 :             : {
    2077                 :             :     Assert(plan->magic == _SPI_PLAN_MAGIC);
    2078                 :       40101 :     return plan->plancache_list;
    2079                 :             : }
    2080                 :             : 
    2081                 :             : /*
    2082                 :             :  * SPI_plan_get_cached_plan --- get a SPI plan's generic CachedPlan,
    2083                 :             :  * if the SPI plan contains exactly one CachedPlanSource.  If not,
    2084                 :             :  * return NULL.
    2085                 :             :  *
    2086                 :             :  * The plan's refcount is incremented (and logged in CurrentResourceOwner,
    2087                 :             :  * if it's a saved plan).  Caller is responsible for doing ReleaseCachedPlan.
    2088                 :             :  *
    2089                 :             :  * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
    2090                 :             :  * look directly into the SPIPlan for itself).  It's not documented in
    2091                 :             :  * spi.sgml because we'd just as soon not have too many places using this.
    2092                 :             :  */
    2093                 :             : CachedPlan *
    2094                 :       19395 : SPI_plan_get_cached_plan(SPIPlanPtr plan)
    2095                 :             : {
    2096                 :             :     CachedPlanSource *plansource;
    2097                 :             :     CachedPlan *cplan;
    2098                 :             :     SPICallbackArg spicallbackarg;
    2099                 :             :     ErrorContextCallback spierrcontext;
    2100                 :             : 
    2101                 :             :     Assert(plan->magic == _SPI_PLAN_MAGIC);
    2102                 :             : 
    2103                 :             :     /* Can't support one-shot plans here */
    2104         [ -  + ]:       19395 :     if (plan->oneshot)
    2105                 :           0 :         return NULL;
    2106                 :             : 
    2107                 :             :     /* Must have exactly one CachedPlanSource */
    2108         [ -  + ]:       19395 :     if (list_length(plan->plancache_list) != 1)
    2109                 :           0 :         return NULL;
    2110                 :       19395 :     plansource = (CachedPlanSource *) linitial(plan->plancache_list);
    2111                 :             : 
    2112                 :             :     /* Setup error traceback support for ereport() */
    2113                 :       19395 :     spicallbackarg.query = plansource->query_string;
    2114                 :       19395 :     spicallbackarg.mode = plan->parse_mode;
    2115                 :       19395 :     spierrcontext.callback = _SPI_error_callback;
    2116                 :       19395 :     spierrcontext.arg = &spicallbackarg;
    2117                 :       19395 :     spierrcontext.previous = error_context_stack;
    2118                 :       19395 :     error_context_stack = &spierrcontext;
    2119                 :             : 
    2120                 :             :     /* Get the generic plan for the query */
    2121                 :       19395 :     cplan = GetCachedPlan(plansource, NULL,
    2122                 :       19395 :                           plan->saved ? CurrentResourceOwner : NULL,
    2123         [ +  + ]:       19395 :                           _SPI_current->queryEnv);
    2124                 :             :     Assert(cplan == plansource->gplan);
    2125                 :             : 
    2126                 :             :     /* Pop the error context stack */
    2127                 :       19366 :     error_context_stack = spierrcontext.previous;
    2128                 :             : 
    2129                 :       19366 :     return cplan;
    2130                 :             : }
    2131                 :             : 
    2132                 :             : 
    2133                 :             : /* =================== private functions =================== */
    2134                 :             : 
    2135                 :             : /*
    2136                 :             :  * spi_dest_startup
    2137                 :             :  *      Initialize to receive tuples from Executor into SPITupleTable
    2138                 :             :  *      of current SPI procedure
    2139                 :             :  */
    2140                 :             : void
    2141                 :       63132 : spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
    2142                 :             : {
    2143                 :             :     SPITupleTable *tuptable;
    2144                 :             :     MemoryContext oldcxt;
    2145                 :             :     MemoryContext tuptabcxt;
    2146                 :             : 
    2147         [ -  + ]:       63132 :     if (_SPI_current == NULL)
    2148         [ #  # ]:           0 :         elog(ERROR, "spi_dest_startup called while not connected to SPI");
    2149                 :             : 
    2150         [ -  + ]:       63132 :     if (_SPI_current->tuptable != NULL)
    2151         [ #  # ]:           0 :         elog(ERROR, "improper call to spi_dest_startup");
    2152                 :             : 
    2153                 :             :     /* We create the tuple table context as a child of procCxt */
    2154                 :             : 
    2155                 :       63132 :     oldcxt = _SPI_procmem();    /* switch to procedure memory context */
    2156                 :             : 
    2157                 :       63132 :     tuptabcxt = AllocSetContextCreate(CurrentMemoryContext,
    2158                 :             :                                       "SPI TupTable",
    2159                 :             :                                       ALLOCSET_DEFAULT_SIZES);
    2160                 :       63132 :     MemoryContextSwitchTo(tuptabcxt);
    2161                 :             : 
    2162                 :       63132 :     _SPI_current->tuptable = tuptable = palloc0_object(SPITupleTable);
    2163                 :       63132 :     tuptable->tuptabcxt = tuptabcxt;
    2164                 :       63132 :     tuptable->subid = GetCurrentSubTransactionId();
    2165                 :             : 
    2166                 :             :     /*
    2167                 :             :      * The tuptable is now valid enough to be freed by AtEOSubXact_SPI, so put
    2168                 :             :      * it onto the SPI context's tuptables list.  This will ensure it's not
    2169                 :             :      * leaked even in the unlikely event the following few lines fail.
    2170                 :             :      */
    2171                 :       63132 :     slist_push_head(&_SPI_current->tuptables, &tuptable->next);
    2172                 :             : 
    2173                 :             :     /* set up initial allocations */
    2174                 :       63132 :     tuptable->alloced = 128;
    2175                 :       63132 :     tuptable->vals = palloc_array(HeapTuple, tuptable->alloced);
    2176                 :       63132 :     tuptable->numvals = 0;
    2177                 :       63132 :     tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
    2178                 :             : 
    2179                 :       63132 :     MemoryContextSwitchTo(oldcxt);
    2180                 :       63132 : }
    2181                 :             : 
    2182                 :             : /*
    2183                 :             :  * spi_printtup
    2184                 :             :  *      store tuple retrieved by Executor into SPITupleTable
    2185                 :             :  *      of current SPI procedure
    2186                 :             :  */
    2187                 :             : bool
    2188                 :       76326 : spi_printtup(TupleTableSlot *slot, DestReceiver *self)
    2189                 :             : {
    2190                 :             :     SPITupleTable *tuptable;
    2191                 :             :     MemoryContext oldcxt;
    2192                 :             : 
    2193         [ -  + ]:       76326 :     if (_SPI_current == NULL)
    2194         [ #  # ]:           0 :         elog(ERROR, "spi_printtup called while not connected to SPI");
    2195                 :             : 
    2196                 :       76326 :     tuptable = _SPI_current->tuptable;
    2197         [ -  + ]:       76326 :     if (tuptable == NULL)
    2198         [ #  # ]:           0 :         elog(ERROR, "improper call to spi_printtup");
    2199                 :             : 
    2200                 :       76326 :     oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
    2201                 :             : 
    2202         [ -  + ]:       76326 :     if (tuptable->numvals >= tuptable->alloced)
    2203                 :             :     {
    2204                 :             :         /* Double the size of the pointer array */
    2205                 :           0 :         uint64      newalloced = tuptable->alloced * 2;
    2206                 :             : 
    2207                 :           0 :         tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
    2208                 :             :                                                      newalloced * sizeof(HeapTuple));
    2209                 :           0 :         tuptable->alloced = newalloced;
    2210                 :             :     }
    2211                 :             : 
    2212                 :       76326 :     tuptable->vals[tuptable->numvals] = ExecCopySlotHeapTuple(slot);
    2213                 :       76326 :     (tuptable->numvals)++;
    2214                 :             : 
    2215                 :       76326 :     MemoryContextSwitchTo(oldcxt);
    2216                 :             : 
    2217                 :       76326 :     return true;
    2218                 :             : }
    2219                 :             : 
    2220                 :             : /*
    2221                 :             :  * Static functions
    2222                 :             :  */
    2223                 :             : 
    2224                 :             : /*
    2225                 :             :  * Parse and analyze a querystring.
    2226                 :             :  *
    2227                 :             :  * At entry, plan->argtypes and plan->nargs (or alternatively plan->parserSetup
    2228                 :             :  * and plan->parserSetupArg) must be valid, as must plan->parse_mode and
    2229                 :             :  * plan->cursor_options.
    2230                 :             :  *
    2231                 :             :  * Results are stored into *plan (specifically, plan->plancache_list).
    2232                 :             :  * Note that the result data is all in CurrentMemoryContext or child contexts
    2233                 :             :  * thereof; in practice this means it is in the SPI executor context, and
    2234                 :             :  * what we are creating is a "temporary" SPIPlan.  Cruft generated during
    2235                 :             :  * parsing is also left in CurrentMemoryContext.
    2236                 :             :  */
    2237                 :             : static void
    2238                 :       27715 : _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
    2239                 :             : {
    2240                 :             :     List       *raw_parsetree_list;
    2241                 :             :     List       *plancache_list;
    2242                 :             :     ListCell   *list_item;
    2243                 :             :     SPICallbackArg spicallbackarg;
    2244                 :             :     ErrorContextCallback spierrcontext;
    2245                 :             : 
    2246                 :             :     /*
    2247                 :             :      * Setup error traceback support for ereport()
    2248                 :             :      */
    2249                 :       27715 :     spicallbackarg.query = src;
    2250                 :       27715 :     spicallbackarg.mode = plan->parse_mode;
    2251                 :       27715 :     spierrcontext.callback = _SPI_error_callback;
    2252                 :       27715 :     spierrcontext.arg = &spicallbackarg;
    2253                 :       27715 :     spierrcontext.previous = error_context_stack;
    2254                 :       27715 :     error_context_stack = &spierrcontext;
    2255                 :             : 
    2256                 :             :     /*
    2257                 :             :      * Parse the request string into a list of raw parse trees.
    2258                 :             :      */
    2259                 :       27715 :     raw_parsetree_list = raw_parser(src, plan->parse_mode);
    2260                 :             : 
    2261                 :             :     /*
    2262                 :             :      * Do parse analysis and rule rewrite for each raw parsetree, storing the
    2263                 :             :      * results into unsaved plancache entries.
    2264                 :             :      */
    2265                 :       27715 :     plancache_list = NIL;
    2266                 :             : 
    2267   [ +  -  +  +  :       55368 :     foreach(list_item, raw_parsetree_list)
                   +  + ]
    2268                 :             :     {
    2269                 :       27715 :         RawStmt    *parsetree = lfirst_node(RawStmt, list_item);
    2270                 :             :         List       *stmt_list;
    2271                 :             :         CachedPlanSource *plansource;
    2272                 :             : 
    2273                 :             :         /*
    2274                 :             :          * Create the CachedPlanSource before we do parse analysis, since it
    2275                 :             :          * needs to see the unmodified raw parse tree.
    2276                 :             :          */
    2277                 :       27715 :         plansource = CreateCachedPlan(parsetree,
    2278                 :             :                                       src,
    2279                 :             :                                       CreateCommandTag(parsetree->stmt));
    2280                 :             : 
    2281                 :             :         /*
    2282                 :             :          * Parameter datatypes are driven by parserSetup hook if provided,
    2283                 :             :          * otherwise we use the fixed parameter list.
    2284                 :             :          */
    2285         [ +  + ]:       27715 :         if (plan->parserSetup != NULL)
    2286                 :             :         {
    2287                 :             :             Assert(plan->nargs == 0);
    2288                 :       18745 :             stmt_list = pg_analyze_and_rewrite_withcb(parsetree,
    2289                 :             :                                                       src,
    2290                 :             :                                                       plan->parserSetup,
    2291                 :             :                                                       plan->parserSetupArg,
    2292                 :       18745 :                                                       _SPI_current->queryEnv);
    2293                 :             :         }
    2294                 :             :         else
    2295                 :             :         {
    2296                 :        8970 :             stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
    2297                 :             :                                                            src,
    2298                 :             :                                                            plan->argtypes,
    2299                 :             :                                                            plan->nargs,
    2300                 :        8970 :                                                            _SPI_current->queryEnv);
    2301                 :             :         }
    2302                 :             : 
    2303                 :             :         /* Finish filling in the CachedPlanSource */
    2304                 :       27653 :         CompleteCachedPlan(plansource,
    2305                 :             :                            stmt_list,
    2306                 :             :                            NULL,
    2307                 :             :                            plan->argtypes,
    2308                 :             :                            plan->nargs,
    2309                 :             :                            plan->parserSetup,
    2310                 :             :                            plan->parserSetupArg,
    2311                 :             :                            plan->cursor_options,
    2312                 :             :                            false);  /* not fixed result */
    2313                 :             : 
    2314                 :       27653 :         plancache_list = lappend(plancache_list, plansource);
    2315                 :             :     }
    2316                 :             : 
    2317                 :       27653 :     plan->plancache_list = plancache_list;
    2318                 :       27653 :     plan->oneshot = false;
    2319                 :             : 
    2320                 :             :     /*
    2321                 :             :      * Pop the error context stack
    2322                 :             :      */
    2323                 :       27653 :     error_context_stack = spierrcontext.previous;
    2324                 :       27653 : }
    2325                 :             : 
    2326                 :             : /*
    2327                 :             :  * Parse, but don't analyze, a querystring.
    2328                 :             :  *
    2329                 :             :  * This is a stripped-down version of _SPI_prepare_plan that only does the
    2330                 :             :  * initial raw parsing.  It creates "one shot" CachedPlanSources
    2331                 :             :  * that still require parse analysis before execution is possible.
    2332                 :             :  *
    2333                 :             :  * The advantage of using the "one shot" form of CachedPlanSource is that
    2334                 :             :  * we eliminate data copying and invalidation overhead.  Postponing parse
    2335                 :             :  * analysis also prevents issues if some of the raw parsetrees are DDL
    2336                 :             :  * commands that affect validity of later parsetrees.  Both of these
    2337                 :             :  * attributes are good things for SPI_execute() and similar cases.
    2338                 :             :  *
    2339                 :             :  * Results are stored into *plan (specifically, plan->plancache_list).
    2340                 :             :  * Note that the result data is all in CurrentMemoryContext or child contexts
    2341                 :             :  * thereof; in practice this means it is in the SPI executor context, and
    2342                 :             :  * what we are creating is a "temporary" SPIPlan.  Cruft generated during
    2343                 :             :  * parsing is also left in CurrentMemoryContext.
    2344                 :             :  */
    2345                 :             : static void
    2346                 :       14331 : _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
    2347                 :             : {
    2348                 :             :     List       *raw_parsetree_list;
    2349                 :             :     List       *plancache_list;
    2350                 :             :     ListCell   *list_item;
    2351                 :             :     SPICallbackArg spicallbackarg;
    2352                 :             :     ErrorContextCallback spierrcontext;
    2353                 :             : 
    2354                 :             :     /*
    2355                 :             :      * Setup error traceback support for ereport()
    2356                 :             :      */
    2357                 :       14331 :     spicallbackarg.query = src;
    2358                 :       14331 :     spicallbackarg.mode = plan->parse_mode;
    2359                 :       14331 :     spierrcontext.callback = _SPI_error_callback;
    2360                 :       14331 :     spierrcontext.arg = &spicallbackarg;
    2361                 :       14331 :     spierrcontext.previous = error_context_stack;
    2362                 :       14331 :     error_context_stack = &spierrcontext;
    2363                 :             : 
    2364                 :             :     /*
    2365                 :             :      * Parse the request string into a list of raw parse trees.
    2366                 :             :      */
    2367                 :       14331 :     raw_parsetree_list = raw_parser(src, plan->parse_mode);
    2368                 :             : 
    2369                 :             :     /*
    2370                 :             :      * Construct plancache entries, but don't do parse analysis yet.
    2371                 :             :      */
    2372                 :       14323 :     plancache_list = NIL;
    2373                 :             : 
    2374   [ +  -  +  +  :       28651 :     foreach(list_item, raw_parsetree_list)
                   +  + ]
    2375                 :             :     {
    2376                 :       14328 :         RawStmt    *parsetree = lfirst_node(RawStmt, list_item);
    2377                 :             :         CachedPlanSource *plansource;
    2378                 :             : 
    2379                 :       14328 :         plansource = CreateOneShotCachedPlan(parsetree,
    2380                 :             :                                              src,
    2381                 :             :                                              CreateCommandTag(parsetree->stmt));
    2382                 :             : 
    2383                 :       14328 :         plancache_list = lappend(plancache_list, plansource);
    2384                 :             :     }
    2385                 :             : 
    2386                 :       14323 :     plan->plancache_list = plancache_list;
    2387                 :       14323 :     plan->oneshot = true;
    2388                 :             : 
    2389                 :             :     /*
    2390                 :             :      * Pop the error context stack
    2391                 :             :      */
    2392                 :       14323 :     error_context_stack = spierrcontext.previous;
    2393                 :       14323 : }
    2394                 :             : 
    2395                 :             : /*
    2396                 :             :  * _SPI_execute_plan: execute the given plan with the given options
    2397                 :             :  *
    2398                 :             :  * options contains options accessible from outside SPI:
    2399                 :             :  * params: parameter values to pass to query
    2400                 :             :  * read_only: true for read-only execution (no CommandCounterIncrement)
    2401                 :             :  * allow_nonatomic: true to allow nonatomic CALL/DO execution
    2402                 :             :  * must_return_tuples: throw error if query doesn't return tuples
    2403                 :             :  * tcount: execution tuple-count limit, or 0 for none
    2404                 :             :  * dest: DestReceiver to receive output, or NULL for normal SPI output
    2405                 :             :  * owner: ResourceOwner that will be used to hold refcount on plan;
    2406                 :             :  *      if NULL, CurrentResourceOwner is used (ignored for non-saved plan)
    2407                 :             :  *
    2408                 :             :  * Additional, only-internally-accessible options:
    2409                 :             :  * snapshot: query snapshot to use, or InvalidSnapshot for the normal
    2410                 :             :  *      behavior of taking a new snapshot for each query.
    2411                 :             :  * crosscheck_snapshot: for RI use, all others pass InvalidSnapshot
    2412                 :             :  * fire_triggers: true to fire AFTER triggers at end of query (normal case);
    2413                 :             :  *      false means any AFTER triggers are postponed to end of outer query
    2414                 :             :  */
    2415                 :             : static int
    2416                 :       85973 : _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
    2417                 :             :                   Snapshot snapshot, Snapshot crosscheck_snapshot,
    2418                 :             :                   bool fire_triggers)
    2419                 :             : {
    2420                 :       85973 :     int         my_res = 0;
    2421                 :       85973 :     uint64      my_processed = 0;
    2422                 :       85973 :     SPITupleTable *my_tuptable = NULL;
    2423                 :       85973 :     int         res = 0;
    2424                 :             :     bool        allow_nonatomic;
    2425                 :       85973 :     bool        pushed_active_snap = false;
    2426                 :       85973 :     ResourceOwner plan_owner = options->owner;
    2427                 :             :     SPICallbackArg spicallbackarg;
    2428                 :             :     ErrorContextCallback spierrcontext;
    2429                 :       85973 :     CachedPlan *cplan = NULL;
    2430                 :             :     ListCell   *lc1;
    2431                 :             : 
    2432                 :             :     /*
    2433                 :             :      * We allow nonatomic behavior only if options->allow_nonatomic is set
    2434                 :             :      * *and* the SPI_OPT_NONATOMIC flag was given when connecting and we are
    2435                 :             :      * not inside a subtransaction.  The latter two tests match whether
    2436                 :             :      * _SPI_commit() would allow a commit; see there for more commentary.
    2437                 :             :      */
    2438                 :      172005 :     allow_nonatomic = options->allow_nonatomic &&
    2439   [ +  +  +  +  :       85973 :         !_SPI_current->atomic && !IsSubTransaction();
                   +  + ]
    2440                 :             : 
    2441                 :             :     /*
    2442                 :             :      * Setup error traceback support for ereport()
    2443                 :             :      */
    2444                 :       85973 :     spicallbackarg.query = NULL;    /* we'll fill this below */
    2445                 :       85973 :     spicallbackarg.mode = plan->parse_mode;
    2446                 :       85973 :     spierrcontext.callback = _SPI_error_callback;
    2447                 :       85973 :     spierrcontext.arg = &spicallbackarg;
    2448                 :       85973 :     spierrcontext.previous = error_context_stack;
    2449                 :       85973 :     error_context_stack = &spierrcontext;
    2450                 :             : 
    2451                 :             :     /*
    2452                 :             :      * We support four distinct snapshot management behaviors:
    2453                 :             :      *
    2454                 :             :      * snapshot != InvalidSnapshot, read_only = true: use exactly the given
    2455                 :             :      * snapshot.
    2456                 :             :      *
    2457                 :             :      * snapshot != InvalidSnapshot, read_only = false: use the given snapshot,
    2458                 :             :      * modified by advancing its command ID before each querytree.
    2459                 :             :      *
    2460                 :             :      * snapshot == InvalidSnapshot, read_only = true: do nothing for queries
    2461                 :             :      * that require no snapshot.  For those that do, ensure that a Portal
    2462                 :             :      * snapshot exists; then use that, or use the entry-time ActiveSnapshot if
    2463                 :             :      * that exists and is different.
    2464                 :             :      *
    2465                 :             :      * snapshot == InvalidSnapshot, read_only = false: do nothing for queries
    2466                 :             :      * that require no snapshot.  For those that do, ensure that a Portal
    2467                 :             :      * snapshot exists; then, in atomic execution (!allow_nonatomic) take a
    2468                 :             :      * full new snapshot for each user command, and advance its command ID
    2469                 :             :      * before each querytree within the command.  In allow_nonatomic mode we
    2470                 :             :      * just use the Portal snapshot unmodified.
    2471                 :             :      *
    2472                 :             :      * In the first two cases, we can just push the snap onto the stack once
    2473                 :             :      * for the whole plan list.
    2474                 :             :      *
    2475                 :             :      * Note that snapshot != InvalidSnapshot implies an atomic execution
    2476                 :             :      * context.
    2477                 :             :      */
    2478         [ +  + ]:       85973 :     if (snapshot != InvalidSnapshot)
    2479                 :             :     {
    2480                 :             :         /* this intentionally tests the options field not the derived value */
    2481                 :             :         Assert(!options->allow_nonatomic);
    2482         [ +  + ]:         828 :         if (options->read_only)
    2483                 :             :         {
    2484                 :         792 :             PushActiveSnapshot(snapshot);
    2485                 :         792 :             pushed_active_snap = true;
    2486                 :             :         }
    2487                 :             :         else
    2488                 :             :         {
    2489                 :             :             /* Make sure we have a private copy of the snapshot to modify */
    2490                 :          36 :             PushCopiedSnapshot(snapshot);
    2491                 :          36 :             pushed_active_snap = true;
    2492                 :             :         }
    2493                 :             :     }
    2494                 :             : 
    2495                 :             :     /*
    2496                 :             :      * Ensure that we have a resource owner if plan is saved, and not if it
    2497                 :             :      * isn't.
    2498                 :             :      */
    2499         [ +  + ]:       85973 :     if (!plan->saved)
    2500                 :       15189 :         plan_owner = NULL;
    2501         [ +  + ]:       70784 :     else if (plan_owner == NULL)
    2502                 :       70729 :         plan_owner = CurrentResourceOwner;
    2503                 :             : 
    2504                 :             :     /*
    2505                 :             :      * We interpret must_return_tuples as "there must be at least one query,
    2506                 :             :      * and all of them must return tuples".  This is a bit laxer than
    2507                 :             :      * SPI_is_cursor_plan's check, but there seems no reason to enforce that
    2508                 :             :      * there be only one query.
    2509                 :             :      */
    2510   [ +  +  -  + ]:       85973 :     if (options->must_return_tuples && plan->plancache_list == NIL)
    2511         [ #  # ]:           0 :         ereport(ERROR,
    2512                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2513                 :             :                  errmsg("empty query does not return tuples")));
    2514                 :             : 
    2515   [ +  -  +  +  :      168398 :     foreach(lc1, plan->plancache_list)
                   +  + ]
    2516                 :             :     {
    2517                 :       85977 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
    2518                 :             :         List       *stmt_list;
    2519                 :             :         ListCell   *lc2;
    2520                 :             : 
    2521                 :       85977 :         spicallbackarg.query = plansource->query_string;
    2522                 :             : 
    2523                 :             :         /*
    2524                 :             :          * If this is a one-shot plan, we still need to do parse analysis.
    2525                 :             :          */
    2526         [ +  + ]:       85977 :         if (plan->oneshot)
    2527                 :             :         {
    2528                 :       14327 :             RawStmt    *parsetree = plansource->raw_parse_tree;
    2529                 :       14327 :             const char *src = plansource->query_string;
    2530                 :             :             List       *querytree_list;
    2531                 :             : 
    2532                 :             :             /*
    2533                 :             :              * Parameter datatypes are driven by parserSetup hook if provided,
    2534                 :             :              * otherwise we use the fixed parameter list.
    2535                 :             :              */
    2536         [ -  + ]:       14327 :             if (parsetree == NULL)
    2537                 :           0 :                 querytree_list = NIL;
    2538         [ +  + ]:       14327 :             else if (plan->parserSetup != NULL)
    2539                 :             :             {
    2540                 :             :                 Assert(plan->nargs == 0);
    2541                 :         289 :                 querytree_list = pg_analyze_and_rewrite_withcb(parsetree,
    2542                 :             :                                                                src,
    2543                 :             :                                                                plan->parserSetup,
    2544                 :             :                                                                plan->parserSetupArg,
    2545                 :         289 :                                                                _SPI_current->queryEnv);
    2546                 :             :             }
    2547                 :             :             else
    2548                 :             :             {
    2549                 :       14038 :                 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree,
    2550                 :             :                                                                     src,
    2551                 :             :                                                                     plan->argtypes,
    2552                 :             :                                                                     plan->nargs,
    2553                 :       14038 :                                                                     _SPI_current->queryEnv);
    2554                 :             :             }
    2555                 :             : 
    2556                 :             :             /* Finish filling in the CachedPlanSource */
    2557                 :       14320 :             CompleteCachedPlan(plansource,
    2558                 :             :                                querytree_list,
    2559                 :             :                                NULL,
    2560                 :             :                                plan->argtypes,
    2561                 :             :                                plan->nargs,
    2562                 :             :                                plan->parserSetup,
    2563                 :             :                                plan->parserSetupArg,
    2564                 :             :                                plan->cursor_options,
    2565                 :             :                                false);  /* not fixed result */
    2566                 :             :         }
    2567                 :             : 
    2568                 :             :         /*
    2569                 :             :          * If asked to, complain when query does not return tuples.
    2570                 :             :          * (Replanning can't change this, so we can check it before that.
    2571                 :             :          * However, we can't check it till after parse analysis, so in the
    2572                 :             :          * case of a one-shot plan this is the earliest we could check.)
    2573                 :             :          */
    2574   [ +  +  +  + ]:       85970 :         if (options->must_return_tuples && !plansource->resultDesc)
    2575                 :             :         {
    2576                 :             :             /* try to give a good error message */
    2577                 :             :             const char *cmdtag;
    2578                 :             : 
    2579                 :             :             /* A SELECT without resultDesc must be SELECT INTO */
    2580         [ +  - ]:           8 :             if (plansource->commandTag == CMDTAG_SELECT)
    2581                 :           8 :                 cmdtag = "SELECT INTO";
    2582                 :             :             else
    2583                 :           0 :                 cmdtag = GetCommandTagName(plansource->commandTag);
    2584         [ +  - ]:           8 :             ereport(ERROR,
    2585                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2586                 :             :             /* translator: %s is name of a SQL command, eg INSERT */
    2587                 :             :                      errmsg("%s query does not return tuples", cmdtag)));
    2588                 :             :         }
    2589                 :             : 
    2590                 :             :         /*
    2591                 :             :          * Replan if needed, and increment plan refcount.  If it's a saved
    2592                 :             :          * plan, the refcount must be backed by the plan_owner.
    2593                 :             :          */
    2594                 :       85962 :         cplan = GetCachedPlan(plansource, options->params,
    2595                 :       85962 :                               plan_owner, _SPI_current->queryEnv);
    2596                 :             : 
    2597                 :       85863 :         stmt_list = cplan->stmt_list;
    2598                 :             : 
    2599                 :             :         /*
    2600                 :             :          * If we weren't given a specific snapshot to use, and the statement
    2601                 :             :          * list requires a snapshot, set that up.
    2602                 :             :          */
    2603   [ +  +  +  - ]:      170898 :         if (snapshot == InvalidSnapshot &&
    2604         [ +  - ]:      170070 :             (list_length(stmt_list) > 1 ||
    2605         [ +  + ]:      170070 :              (list_length(stmt_list) == 1 &&
    2606                 :       85035 :               PlannedStmtRequiresSnapshot(linitial_node(PlannedStmt,
    2607                 :             :                                                         stmt_list)))))
    2608                 :             :         {
    2609                 :             :             /*
    2610                 :             :              * First, ensure there's a Portal-level snapshot.  This back-fills
    2611                 :             :              * the snapshot stack in case the previous operation was a COMMIT
    2612                 :             :              * or ROLLBACK inside a procedure or DO block.  (We can't put back
    2613                 :             :              * the Portal snapshot any sooner, or we'd break cases like doing
    2614                 :             :              * SET or LOCK just after COMMIT.)  It's enough to check once per
    2615                 :             :              * statement list, since COMMIT/ROLLBACK/CALL/DO can't appear
    2616                 :             :              * within a multi-statement list.
    2617                 :             :              */
    2618                 :       76388 :             EnsurePortalSnapshotExists();
    2619                 :             : 
    2620                 :             :             /*
    2621                 :             :              * In the default non-read-only case, get a new per-statement-list
    2622                 :             :              * snapshot, replacing any that we pushed in a previous cycle.
    2623                 :             :              * Skip it when doing non-atomic execution, though (we rely
    2624                 :             :              * entirely on the Portal snapshot in that case).
    2625                 :             :              */
    2626   [ +  +  +  + ]:       76388 :             if (!options->read_only && !allow_nonatomic)
    2627                 :             :             {
    2628         [ +  + ]:       73324 :                 if (pushed_active_snap)
    2629                 :           4 :                     PopActiveSnapshot();
    2630                 :       73324 :                 PushActiveSnapshot(GetTransactionSnapshot());
    2631                 :       73324 :                 pushed_active_snap = true;
    2632                 :             :             }
    2633                 :             :         }
    2634                 :             : 
    2635   [ +  -  +  +  :      168288 :         foreach(lc2, stmt_list)
                   +  + ]
    2636                 :             :         {
    2637                 :       85863 :             PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
    2638                 :       85863 :             bool        canSetTag = stmt->canSetTag;
    2639                 :             :             DestReceiver *dest;
    2640                 :             : 
    2641                 :             :             /*
    2642                 :             :              * Reset output state.  (Note that if a non-SPI receiver is used,
    2643                 :             :              * _SPI_current->processed will stay zero, and that's what we'll
    2644                 :             :              * report to the caller.  It's the receiver's job to count tuples
    2645                 :             :              * in that case.)
    2646                 :             :              */
    2647                 :       85863 :             _SPI_current->processed = 0;
    2648                 :       85863 :             _SPI_current->tuptable = NULL;
    2649                 :             : 
    2650                 :             :             /* Check for unsupported cases. */
    2651         [ +  + ]:       85863 :             if (stmt->utilityStmt)
    2652                 :             :             {
    2653         [ +  + ]:       20140 :                 if (IsA(stmt->utilityStmt, CopyStmt))
    2654                 :             :                 {
    2655                 :           9 :                     CopyStmt   *cstmt = (CopyStmt *) stmt->utilityStmt;
    2656                 :             : 
    2657         [ +  + ]:           9 :                     if (cstmt->filename == NULL)
    2658                 :             :                     {
    2659                 :           4 :                         my_res = SPI_ERROR_COPY;
    2660                 :           9 :                         goto fail;
    2661                 :             :                     }
    2662                 :             :                 }
    2663         [ +  + ]:       20131 :                 else if (IsA(stmt->utilityStmt, TransactionStmt))
    2664                 :             :                 {
    2665                 :           5 :                     my_res = SPI_ERROR_TRANSACTION;
    2666                 :           5 :                     goto fail;
    2667                 :             :                 }
    2668                 :             :             }
    2669                 :             : 
    2670   [ +  +  -  + ]:       85854 :             if (options->read_only && !CommandIsReadOnly(stmt))
    2671         [ #  # ]:           0 :                 ereport(ERROR,
    2672                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2673                 :             :                 /* translator: %s is a SQL statement name */
    2674                 :             :                          errmsg("%s is not allowed in a non-volatile function",
    2675                 :             :                                 CreateCommandName((Node *) stmt))));
    2676                 :             : 
    2677                 :             :             /*
    2678                 :             :              * If not read-only mode, advance the command counter before each
    2679                 :             :              * command and update the snapshot.  (But skip it if the snapshot
    2680                 :             :              * isn't under our control.)
    2681                 :             :              */
    2682   [ +  +  +  + ]:       85854 :             if (!options->read_only && pushed_active_snap)
    2683                 :             :             {
    2684                 :       73356 :                 CommandCounterIncrement();
    2685                 :       73356 :                 UpdateActiveSnapshotCommandId();
    2686                 :             :             }
    2687                 :             : 
    2688                 :             :             /*
    2689                 :             :              * Select appropriate tuple receiver.  Output from non-canSetTag
    2690                 :             :              * subqueries always goes to the bit bucket.
    2691                 :             :              */
    2692         [ -  + ]:       85854 :             if (!canSetTag)
    2693                 :           0 :                 dest = CreateDestReceiver(DestNone);
    2694         [ +  + ]:       85854 :             else if (options->dest)
    2695                 :        1853 :                 dest = options->dest;
    2696                 :             :             else
    2697                 :       84001 :                 dest = CreateDestReceiver(DestSPI);
    2698                 :             : 
    2699         [ +  + ]:       85854 :             if (stmt->utilityStmt == NULL)
    2700                 :             :             {
    2701                 :             :                 QueryDesc  *qdesc;
    2702                 :             :                 Snapshot    snap;
    2703                 :             : 
    2704         [ +  - ]:       65723 :                 if (ActiveSnapshotSet())
    2705                 :       65723 :                     snap = GetActiveSnapshot();
    2706                 :             :                 else
    2707                 :           0 :                     snap = InvalidSnapshot;
    2708                 :             : 
    2709                 :       65723 :                 qdesc = CreateQueryDesc(stmt,
    2710                 :             :                                         plansource->query_string,
    2711                 :             :                                         snap, crosscheck_snapshot,
    2712                 :             :                                         dest,
    2713                 :       65723 :                                         options->params,
    2714                 :       65723 :                                         _SPI_current->queryEnv,
    2715                 :             :                                         0);
    2716         [ +  - ]:       65723 :                 res = _SPI_pquery(qdesc, fire_triggers,
    2717                 :             :                                   canSetTag ? options->tcount : 0);
    2718                 :       62426 :                 FreeQueryDesc(qdesc);
    2719                 :             :             }
    2720                 :             :             else
    2721                 :             :             {
    2722                 :             :                 ProcessUtilityContext context;
    2723                 :             :                 QueryCompletion qc;
    2724                 :             : 
    2725                 :             :                 /*
    2726                 :             :                  * If we're not allowing nonatomic operations, tell
    2727                 :             :                  * ProcessUtility this is an atomic execution context.
    2728                 :             :                  */
    2729         [ +  + ]:       20131 :                 if (allow_nonatomic)
    2730                 :          51 :                     context = PROCESS_UTILITY_QUERY_NONATOMIC;
    2731                 :             :                 else
    2732                 :       20080 :                     context = PROCESS_UTILITY_QUERY;
    2733                 :             : 
    2734                 :       20131 :                 InitializeQueryCompletion(&qc);
    2735                 :       20131 :                 ProcessUtility(stmt,
    2736                 :             :                                plansource->query_string,
    2737                 :             :                                true,    /* protect plancache's node tree */
    2738                 :             :                                context,
    2739                 :       20131 :                                options->params,
    2740                 :       20131 :                                _SPI_current->queryEnv,
    2741                 :             :                                dest,
    2742                 :             :                                &qc);
    2743                 :             : 
    2744                 :             :                 /* Update "processed" if stmt returned tuples */
    2745         [ +  + ]:       19999 :                 if (_SPI_current->tuptable)
    2746                 :        1206 :                     _SPI_current->processed = _SPI_current->tuptable->numvals;
    2747                 :             : 
    2748                 :       19999 :                 res = SPI_OK_UTILITY;
    2749                 :             : 
    2750                 :             :                 /*
    2751                 :             :                  * Some utility statements return a row count, even though the
    2752                 :             :                  * tuples are not returned to the caller.
    2753                 :             :                  */
    2754         [ +  + ]:       19999 :                 if (IsA(stmt->utilityStmt, CreateTableAsStmt))
    2755                 :             :                 {
    2756                 :          33 :                     CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
    2757                 :             : 
    2758         [ +  + ]:          33 :                     if (qc.commandTag == CMDTAG_SELECT)
    2759                 :          29 :                         _SPI_current->processed = qc.nprocessed;
    2760                 :             :                     else
    2761                 :             :                     {
    2762                 :             :                         /*
    2763                 :             :                          * Must be an IF NOT EXISTS that did nothing, or a
    2764                 :             :                          * CREATE ... WITH NO DATA.
    2765                 :             :                          */
    2766                 :             :                         Assert(ctastmt->if_not_exists ||
    2767                 :             :                                ctastmt->into->skipData);
    2768                 :           4 :                         _SPI_current->processed = 0;
    2769                 :             :                     }
    2770                 :             : 
    2771                 :             :                     /*
    2772                 :             :                      * For historical reasons, if CREATE TABLE AS was spelled
    2773                 :             :                      * as SELECT INTO, return a special return code.
    2774                 :             :                      */
    2775         [ -  + ]:          33 :                     if (ctastmt->is_select_into)
    2776                 :           0 :                         res = SPI_OK_SELINTO;
    2777                 :             :                 }
    2778         [ +  + ]:       19966 :                 else if (IsA(stmt->utilityStmt, CopyStmt))
    2779                 :             :                 {
    2780                 :             :                     Assert(qc.commandTag == CMDTAG_COPY);
    2781                 :           5 :                     _SPI_current->processed = qc.nprocessed;
    2782                 :             :                 }
    2783                 :             :             }
    2784                 :             : 
    2785                 :             :             /*
    2786                 :             :              * The last canSetTag query sets the status values returned to the
    2787                 :             :              * caller.  Be careful to free any tuptables not returned, to
    2788                 :             :              * avoid intra-transaction memory leak.
    2789                 :             :              */
    2790         [ +  - ]:       82425 :             if (canSetTag)
    2791                 :             :             {
    2792                 :       82425 :                 my_processed = _SPI_current->processed;
    2793                 :       82425 :                 SPI_freetuptable(my_tuptable);
    2794                 :       82425 :                 my_tuptable = _SPI_current->tuptable;
    2795                 :       82425 :                 my_res = res;
    2796                 :             :             }
    2797                 :             :             else
    2798                 :             :             {
    2799                 :           0 :                 SPI_freetuptable(_SPI_current->tuptable);
    2800                 :           0 :                 _SPI_current->tuptable = NULL;
    2801                 :             :             }
    2802                 :             : 
    2803                 :             :             /*
    2804                 :             :              * We don't issue a destroy call to the receiver.  The SPI and
    2805                 :             :              * None receivers would ignore it anyway, while if the caller
    2806                 :             :              * supplied a receiver, it's not our job to destroy it.
    2807                 :             :              */
    2808                 :             : 
    2809         [ -  + ]:       82425 :             if (res < 0)
    2810                 :             :             {
    2811                 :           0 :                 my_res = res;
    2812                 :           0 :                 goto fail;
    2813                 :             :             }
    2814                 :             :         }
    2815                 :             : 
    2816                 :             :         /* Done with this plan, so release refcount */
    2817                 :       82425 :         ReleaseCachedPlan(cplan, plan_owner);
    2818                 :       82425 :         cplan = NULL;
    2819                 :             : 
    2820                 :             :         /*
    2821                 :             :          * If not read-only mode, advance the command counter after the last
    2822                 :             :          * command.  This ensures that its effects are visible, in case it was
    2823                 :             :          * DDL that would affect the next CachedPlanSource.
    2824                 :             :          */
    2825         [ +  + ]:       82425 :         if (!options->read_only)
    2826                 :       78666 :             CommandCounterIncrement();
    2827                 :             :     }
    2828                 :             : 
    2829                 :       82430 : fail:
    2830                 :             : 
    2831                 :             :     /* Pop the snapshot off the stack if we pushed one */
    2832         [ +  + ]:       82430 :     if (pushed_active_snap)
    2833                 :       70790 :         PopActiveSnapshot();
    2834                 :             : 
    2835                 :             :     /* We no longer need the cached plan refcount, if any */
    2836         [ +  + ]:       82430 :     if (cplan)
    2837                 :           9 :         ReleaseCachedPlan(cplan, plan_owner);
    2838                 :             : 
    2839                 :             :     /*
    2840                 :             :      * Pop the error context stack
    2841                 :             :      */
    2842                 :       82430 :     error_context_stack = spierrcontext.previous;
    2843                 :             : 
    2844                 :             :     /* Save results for caller */
    2845                 :       82430 :     SPI_processed = my_processed;
    2846                 :       82430 :     SPI_tuptable = my_tuptable;
    2847                 :             : 
    2848                 :             :     /* tuptable now is caller's responsibility, not SPI's */
    2849                 :       82430 :     _SPI_current->tuptable = NULL;
    2850                 :             : 
    2851                 :             :     /*
    2852                 :             :      * If none of the queries had canSetTag, return SPI_OK_REWRITTEN. Prior to
    2853                 :             :      * 8.4, we used return the last query's result code, but not its auxiliary
    2854                 :             :      * results, but that's confusing.
    2855                 :             :      */
    2856         [ -  + ]:       82430 :     if (my_res == 0)
    2857                 :           0 :         my_res = SPI_OK_REWRITTEN;
    2858                 :             : 
    2859                 :       82430 :     return my_res;
    2860                 :             : }
    2861                 :             : 
    2862                 :             : /*
    2863                 :             :  * Convert arrays of query parameters to form wanted by planner and executor
    2864                 :             :  */
    2865                 :             : static ParamListInfo
    2866                 :        6343 : _SPI_convert_params(int nargs, const Oid *argtypes,
    2867                 :             :                     const Datum *Values, const char *Nulls)
    2868                 :             : {
    2869                 :             :     ParamListInfo paramLI;
    2870                 :             : 
    2871         [ +  + ]:        6343 :     if (nargs > 0)
    2872                 :             :     {
    2873                 :        5333 :         paramLI = makeParamList(nargs);
    2874                 :             : 
    2875         [ +  + ]:       14158 :         for (int i = 0; i < nargs; i++)
    2876                 :             :         {
    2877                 :        8825 :             ParamExternData *prm = &paramLI->params[i];
    2878                 :             : 
    2879                 :        8825 :             prm->value = Values[i];
    2880   [ +  +  -  + ]:        8825 :             prm->isnull = (Nulls && Nulls[i] == 'n');
    2881                 :        8825 :             prm->pflags = PARAM_FLAG_CONST;
    2882                 :        8825 :             prm->ptype = argtypes[i];
    2883                 :             :         }
    2884                 :             :     }
    2885                 :             :     else
    2886                 :        1010 :         paramLI = NULL;
    2887                 :        6343 :     return paramLI;
    2888                 :             : }
    2889                 :             : 
    2890                 :             : static int
    2891                 :       65723 : _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
    2892                 :             : {
    2893                 :       65723 :     int         operation = queryDesc->operation;
    2894                 :             :     int         eflags;
    2895                 :             :     int         res;
    2896                 :             : 
    2897   [ +  +  +  +  :       65723 :     switch (operation)
                   +  - ]
    2898                 :             :     {
    2899                 :       32804 :         case CMD_SELECT:
    2900         [ -  + ]:       32804 :             if (queryDesc->dest->mydest == DestNone)
    2901                 :             :             {
    2902                 :             :                 /* Don't return SPI_OK_SELECT if we're discarding result */
    2903                 :           0 :                 res = SPI_OK_UTILITY;
    2904                 :             :             }
    2905                 :             :             else
    2906                 :       32804 :                 res = SPI_OK_SELECT;
    2907                 :       32804 :             break;
    2908                 :       25955 :         case CMD_INSERT:
    2909         [ +  + ]:       25955 :             if (queryDesc->plannedstmt->hasReturning)
    2910                 :        1070 :                 res = SPI_OK_INSERT_RETURNING;
    2911                 :             :             else
    2912                 :       24885 :                 res = SPI_OK_INSERT;
    2913                 :       25955 :             break;
    2914                 :        5821 :         case CMD_DELETE:
    2915         [ -  + ]:        5821 :             if (queryDesc->plannedstmt->hasReturning)
    2916                 :           0 :                 res = SPI_OK_DELETE_RETURNING;
    2917                 :             :             else
    2918                 :        5821 :                 res = SPI_OK_DELETE;
    2919                 :        5821 :             break;
    2920                 :        1099 :         case CMD_UPDATE:
    2921         [ +  + ]:        1099 :             if (queryDesc->plannedstmt->hasReturning)
    2922                 :          11 :                 res = SPI_OK_UPDATE_RETURNING;
    2923                 :             :             else
    2924                 :        1088 :                 res = SPI_OK_UPDATE;
    2925                 :        1099 :             break;
    2926                 :          44 :         case CMD_MERGE:
    2927         [ +  + ]:          44 :             if (queryDesc->plannedstmt->hasReturning)
    2928                 :          12 :                 res = SPI_OK_MERGE_RETURNING;
    2929                 :             :             else
    2930                 :          32 :                 res = SPI_OK_MERGE;
    2931                 :          44 :             break;
    2932                 :           0 :         default:
    2933                 :           0 :             return SPI_ERROR_OPUNKNOWN;
    2934                 :             :     }
    2935                 :             : 
    2936                 :             : #ifdef SPI_EXECUTOR_STATS
    2937                 :             :     if (ShowExecutorStats)
    2938                 :             :         ResetUsage();
    2939                 :             : #endif
    2940                 :             : 
    2941                 :             :     /* Select execution options */
    2942         [ +  + ]:       65723 :     if (fire_triggers)
    2943                 :       62166 :         eflags = 0;             /* default run-to-completion flags */
    2944                 :             :     else
    2945                 :        3557 :         eflags = EXEC_FLAG_SKIP_TRIGGERS;
    2946                 :             : 
    2947                 :       65723 :     ExecutorStart(queryDesc, eflags);
    2948                 :             : 
    2949                 :       65718 :     ExecutorRun(queryDesc, ForwardScanDirection, tcount);
    2950                 :             : 
    2951                 :       62555 :     _SPI_current->processed = queryDesc->estate->es_processed;
    2952                 :             : 
    2953   [ +  +  +  + ]:       62555 :     if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
    2954         [ +  + ]:       30837 :         queryDesc->dest->mydest == DestSPI)
    2955                 :             :     {
    2956         [ -  + ]:       29029 :         if (_SPI_checktuples())
    2957         [ #  # ]:           0 :             elog(ERROR, "consistency check on SPI tuple count failed");
    2958                 :             :     }
    2959                 :             : 
    2960                 :       62555 :     ExecutorFinish(queryDesc);
    2961                 :       62426 :     ExecutorEnd(queryDesc);
    2962                 :             :     /* FreeQueryDesc is done by the caller */
    2963                 :             : 
    2964                 :             : #ifdef SPI_EXECUTOR_STATS
    2965                 :             :     if (ShowExecutorStats)
    2966                 :             :         ShowUsage("SPI EXECUTOR STATS");
    2967                 :             : #endif
    2968                 :             : 
    2969                 :       62426 :     return res;
    2970                 :             : }
    2971                 :             : 
    2972                 :             : /*
    2973                 :             :  * _SPI_error_callback
    2974                 :             :  *
    2975                 :             :  * Add context information when a query invoked via SPI fails
    2976                 :             :  */
    2977                 :             : static void
    2978                 :        4167 : _SPI_error_callback(void *arg)
    2979                 :             : {
    2980                 :        4167 :     SPICallbackArg *carg = (SPICallbackArg *) arg;
    2981                 :        4167 :     const char *query = carg->query;
    2982                 :             :     int         syntaxerrposition;
    2983                 :             : 
    2984         [ -  + ]:        4167 :     if (query == NULL)          /* in case arg wasn't set yet */
    2985                 :           0 :         return;
    2986                 :             : 
    2987                 :             :     /*
    2988                 :             :      * If there is a syntax error position, convert to internal syntax error;
    2989                 :             :      * otherwise treat the query as an item of context stack
    2990                 :             :      */
    2991                 :        4167 :     syntaxerrposition = geterrposition();
    2992         [ +  + ]:        4167 :     if (syntaxerrposition > 0)
    2993                 :             :     {
    2994                 :          61 :         errposition(0);
    2995                 :          61 :         internalerrposition(syntaxerrposition);
    2996                 :          61 :         internalerrquery(query);
    2997                 :             :     }
    2998                 :             :     else
    2999                 :             :     {
    3000                 :             :         /* Use the parse mode to decide how to describe the query */
    3001      [ +  +  + ]:        4106 :         switch (carg->mode)
    3002                 :             :         {
    3003                 :          49 :             case RAW_PARSE_PLPGSQL_EXPR:
    3004                 :          49 :                 errcontext("PL/pgSQL expression \"%s\"", query);
    3005                 :          49 :                 break;
    3006                 :           8 :             case RAW_PARSE_PLPGSQL_ASSIGN1:
    3007                 :             :             case RAW_PARSE_PLPGSQL_ASSIGN2:
    3008                 :             :             case RAW_PARSE_PLPGSQL_ASSIGN3:
    3009                 :           8 :                 errcontext("PL/pgSQL assignment \"%s\"", query);
    3010                 :           8 :                 break;
    3011                 :        4049 :             default:
    3012                 :        4049 :                 errcontext("SQL statement \"%s\"", query);
    3013                 :        4049 :                 break;
    3014                 :             :         }
    3015                 :             :     }
    3016                 :             : }
    3017                 :             : 
    3018                 :             : /*
    3019                 :             :  * _SPI_cursor_operation()
    3020                 :             :  *
    3021                 :             :  *  Do a FETCH or MOVE in a cursor
    3022                 :             :  */
    3023                 :             : static void
    3024                 :       29874 : _SPI_cursor_operation(Portal portal, FetchDirection direction, long count,
    3025                 :             :                       DestReceiver *dest)
    3026                 :             : {
    3027                 :             :     uint64      nfetched;
    3028                 :             : 
    3029                 :             :     /* Check that the portal is valid */
    3030         [ -  + ]:       29874 :     if (!PortalIsValid(portal))
    3031         [ #  # ]:           0 :         elog(ERROR, "invalid portal in SPI cursor operation");
    3032                 :             : 
    3033                 :             :     /* Push the SPI stack */
    3034         [ -  + ]:       29874 :     if (_SPI_begin_call(true) < 0)
    3035         [ #  # ]:           0 :         elog(ERROR, "SPI cursor operation called while not connected");
    3036                 :             : 
    3037                 :             :     /* Reset the SPI result (note we deliberately don't touch lastoid) */
    3038                 :       29874 :     SPI_processed = 0;
    3039                 :       29874 :     SPI_tuptable = NULL;
    3040                 :       29874 :     _SPI_current->processed = 0;
    3041                 :       29874 :     _SPI_current->tuptable = NULL;
    3042                 :             : 
    3043                 :             :     /* Run the cursor */
    3044                 :       29874 :     nfetched = PortalRunFetch(portal,
    3045                 :             :                               direction,
    3046                 :             :                               count,
    3047                 :             :                               dest);
    3048                 :             : 
    3049                 :             :     /*
    3050                 :             :      * Think not to combine this store with the preceding function call. If
    3051                 :             :      * the portal contains calls to functions that use SPI, then _SPI_stack is
    3052                 :             :      * likely to move around while the portal runs.  When control returns,
    3053                 :             :      * _SPI_current will point to the correct stack entry... but the pointer
    3054                 :             :      * may be different than it was beforehand. So we must be sure to re-fetch
    3055                 :             :      * the pointer after the function call completes.
    3056                 :             :      */
    3057                 :       29857 :     _SPI_current->processed = nfetched;
    3058                 :             : 
    3059   [ +  +  -  + ]:       29857 :     if (dest->mydest == DestSPI && _SPI_checktuples())
    3060         [ #  # ]:           0 :         elog(ERROR, "consistency check on SPI tuple count failed");
    3061                 :             : 
    3062                 :             :     /* Put the result into place for access by caller */
    3063                 :       29857 :     SPI_processed = _SPI_current->processed;
    3064                 :       29857 :     SPI_tuptable = _SPI_current->tuptable;
    3065                 :             : 
    3066                 :             :     /* tuptable now is caller's responsibility, not SPI's */
    3067                 :       29857 :     _SPI_current->tuptable = NULL;
    3068                 :             : 
    3069                 :             :     /* Pop the SPI stack */
    3070                 :       29857 :     _SPI_end_call(true);
    3071                 :       29857 : }
    3072                 :             : 
    3073                 :             : 
    3074                 :             : static MemoryContext
    3075                 :      151911 : _SPI_execmem(void)
    3076                 :             : {
    3077                 :      151911 :     return MemoryContextSwitchTo(_SPI_current->execCxt);
    3078                 :             : }
    3079                 :             : 
    3080                 :             : static MemoryContext
    3081                 :      211397 : _SPI_procmem(void)
    3082                 :             : {
    3083                 :      211397 :     return MemoryContextSwitchTo(_SPI_current->procCxt);
    3084                 :             : }
    3085                 :             : 
    3086                 :             : /*
    3087                 :             :  * _SPI_begin_call: begin a SPI operation within a connected procedure
    3088                 :             :  *
    3089                 :             :  * use_exec is true if we intend to make use of the procedure's execCxt
    3090                 :             :  * during this SPI operation.  We'll switch into that context, and arrange
    3091                 :             :  * for it to be cleaned up at _SPI_end_call or if an error occurs.
    3092                 :             :  */
    3093                 :             : static int
    3094                 :      226586 : _SPI_begin_call(bool use_exec)
    3095                 :             : {
    3096         [ -  + ]:      226586 :     if (_SPI_current == NULL)
    3097                 :           0 :         return SPI_ERROR_UNCONNECTED;
    3098                 :             : 
    3099         [ +  + ]:      226586 :     if (use_exec)
    3100                 :             :     {
    3101                 :             :         /* remember when the Executor operation started */
    3102                 :      151911 :         _SPI_current->execSubid = GetCurrentSubTransactionId();
    3103                 :             :         /* switch to the Executor memory context */
    3104                 :      151911 :         _SPI_execmem();
    3105                 :             :     }
    3106                 :             : 
    3107                 :      226586 :     return 0;
    3108                 :             : }
    3109                 :             : 
    3110                 :             : /*
    3111                 :             :  * _SPI_end_call: end a SPI operation within a connected procedure
    3112                 :             :  *
    3113                 :             :  * use_exec must be the same as in the previous _SPI_begin_call
    3114                 :             :  *
    3115                 :             :  * Note: this currently has no failure return cases, so callers don't check
    3116                 :             :  */
    3117                 :             : static int
    3118                 :      148783 : _SPI_end_call(bool use_exec)
    3119                 :             : {
    3120         [ +  + ]:      148783 :     if (use_exec)
    3121                 :             :     {
    3122                 :             :         /* switch to the procedure memory context */
    3123                 :      148265 :         _SPI_procmem();
    3124                 :             :         /* mark Executor context no longer in use */
    3125                 :      148265 :         _SPI_current->execSubid = InvalidSubTransactionId;
    3126                 :             :         /* and free Executor memory */
    3127                 :      148265 :         MemoryContextReset(_SPI_current->execCxt);
    3128                 :             :     }
    3129                 :             : 
    3130                 :      148783 :     return 0;
    3131                 :             : }
    3132                 :             : 
    3133                 :             : static bool
    3134                 :       58858 : _SPI_checktuples(void)
    3135                 :             : {
    3136                 :       58858 :     uint64      processed = _SPI_current->processed;
    3137                 :       58858 :     SPITupleTable *tuptable = _SPI_current->tuptable;
    3138                 :       58858 :     bool        failed = false;
    3139                 :             : 
    3140         [ -  + ]:       58858 :     if (tuptable == NULL)       /* spi_dest_startup was not called */
    3141                 :           0 :         failed = true;
    3142         [ -  + ]:       58858 :     else if (processed != tuptable->numvals)
    3143                 :           0 :         failed = true;
    3144                 :             : 
    3145                 :       58858 :     return failed;
    3146                 :             : }
    3147                 :             : 
    3148                 :             : /*
    3149                 :             :  * Convert a "temporary" SPIPlan into an "unsaved" plan.
    3150                 :             :  *
    3151                 :             :  * The passed _SPI_plan struct is on the stack, and all its subsidiary data
    3152                 :             :  * is in or under the current SPI executor context.  Copy the plan into the
    3153                 :             :  * SPI procedure context so it will survive _SPI_end_call().  To minimize
    3154                 :             :  * data copying, this destructively modifies the input plan, by taking the
    3155                 :             :  * plancache entries away from it and reparenting them to the new SPIPlan.
    3156                 :             :  */
    3157                 :             : static SPIPlanPtr
    3158                 :       21283 : _SPI_make_plan_non_temp(SPIPlanPtr plan)
    3159                 :             : {
    3160                 :             :     SPIPlanPtr  newplan;
    3161                 :       21283 :     MemoryContext parentcxt = _SPI_current->procCxt;
    3162                 :             :     MemoryContext plancxt;
    3163                 :             :     MemoryContext oldcxt;
    3164                 :             :     ListCell   *lc;
    3165                 :             : 
    3166                 :             :     /* Assert the input is a temporary SPIPlan */
    3167                 :             :     Assert(plan->magic == _SPI_PLAN_MAGIC);
    3168                 :             :     Assert(plan->plancxt == NULL);
    3169                 :             :     /* One-shot plans can't be saved */
    3170                 :             :     Assert(!plan->oneshot);
    3171                 :             : 
    3172                 :             :     /*
    3173                 :             :      * Create a memory context for the plan, underneath the procedure context.
    3174                 :             :      * We don't expect the plan to be very large.
    3175                 :             :      */
    3176                 :       21283 :     plancxt = AllocSetContextCreate(parentcxt,
    3177                 :             :                                     "SPI Plan",
    3178                 :             :                                     ALLOCSET_SMALL_SIZES);
    3179                 :       21283 :     oldcxt = MemoryContextSwitchTo(plancxt);
    3180                 :             : 
    3181                 :             :     /* Copy the _SPI_plan struct and subsidiary data into the new context */
    3182                 :       21283 :     newplan = palloc0_object(_SPI_plan);
    3183                 :       21283 :     newplan->magic = _SPI_PLAN_MAGIC;
    3184                 :       21283 :     newplan->plancxt = plancxt;
    3185                 :       21283 :     newplan->parse_mode = plan->parse_mode;
    3186                 :       21283 :     newplan->cursor_options = plan->cursor_options;
    3187                 :       21283 :     newplan->nargs = plan->nargs;
    3188         [ +  + ]:       21283 :     if (plan->nargs > 0)
    3189                 :             :     {
    3190                 :             :         Oid        *newplan_argtypes;
    3191                 :             : 
    3192                 :        1597 :         newplan_argtypes = palloc_array(Oid, plan->nargs);
    3193                 :        1597 :         memcpy(newplan_argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
    3194                 :        1597 :         newplan->argtypes = newplan_argtypes;
    3195                 :             :     }
    3196                 :             :     else
    3197                 :       19686 :         newplan->argtypes = NULL;
    3198                 :       21283 :     newplan->parserSetup = plan->parserSetup;
    3199                 :       21283 :     newplan->parserSetupArg = plan->parserSetupArg;
    3200                 :             : 
    3201                 :             :     /*
    3202                 :             :      * Reparent all the CachedPlanSources into the procedure context.  In
    3203                 :             :      * theory this could fail partway through due to the pallocs, but we don't
    3204                 :             :      * care too much since both the procedure context and the executor context
    3205                 :             :      * would go away on error.
    3206                 :             :      */
    3207   [ +  -  +  +  :       42566 :     foreach(lc, plan->plancache_list)
                   +  + ]
    3208                 :             :     {
    3209                 :       21283 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
    3210                 :             : 
    3211                 :       21283 :         CachedPlanSetParentContext(plansource, parentcxt);
    3212                 :             : 
    3213                 :             :         /* Build new list, with list cells in plancxt */
    3214                 :       21283 :         newplan->plancache_list = lappend(newplan->plancache_list, plansource);
    3215                 :             :     }
    3216                 :             : 
    3217                 :       21283 :     MemoryContextSwitchTo(oldcxt);
    3218                 :             : 
    3219                 :             :     /* For safety, unlink the CachedPlanSources from the temporary plan */
    3220                 :       21283 :     plan->plancache_list = NIL;
    3221                 :             : 
    3222                 :       21283 :     return newplan;
    3223                 :             : }
    3224                 :             : 
    3225                 :             : /*
    3226                 :             :  * Make a "saved" copy of the given plan.
    3227                 :             :  */
    3228                 :             : static SPIPlanPtr
    3229                 :           0 : _SPI_save_plan(SPIPlanPtr plan)
    3230                 :             : {
    3231                 :             :     SPIPlanPtr  newplan;
    3232                 :             :     MemoryContext plancxt;
    3233                 :             :     MemoryContext oldcxt;
    3234                 :             :     ListCell   *lc;
    3235                 :             : 
    3236                 :             :     /* One-shot plans can't be saved */
    3237                 :             :     Assert(!plan->oneshot);
    3238                 :             : 
    3239                 :             :     /*
    3240                 :             :      * Create a memory context for the plan.  We don't expect the plan to be
    3241                 :             :      * very large, so use smaller-than-default alloc parameters.  It's a
    3242                 :             :      * transient context until we finish copying everything.
    3243                 :             :      */
    3244                 :           0 :     plancxt = AllocSetContextCreate(CurrentMemoryContext,
    3245                 :             :                                     "SPI Plan",
    3246                 :             :                                     ALLOCSET_SMALL_SIZES);
    3247                 :           0 :     oldcxt = MemoryContextSwitchTo(plancxt);
    3248                 :             : 
    3249                 :             :     /* Copy the SPI plan into its own context */
    3250                 :           0 :     newplan = palloc0_object(_SPI_plan);
    3251                 :           0 :     newplan->magic = _SPI_PLAN_MAGIC;
    3252                 :           0 :     newplan->plancxt = plancxt;
    3253                 :           0 :     newplan->parse_mode = plan->parse_mode;
    3254                 :           0 :     newplan->cursor_options = plan->cursor_options;
    3255                 :           0 :     newplan->nargs = plan->nargs;
    3256         [ #  # ]:           0 :     if (plan->nargs > 0)
    3257                 :             :     {
    3258                 :             :         Oid        *newplan_argtypes;
    3259                 :             : 
    3260                 :           0 :         newplan_argtypes = palloc_array(Oid, plan->nargs);
    3261                 :           0 :         memcpy(newplan_argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
    3262                 :           0 :         newplan->argtypes = newplan_argtypes;
    3263                 :             :     }
    3264                 :             :     else
    3265                 :           0 :         newplan->argtypes = NULL;
    3266                 :           0 :     newplan->parserSetup = plan->parserSetup;
    3267                 :           0 :     newplan->parserSetupArg = plan->parserSetupArg;
    3268                 :             : 
    3269                 :             :     /* Copy all the plancache entries */
    3270   [ #  #  #  #  :           0 :     foreach(lc, plan->plancache_list)
                   #  # ]
    3271                 :             :     {
    3272                 :           0 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
    3273                 :             :         CachedPlanSource *newsource;
    3274                 :             : 
    3275                 :           0 :         newsource = CopyCachedPlan(plansource);
    3276                 :           0 :         newplan->plancache_list = lappend(newplan->plancache_list, newsource);
    3277                 :             :     }
    3278                 :             : 
    3279                 :           0 :     MemoryContextSwitchTo(oldcxt);
    3280                 :             : 
    3281                 :             :     /*
    3282                 :             :      * Mark it saved, reparent it under CacheMemoryContext, and mark all the
    3283                 :             :      * component CachedPlanSources as saved.  This sequence cannot fail
    3284                 :             :      * partway through, so there's no risk of long-term memory leakage.
    3285                 :             :      */
    3286                 :           0 :     newplan->saved = true;
    3287                 :           0 :     MemoryContextSetParent(newplan->plancxt, CacheMemoryContext);
    3288                 :             : 
    3289   [ #  #  #  #  :           0 :     foreach(lc, newplan->plancache_list)
                   #  # ]
    3290                 :             :     {
    3291                 :           0 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
    3292                 :             : 
    3293                 :           0 :         SaveCachedPlan(plansource);
    3294                 :             :     }
    3295                 :             : 
    3296                 :           0 :     return newplan;
    3297                 :             : }
    3298                 :             : 
    3299                 :             : /*
    3300                 :             :  * Internal lookup of ephemeral named relation by name.
    3301                 :             :  */
    3302                 :             : static EphemeralNamedRelation
    3303                 :         518 : _SPI_find_ENR_by_name(const char *name)
    3304                 :             : {
    3305                 :             :     /* internal static function; any error is bug in SPI itself */
    3306                 :             :     Assert(name != NULL);
    3307                 :             : 
    3308                 :             :     /* fast exit if no tuplestores have been added */
    3309         [ +  + ]:         518 :     if (_SPI_current->queryEnv == NULL)
    3310                 :         407 :         return NULL;
    3311                 :             : 
    3312                 :         111 :     return get_ENR(_SPI_current->queryEnv, name);
    3313                 :             : }
    3314                 :             : 
    3315                 :             : /*
    3316                 :             :  * Register an ephemeral named relation for use by the planner and executor on
    3317                 :             :  * subsequent calls using this SPI connection.
    3318                 :             :  *
    3319                 :             :  * NB: The query environment for the ENR will not last after the SPI
    3320                 :             :  * connection; if SPI_register_relation() is called, all portals created on
    3321                 :             :  * this SPI connection must be closed.  Remaining portals (e.g. returned using
    3322                 :             :  * a refcursor) will be closed at SPI_finish time.
    3323                 :             :  */
    3324                 :             : int
    3325                 :         518 : SPI_register_relation(EphemeralNamedRelation enr)
    3326                 :             : {
    3327                 :             :     EphemeralNamedRelation match;
    3328                 :             :     int         res;
    3329                 :             : 
    3330   [ +  -  -  + ]:         518 :     if (enr == NULL || enr->md.name == NULL)
    3331                 :           0 :         return SPI_ERROR_ARGUMENT;
    3332                 :             : 
    3333                 :         518 :     res = _SPI_begin_call(false);   /* keep current memory context */
    3334         [ -  + ]:         518 :     if (res < 0)
    3335                 :           0 :         return res;
    3336                 :             : 
    3337                 :         518 :     match = _SPI_find_ENR_by_name(enr->md.name);
    3338         [ -  + ]:         518 :     if (match)
    3339                 :           0 :         res = SPI_ERROR_REL_DUPLICATE;
    3340                 :             :     else
    3341                 :             :     {
    3342         [ +  + ]:         518 :         if (_SPI_current->queryEnv == NULL)
    3343                 :         407 :             _SPI_current->queryEnv = create_queryEnv();
    3344                 :             : 
    3345                 :         518 :         register_ENR(_SPI_current->queryEnv, enr);
    3346                 :         518 :         res = SPI_OK_REL_REGISTER;
    3347                 :             :     }
    3348                 :             : 
    3349                 :         518 :     _SPI_end_call(false);
    3350                 :             : 
    3351                 :         518 :     return res;
    3352                 :             : }
    3353                 :             : 
    3354                 :             : /*
    3355                 :             :  * Unregister an ephemeral named relation by name.  This will probably be a
    3356                 :             :  * rarely used function, since SPI_finish will clear it automatically.
    3357                 :             :  */
    3358                 :             : int
    3359                 :           0 : SPI_unregister_relation(const char *name)
    3360                 :             : {
    3361                 :             :     EphemeralNamedRelation match;
    3362                 :             :     int         res;
    3363                 :             : 
    3364         [ #  # ]:           0 :     if (name == NULL)
    3365                 :           0 :         return SPI_ERROR_ARGUMENT;
    3366                 :             : 
    3367                 :           0 :     res = _SPI_begin_call(false);   /* keep current memory context */
    3368         [ #  # ]:           0 :     if (res < 0)
    3369                 :           0 :         return res;
    3370                 :             : 
    3371                 :           0 :     match = _SPI_find_ENR_by_name(name);
    3372         [ #  # ]:           0 :     if (match)
    3373                 :             :     {
    3374                 :           0 :         unregister_ENR(_SPI_current->queryEnv, match->md.name);
    3375                 :           0 :         res = SPI_OK_REL_UNREGISTER;
    3376                 :             :     }
    3377                 :             :     else
    3378                 :           0 :         res = SPI_ERROR_REL_NOT_FOUND;
    3379                 :             : 
    3380                 :           0 :     _SPI_end_call(false);
    3381                 :             : 
    3382                 :           0 :     return res;
    3383                 :             : }
    3384                 :             : 
    3385                 :             : /*
    3386                 :             :  * Register the transient relations from 'tdata' using this SPI connection.
    3387                 :             :  * This should be called by PL implementations' trigger handlers after
    3388                 :             :  * connecting, in order to make transition tables visible to any queries run
    3389                 :             :  * in this connection.
    3390                 :             :  *
    3391                 :             :  * NB: The query environment for the ENR will not last after the SPI
    3392                 :             :  * connection; if SPI_register_trigger_data() is called, all portals created
    3393                 :             :  * on this SPI connection must be closed.  Remaining portals (e.g. returned
    3394                 :             :  * using a refcursor) will be closed at SPI_finish time.
    3395                 :             :  */
    3396                 :             : int
    3397                 :       10450 : SPI_register_trigger_data(TriggerData *tdata)
    3398                 :             : {
    3399         [ -  + ]:       10450 :     if (tdata == NULL)
    3400                 :           0 :         return SPI_ERROR_ARGUMENT;
    3401                 :             : 
    3402         [ +  + ]:       10450 :     if (tdata->tg_newtable)
    3403                 :             :     {
    3404                 :             :         EphemeralNamedRelation enr =
    3405                 :         291 :             palloc_object(EphemeralNamedRelationData);
    3406                 :             :         int         rc;
    3407                 :             : 
    3408                 :         291 :         enr->md.name = tdata->tg_trigger->tgnewtable;
    3409                 :         291 :         enr->md.reliddesc = tdata->tg_relation->rd_id;
    3410                 :         291 :         enr->md.tupdesc = NULL;
    3411                 :         291 :         enr->md.enrtype = ENR_NAMED_TUPLESTORE;
    3412                 :         291 :         enr->md.enrtuples = tuplestore_tuple_count(tdata->tg_newtable);
    3413                 :         291 :         enr->reldata = tdata->tg_newtable;
    3414                 :         291 :         rc = SPI_register_relation(enr);
    3415         [ -  + ]:         291 :         if (rc != SPI_OK_REL_REGISTER)
    3416                 :           0 :             return rc;
    3417                 :             :     }
    3418                 :             : 
    3419         [ +  + ]:       10450 :     if (tdata->tg_oldtable)
    3420                 :             :     {
    3421                 :             :         EphemeralNamedRelation enr =
    3422                 :         227 :             palloc_object(EphemeralNamedRelationData);
    3423                 :             :         int         rc;
    3424                 :             : 
    3425                 :         227 :         enr->md.name = tdata->tg_trigger->tgoldtable;
    3426                 :         227 :         enr->md.reliddesc = tdata->tg_relation->rd_id;
    3427                 :         227 :         enr->md.tupdesc = NULL;
    3428                 :         227 :         enr->md.enrtype = ENR_NAMED_TUPLESTORE;
    3429                 :         227 :         enr->md.enrtuples = tuplestore_tuple_count(tdata->tg_oldtable);
    3430                 :         227 :         enr->reldata = tdata->tg_oldtable;
    3431                 :         227 :         rc = SPI_register_relation(enr);
    3432         [ -  + ]:         227 :         if (rc != SPI_OK_REL_REGISTER)
    3433                 :           0 :             return rc;
    3434                 :             :     }
    3435                 :             : 
    3436                 :       10450 :     return SPI_OK_TD_REGISTER;
    3437                 :             : }
        

Generated by: LCOV version 2.0-1