LCOV - differential code coverage report
Current view: top level - src/backend/executor - spi.c (source / functions) Coverage Total Hit UNC LBC UBC GNC CBC ECB DUB DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 71.4 % 1260 900 4 2 354 7 893 2 3 7
Current Date: 2026-11-28 16:48:44 +0900 Functions: 81.0 % 84 68 2 1 13 7 61 1 3
Baseline: lcov-20261128-baseline Branches: 54.6 % 811 443 368 443
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 40.0 % 5 2 3 2
(30,360] days: 60.0 % 20 12 4 1 3 7 5
(360..) days: 71.7 % 1235 886 1 348 886 2
Function coverage date bins:
(30,360] days: 60.0 % 5 3 1 1 3
(360..) days: 82.3 % 79 65 1 13 4 61
Branch coverage date bins:
(7,30] days: 33.3 % 6 2 4 2
(360..) days: 54.8 % 805 441 364 441

 Age         Owner                    Branch data    TLA  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
 9311 tgl@sss.pgh.pa.us          95                 :CBC        9608 : SPI_connect(void)
                                 96                 :                : {
 3232 peter_e@gmx.net            97                 :           9608 :     return SPI_connect_ext(0);
                                 98                 :                : }
                                 99                 :                : 
                                100                 :                : int
                                101                 :          76226 : SPI_connect_ext(int options)
                                102                 :                : {
                                103                 :                :     int         newdepth;
                                104                 :                : 
                                105                 :                :     /* Enlarge stack if necessary */
10674 bruce@momjian.us          106         [ +  + ]:          76226 :     if (_SPI_stack == NULL)
                                107                 :                :     {
 8185 tgl@sss.pgh.pa.us         108   [ +  -  -  + ]:           1136 :         if (_SPI_connected != -1 || _SPI_stack_depth != 0)
 8531 tgl@sss.pgh.pa.us         109         [ #  # ]:UBC           0 :             elog(ERROR, "SPI stack corrupted");
 8185 tgl@sss.pgh.pa.us         110                 :CBC        1136 :         newdepth = 16;
                                111                 :           1136 :         _SPI_stack = (_SPI_connection *)
 3232 peter_e@gmx.net           112                 :           1136 :             MemoryContextAlloc(TopMemoryContext,
                                113                 :                :                                newdepth * sizeof(_SPI_connection));
 8185 tgl@sss.pgh.pa.us         114                 :           1136 :         _SPI_stack_depth = newdepth;
                                115                 :                :     }
                                116                 :                :     else
                                117                 :                :     {
                                118   [ +  -  -  + ]:          75090 :         if (_SPI_stack_depth <= 0 || _SPI_stack_depth <= _SPI_connected)
 8531 tgl@sss.pgh.pa.us         119         [ #  # ]:UBC           0 :             elog(ERROR, "SPI stack corrupted");
 8185 tgl@sss.pgh.pa.us         120         [ +  + ]:CBC       75090 :         if (_SPI_stack_depth == _SPI_connected + 1)
                                121                 :                :         {
                                122                 :             13 :             newdepth = _SPI_stack_depth * 2;
  103 michael@paquier.xyz       123                 :GNC          13 :             _SPI_stack = repalloc_array(_SPI_stack, _SPI_connection, newdepth);
 8185 tgl@sss.pgh.pa.us         124                 :CBC          13 :             _SPI_stack_depth = newdepth;
                                125                 :                :         }
                                126                 :                :     }
                                127                 :                : 
                                128                 :                :     /* Enter new stack level */
10674 bruce@momjian.us          129                 :          76226 :     _SPI_connected++;
 8185 tgl@sss.pgh.pa.us         130   [ +  -  -  + ]:          76226 :     Assert(_SPI_connected >= 0 && _SPI_connected < _SPI_stack_depth);
                                131                 :                : 
10674 bruce@momjian.us          132                 :          76226 :     _SPI_current = &(_SPI_stack[_SPI_connected]);
                                133                 :          76226 :     _SPI_current->processed = 0;
                                134                 :          76226 :     _SPI_current->tuptable = NULL;
 3340 tgl@sss.pgh.pa.us         135                 :          76226 :     _SPI_current->execSubid = InvalidSubTransactionId;
 4874                           136                 :          76226 :     slist_init(&_SPI_current->tuptables);
 3447                           137                 :          76226 :     _SPI_current->procCxt = NULL;    /* in case we fail to create 'em */
 8108                           138                 :          76226 :     _SPI_current->execCxt = NULL;
                                139                 :          76226 :     _SPI_current->connectSubid = GetCurrentSubTransactionId();
 3529 kgrittn@postgresql.o      140                 :          76226 :     _SPI_current->queryEnv = NULL;
 3232 peter_e@gmx.net           141                 :          76226 :     _SPI_current->atomic = (options & SPI_OPT_NONATOMIC ? false : true);
                                142                 :          76226 :     _SPI_current->internal_xact = false;
 3004 tgl@sss.pgh.pa.us         143                 :          76226 :     _SPI_current->outer_processed = SPI_processed;
                                144                 :          76226 :     _SPI_current->outer_tuptable = SPI_tuptable;
                                145                 :          76226 :     _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                 :                :      */
 3232 peter_e@gmx.net           160         [ +  + ]:          76226 :     _SPI_current->procCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : PortalContext,
                                161                 :                :                                                   "SPI Proc",
                                162                 :                :                                                   ALLOCSET_DEFAULT_SIZES);
                                163         [ +  + ]:          76226 :     _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 */
 9649 tgl@sss.pgh.pa.us         167                 :          76226 :     _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                 :                :      */
 3004                           173                 :          76226 :     SPI_processed = 0;
                                174                 :          76226 :     SPI_tuptable = NULL;
                                175                 :          76226 :     SPI_result = 0;
                                176                 :                : 
10315 bruce@momjian.us          177                 :          76226 :     return SPI_OK_CONNECT;
                                178                 :                : }
                                179                 :                : 
                                180                 :                : int
 9311 tgl@sss.pgh.pa.us         181                 :          74104 : SPI_finish(void)
                                182                 :                : {
                                183                 :                :     int         res;
                                184                 :                : 
 3340                           185                 :          74104 :     res = _SPI_begin_call(false);   /* just check we're connected */
10674 bruce@momjian.us          186         [ -  + ]:          74104 :     if (res < 0)
10315 bruce@momjian.us          187                 :UBC           0 :         return res;
                                188                 :                : 
                                189                 :                :     /* Restore memory context as it was before procedure call */
10674 bruce@momjian.us          190                 :CBC       74104 :     MemoryContextSwitchTo(_SPI_current->savedcxt);
                                191                 :                : 
                                192                 :                :     /* queryEnv will become invalid; drop portals that need it */
   19 jdavis@postgresql.or      193         [ +  + ]:          74104 :     if (_SPI_current->queryEnv != NULL)
                                194                 :            375 :         DropQueryEnvPortals(_SPI_current->queryEnv);
                                195                 :                : 
                                196                 :                :     /* Release memory used in procedure call (including tuptables) */
 9649 tgl@sss.pgh.pa.us         197                 :          74104 :     MemoryContextDelete(_SPI_current->execCxt);
 8108                           198                 :          74104 :     _SPI_current->execCxt = NULL;
 9649                           199                 :          74104 :     MemoryContextDelete(_SPI_current->procCxt);
 8108                           200                 :          74104 :     _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                 :                :      */
 3004                           206                 :          74104 :     SPI_processed = _SPI_current->outer_processed;
                                207                 :          74104 :     SPI_tuptable = _SPI_current->outer_tuptable;
                                208                 :          74104 :     SPI_result = _SPI_current->outer_result;
                                209                 :                : 
                                210                 :                :     /* Exit stack level */
10674 bruce@momjian.us          211                 :          74104 :     _SPI_connected--;
 3672 tgl@sss.pgh.pa.us         212         [ +  + ]:          74104 :     if (_SPI_connected < 0)
 9649                           213                 :          63658 :         _SPI_current = NULL;
                                214                 :                :     else
10674 bruce@momjian.us          215                 :          10446 :         _SPI_current = &(_SPI_stack[_SPI_connected]);
                                216                 :                : 
10315                           217                 :          74104 :     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
 3232 peter_e@gmx.net           225                 :UBC           0 : SPI_start_transaction(void)
                                226                 :                : {
                                227                 :              0 : }
                                228                 :                : 
                                229                 :                : static void
 2806 peter@eisentraut.org      230                 :CBC        2223 : _SPI_commit(bool chain)
                                231                 :                : {
 3232 peter_e@gmx.net           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                 :                : 
 1734 tgl@sss.pgh.pa.us         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 */
 2806 peter@eisentraut.org      284                 :           2196 :         StartTransactionCommand();
 1734 tgl@sss.pgh.pa.us         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)
 1734 tgl@sss.pgh.pa.us         310                 :UBC           0 :             RestoreTransactionCharacteristics(&savetc);
                                311                 :                : 
 1734 tgl@sss.pgh.pa.us         312                 :CBC           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();
 3232 peter_e@gmx.net           320                 :           2196 : }
                                321                 :                : 
                                322                 :                : void
 2806 peter@eisentraut.org      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                 :                : {
 3232 peter_e@gmx.net           337                 :            138 :     MemoryContext oldcontext = CurrentMemoryContext;
                                338                 :                :     SavedTransactionCharacteristics savetc;
                                339                 :                : 
                                340                 :                :     /* see comments in _SPI_commit() */
                                341         [ -  + ]:            138 :     if (_SPI_current->atomic)
 3232 peter_e@gmx.net           342         [ #  # ]:UBC           0 :         ereport(ERROR,
                                343                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
                                344                 :                :                  errmsg("invalid transaction termination")));
                                345                 :                : 
                                346                 :                :     /* see comments in _SPI_commit() */
 3232 peter_e@gmx.net           347         [ +  + ]:CBC         138 :     if (IsSubTransaction())
                                348         [ +  - ]:              2 :         ereport(ERROR,
                                349                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
                                350                 :                :                  errmsg("cannot roll back while a subtransaction is active")));
                                351                 :                : 
 1734 tgl@sss.pgh.pa.us         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 */
 2806 peter@eisentraut.org      376                 :            134 :         StartTransactionCommand();
 1734 tgl@sss.pgh.pa.us         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)
 1734 tgl@sss.pgh.pa.us         403                 :UBC           0 :             RestoreTransactionCharacteristics(&savetc);
                                404                 :                : 
 1734 tgl@sss.pgh.pa.us         405                 :CBC           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();
 3232 peter_e@gmx.net           413                 :            134 : }
                                414                 :                : 
                                415                 :                : void
 2806 peter@eisentraut.org      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
 8397 mail@joeconway.com        431                 :         442279 : AtEOXact_SPI(bool isCommit)
                                432                 :                : {
 1734 tgl@sss.pgh.pa.us         433                 :         442279 :     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         [ +  + ]:         443961 :     while (_SPI_connected >= 0)
                                440                 :                :     {
                                441                 :           4022 :         _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
                                442                 :                : 
                                443         [ +  + ]:           4022 :         if (connection->internal_xact)
                                444                 :           2340 :             break;
                                445                 :                : 
                                446                 :           1682 :         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                 :           1682 :         SPI_processed = connection->outer_processed;
                                460                 :           1682 :         SPI_tuptable = connection->outer_tuptable;
                                461                 :           1682 :         SPI_result = connection->outer_result;
                                462                 :                : 
                                463                 :           1682 :         _SPI_connected--;
                                464         [ +  + ]:           1682 :         if (_SPI_connected < 0)
                                465                 :           1634 :             _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   [ +  +  -  + ]:         442279 :     if (found && isCommit)
 8185 tgl@sss.pgh.pa.us         472         [ #  # ]:UBC           0 :         ereport(WARNING,
                                473                 :                :                 (errcode(ERRCODE_WARNING),
                                474                 :                :                  errmsg("transaction left non-empty SPI stack"),
                                475                 :                :                  errhint("Check for missing \"SPI_finish\" calls.")));
 9649 tgl@sss.pgh.pa.us         476                 :CBC      442279 : }
                                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
 8108                           485                 :          23131 : AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
                                486                 :                : {
 8126 bruce@momjian.us          487                 :          23131 :     bool        found = false;
                                488                 :                : 
 8185 tgl@sss.pgh.pa.us         489         [ +  + ]:          23571 :     while (_SPI_connected >= 0)
                                490                 :                :     {
                                491                 :          20747 :         _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
                                492                 :                : 
 8108                           493         [ +  + ]:          20747 :         if (connection->connectSubid != mySubid)
 8185                           494                 :          20307 :             break;              /* couldn't be any underneath it either */
                                495                 :                : 
 3232 peter_e@gmx.net           496         [ -  + ]:            440 :         if (connection->internal_xact)
 3232 peter_e@gmx.net           497                 :UBC           0 :             break;
                                498                 :                : 
 8185 tgl@sss.pgh.pa.us         499                 :CBC         440 :         found = true;
                                500                 :                : 
                                501                 :                :         /*
                                502                 :                :          * Release procedure memory explicitly (see note in SPI_connect)
                                503                 :                :          */
 8108                           504         [ +  - ]:            440 :         if (connection->execCxt)
                                505                 :                :         {
                                506                 :            440 :             MemoryContextDelete(connection->execCxt);
                                507                 :            440 :             connection->execCxt = NULL;
                                508                 :                :         }
                                509         [ +  - ]:            440 :         if (connection->procCxt)
                                510                 :                :         {
                                511                 :            440 :             MemoryContextDelete(connection->procCxt);
                                512                 :            440 :             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                 :                :          */
 3004                           520                 :            440 :         SPI_processed = connection->outer_processed;
                                521                 :            440 :         SPI_tuptable = connection->outer_tuptable;
                                522                 :            440 :         SPI_result = connection->outer_result;
                                523                 :                : 
 8185                           524                 :            440 :         _SPI_connected--;
 3672                           525         [ +  + ]:            440 :         if (_SPI_connected < 0)
 8185                           526                 :             88 :             _SPI_current = NULL;
                                527                 :                :         else
                                528                 :            352 :             _SPI_current = &(_SPI_stack[_SPI_connected]);
                                529                 :                :     }
                                530                 :                : 
                                531   [ +  +  -  + ]:          23131 :     if (found && isCommit)
 8185 tgl@sss.pgh.pa.us         532         [ #  # ]:UBC           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                 :                :      */
 7312 tgl@sss.pgh.pa.us         541   [ +  +  +  + ]:CBC       23131 :     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                 :                :          */
 3340                           549         [ +  + ]:           3770 :         if (_SPI_current->execSubid >= mySubid)
                                550                 :                :         {
                                551                 :           3214 :             _SPI_current->execSubid = InvalidSubTransactionId;
 1109 nathan@postgresql.or      552                 :           3214 :             MemoryContextReset(_SPI_current->execCxt);
                                553                 :                :         }
                                554                 :                : 
                                555                 :                :         /* throw away any tuple tables created within current subxact */
 4874 tgl@sss.pgh.pa.us         556   [ +  +  +  +  :           9298 :         slist_foreach_modify(siter, &_SPI_current->tuptables)
                                              +  + ]
                                557                 :                :         {
                                558                 :                :             SPITupleTable *tuptable;
                                559                 :                : 
                                560                 :           5528 :             tuptable = slist_container(SPITupleTable, next, siter.cur);
                                561         [ +  + ]:           5528 :             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                 :           2972 :                 slist_delete_current(&siter);
                                570         [ +  + ]:           2972 :                 if (tuptable == _SPI_current->tuptable)
                                571                 :           2968 :                     _SPI_current->tuptable = NULL;
                                572         [ +  + ]:           2972 :                 if (tuptable == SPI_tuptable)
                                573                 :              4 :                     SPI_tuptable = NULL;
                                574                 :           2972 :                 MemoryContextDelete(tuptable->tuptabcxt);
                                575                 :                :             }
                                576                 :                :         }
                                577                 :                :     }
 8185                           578                 :          23131 : }
                                579                 :                : 
                                580                 :                : /*
                                581                 :                :  * Are we executing inside a procedure (that is, a nonatomic SPI context)?
                                582                 :                :  */
                                583                 :                : bool
 2973                           584                 :         436131 : SPI_inside_nonatomic_context(void)
                                585                 :                : {
                                586         [ +  + ]:         436131 :     if (_SPI_current == NULL)
                                587                 :         433791 :         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)
 2973 tgl@sss.pgh.pa.us         590                 :UBC           0 :         return false;           /* it's atomic (ie function not procedure) */
  773 tgl@sss.pgh.pa.us         591         [ -  + ]:CBC        2340 :     if (IsSubTransaction())
  773 tgl@sss.pgh.pa.us         592                 :UBC           0 :         return false;           /* if within subtransaction, it's atomic */
 2973 tgl@sss.pgh.pa.us         593                 :CBC        2340 :     return true;
                                594                 :                : }
                                595                 :                : 
                                596                 :                : 
                                597                 :                : /* Parse, plan, and execute a query string */
                                598                 :                : int
 7880 neilc@samurai.com         599                 :            857 : SPI_execute(const char *src, bool read_only, long tcount)
                                600                 :                : {
                                601                 :                :     _SPI_plan   plan;
                                602                 :                :     SPIExecuteOptions options;
                                603                 :                :     int         res;
                                604                 :                : 
10674 bruce@momjian.us          605   [ +  -  -  + ]:            857 :     if (src == NULL || tcount < 0)
10315 bruce@momjian.us          606                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                607                 :                : 
10674 bruce@momjian.us          608                 :CBC         857 :     res = _SPI_begin_call(true);
                                609         [ -  + ]:            857 :     if (res < 0)
10315 bruce@momjian.us          610                 :UBC           0 :         return res;
                                611                 :                : 
 7198 tgl@sss.pgh.pa.us         612                 :CBC         857 :     memset(&plan, 0, sizeof(_SPI_plan));
                                613                 :            857 :     plan.magic = _SPI_PLAN_MAGIC;
 2154                           614                 :            857 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 3536 rhaas@postgresql.org      615                 :            857 :     plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
                                616                 :                : 
 5076 tgl@sss.pgh.pa.us         617                 :            857 :     _SPI_prepare_oneshot_plan(src, &plan);
                                618                 :                : 
 1882                           619                 :            851 :     memset(&options, 0, sizeof(options));
                                620                 :            851 :     options.read_only = read_only;
                                621                 :            851 :     options.tcount = tcount;
                                622                 :                : 
                                623                 :            851 :     res = _SPI_execute_plan(&plan, &options,
                                624                 :                :                             InvalidSnapshot, InvalidSnapshot,
                                625                 :                :                             true);
                                626                 :                : 
10674 bruce@momjian.us          627                 :            825 :     _SPI_end_call(true);
10315                           628                 :            825 :     return res;
                                629                 :                : }
                                630                 :                : 
                                631                 :                : /* Obsolete version of SPI_execute */
                                632                 :                : int
 7880 neilc@samurai.com         633                 :            325 : SPI_exec(const char *src, long tcount)
                                634                 :                : {
 8111 tgl@sss.pgh.pa.us         635                 :            325 :     return SPI_execute(src, false, tcount);
                                636                 :                : }
                                637                 :                : 
                                638                 :                : /* Parse, plan, and execute a query string, with extensible options */
                                639                 :                : int
 2132                           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)
 2132 tgl@sss.pgh.pa.us         647                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                648                 :                : 
 2132 tgl@sss.pgh.pa.us         649                 :CBC       13471 :     res = _SPI_begin_call(true);
                                650         [ -  + ]:          13471 :     if (res < 0)
 2132 tgl@sss.pgh.pa.us         651                 :UBC           0 :         return res;
                                652                 :                : 
 2132 tgl@sss.pgh.pa.us         653                 :CBC       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                 :                : 
 1882                           665                 :          13471 :     res = _SPI_execute_plan(&plan, options,
                                666                 :                :                             InvalidSnapshot, InvalidSnapshot,
                                667                 :                :                             true);
                                668                 :                : 
 2132                           669                 :          13297 :     _SPI_end_call(true);
                                670                 :          13297 :     return res;
                                671                 :                : }
                                672                 :                : 
                                673                 :                : /* Execute a previously prepared plan */
                                674                 :                : int
  393 peter@eisentraut.org      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                 :                : 
 7198 tgl@sss.pgh.pa.us         681   [ +  -  +  -  :           2645 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
                                              -  + ]
10315 bruce@momjian.us          682                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                683                 :                : 
 7198 tgl@sss.pgh.pa.us         684   [ +  +  -  + ]:CBC        2645 :     if (plan->nargs > 0 && Values == NULL)
10315 bruce@momjian.us          685                 :UBC           0 :         return SPI_ERROR_PARAM;
                                686                 :                : 
10674 bruce@momjian.us          687                 :CBC        2645 :     res = _SPI_begin_call(true);
                                688         [ -  + ]:           2645 :     if (res < 0)
10315 bruce@momjian.us          689                 :UBC           0 :         return res;
                                690                 :                : 
 1882 tgl@sss.pgh.pa.us         691                 :CBC        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                 :                : 
 8465                           701                 :           2643 :     _SPI_end_call(true);
                                702                 :           2643 :     return res;
                                703                 :                : }
                                704                 :                : 
                                705                 :                : /* Obsolete version of SPI_execute_plan */
                                706                 :                : int
  151 peter@eisentraut.org      707                 :LBC        (27) : SPI_execp(SPIPlanPtr plan, const Datum *Values, const char *Nulls, long tcount)
                                708                 :                : {
 8111 tgl@sss.pgh.pa.us         709                 :           (27) :     return SPI_execute_plan(plan, Values, Nulls, false, tcount);
                                710                 :                : }
                                711                 :                : 
                                712                 :                : /* Execute a previously prepared plan */
                                713                 :                : int
 2133 tgl@sss.pgh.pa.us         714                 :CBC        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)
                                              -  + ]
 6233 tgl@sss.pgh.pa.us         720                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                721                 :                : 
 6233 tgl@sss.pgh.pa.us         722                 :CBC        1748 :     res = _SPI_begin_call(true);
                                723         [ -  + ]:           1748 :     if (res < 0)
 6233 tgl@sss.pgh.pa.us         724                 :UBC           0 :         return res;
                                725                 :                : 
 1882 tgl@sss.pgh.pa.us         726                 :CBC        1748 :     res = _SPI_execute_plan(plan, options,
                                727                 :                :                             InvalidSnapshot, InvalidSnapshot,
                                728                 :                :                             true);
                                729                 :                : 
 2360                           730                 :           1738 :     _SPI_end_call(true);
                                731                 :           1738 :     return res;
                                732                 :                : }
                                733                 :                : 
                                734                 :                : /* Execute a previously prepared plan */
                                735                 :                : int
 2133                           736                 :          63628 : SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params,
                                737                 :                :                                 bool read_only, long tcount)
                                738                 :                : {
                                739                 :                :     SPIExecuteOptions options;
                                740                 :                :     int         res;
                                741                 :                : 
 2360                           742   [ +  -  +  -  :          63628 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
                                              -  + ]
 2360 tgl@sss.pgh.pa.us         743                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                744                 :                : 
 2360 tgl@sss.pgh.pa.us         745                 :CBC       63628 :     res = _SPI_begin_call(true);
                                746         [ -  + ]:          63628 :     if (res < 0)
 2360 tgl@sss.pgh.pa.us         747                 :UBC           0 :         return res;
                                748                 :                : 
 1882 tgl@sss.pgh.pa.us         749                 :CBC       63628 :     memset(&options, 0, sizeof(options));
                                750                 :          63628 :     options.params = params;
                                751                 :          63628 :     options.read_only = read_only;
                                752                 :          63628 :     options.tcount = tcount;
                                753                 :                : 
                                754                 :          63628 :     res = _SPI_execute_plan(plan, &options,
                                755                 :                :                             InvalidSnapshot, InvalidSnapshot,
                                756                 :                :                             true);
                                757                 :                : 
 6233                           758                 :          60449 :     _SPI_end_call(true);
                                759                 :          60449 :     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
 7198                           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)
                                              -  + ]
 8465 tgl@sss.pgh.pa.us         785                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                                786                 :                : 
 7198 tgl@sss.pgh.pa.us         787   [ +  +  -  + ]:CBC        3565 :     if (plan->nargs > 0 && Values == NULL)
 8465 tgl@sss.pgh.pa.us         788                 :UBC           0 :         return SPI_ERROR_PARAM;
                                789                 :                : 
 8465 tgl@sss.pgh.pa.us         790                 :CBC        3565 :     res = _SPI_begin_call(true);
                                791         [ -  + ]:           3565 :     if (res < 0)
 8465 tgl@sss.pgh.pa.us         792                 :UBC           0 :         return res;
                                793                 :                : 
 1882 tgl@sss.pgh.pa.us         794                 :CBC        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                 :                : 
10674 bruce@momjian.us          804                 :           3411 :     _SPI_end_call(true);
10315                           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
 6815 tgl@sss.pgh.pa.us         815                 :UBC           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;
 2154                           837                 :              0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 3536 rhaas@postgresql.org      838                 :              0 :     plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
 6815 tgl@sss.pgh.pa.us         839                 :              0 :     plan.nargs = nargs;
                                840                 :              0 :     plan.argtypes = argtypes;
 6233                           841                 :              0 :     plan.parserSetup = NULL;
                                842                 :              0 :     plan.parserSetupArg = NULL;
                                843                 :                : 
 6815                           844                 :              0 :     paramLI = _SPI_convert_params(nargs, argtypes,
                                845                 :                :                                   Values, Nulls);
                                846                 :                : 
 5076                           847                 :              0 :     _SPI_prepare_oneshot_plan(src, &plan);
                                848                 :                : 
 1882                           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                 :                : 
 2360                           858                 :              0 :     _SPI_end_call(true);
                                859                 :              0 :     return res;
                                860                 :                : }
                                861                 :                : 
                                862                 :                : SPIPlanPtr
  151 peter@eisentraut.org      863                 :GNC        2605 : SPI_prepare(const char *src, int nargs, const Oid *argtypes)
                                864                 :                : {
 7166 tgl@sss.pgh.pa.us         865                 :CBC        2605 :     return SPI_prepare_cursor(src, nargs, argtypes, 0);
                                866                 :                : }
                                867                 :                : 
                                868                 :                : SPIPlanPtr
  151 peter@eisentraut.org      869                 :GNC        2605 : SPI_prepare_cursor(const char *src, int nargs, const Oid *argtypes,
                                870                 :                :                    int cursorOptions)
                                871                 :                : {
                                872                 :                :     _SPI_plan   plan;
                                873                 :                :     SPIPlanPtr  result;
                                874                 :                : 
10655 vadim4o@yahoo.com         875   [ +  -  +  -  :CBC        2605 :     if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
                                        +  +  -  + ]
                                876                 :                :     {
10674 bruce@momjian.us          877                 :UBC           0 :         SPI_result = SPI_ERROR_ARGUMENT;
10315                           878                 :              0 :         return NULL;
                                879                 :                :     }
                                880                 :                : 
10674 bruce@momjian.us          881                 :CBC        2605 :     SPI_result = _SPI_begin_call(true);
                                882         [ -  + ]:           2605 :     if (SPI_result < 0)
10315 bruce@momjian.us          883                 :UBC           0 :         return NULL;
                                884                 :                : 
 7198 tgl@sss.pgh.pa.us         885                 :CBC        2605 :     memset(&plan, 0, sizeof(_SPI_plan));
                                886                 :           2605 :     plan.magic = _SPI_PLAN_MAGIC;
 2154                           887                 :           2605 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 7166                           888                 :           2605 :     plan.cursor_options = cursorOptions;
 8287                           889                 :           2605 :     plan.nargs = nargs;
                                890                 :           2605 :     plan.argtypes = argtypes;
 6233                           891                 :           2605 :     plan.parserSetup = NULL;
                                892                 :           2605 :     plan.parserSetupArg = NULL;
                                893                 :                : 
 5076                           894                 :           2605 :     _SPI_prepare_plan(src, &plan);
                                895                 :                : 
                                896                 :                :     /* copy plan to procedure context */
 5552                           897                 :           2604 :     result = _SPI_make_plan_non_temp(&plan);
                                898                 :                : 
 6233                           899                 :           2604 :     _SPI_end_call(true);
                                900                 :                : 
                                901                 :           2604 :     return result;
                                902                 :                : }
                                903                 :                : 
                                904                 :                : SPIPlanPtr
 2154                           905                 :          18572 : SPI_prepare_extended(const char *src,
                                906                 :                :                      const SPIPrepareOptions *options)
                                907                 :                : {
                                908                 :                :     _SPI_plan   plan;
                                909                 :                :     SPIPlanPtr  result;
                                910                 :                : 
                                911   [ +  -  -  + ]:          18572 :     if (src == NULL || options == NULL)
                                912                 :                :     {
 2154 tgl@sss.pgh.pa.us         913                 :UBC           0 :         SPI_result = SPI_ERROR_ARGUMENT;
                                914                 :              0 :         return NULL;
                                915                 :                :     }
                                916                 :                : 
 2154 tgl@sss.pgh.pa.us         917                 :CBC       18572 :     SPI_result = _SPI_begin_call(true);
                                918         [ -  + ]:          18572 :     if (SPI_result < 0)
 2154 tgl@sss.pgh.pa.us         919                 :UBC           0 :         return NULL;
                                920                 :                : 
 2154 tgl@sss.pgh.pa.us         921                 :CBC       18572 :     memset(&plan, 0, sizeof(_SPI_plan));
                                922                 :          18572 :     plan.magic = _SPI_PLAN_MAGIC;
                                923                 :          18572 :     plan.parse_mode = options->parseMode;
                                924                 :          18572 :     plan.cursor_options = options->cursorOptions;
                                925                 :          18572 :     plan.nargs = 0;
                                926                 :          18572 :     plan.argtypes = NULL;
                                927                 :          18572 :     plan.parserSetup = options->parserSetup;
                                928                 :          18572 :     plan.parserSetupArg = options->parserSetupArg;
                                929                 :                : 
                                930                 :          18572 :     _SPI_prepare_plan(src, &plan);
                                931                 :                : 
                                932                 :                :     /* copy plan to procedure context */
                                933                 :          18511 :     result = _SPI_make_plan_non_temp(&plan);
                                934                 :                : 
                                935                 :          18511 :     _SPI_end_call(true);
                                936                 :                : 
                                937                 :          18511 :     return result;
                                938                 :                : }
                                939                 :                : 
                                940                 :                : SPIPlanPtr
 6233 tgl@sss.pgh.pa.us         941                 :UBC           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;
 2154                           961                 :              0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 6233                           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                 :                : 
 5076                           968                 :              0 :     _SPI_prepare_plan(src, &plan);
                                969                 :                : 
                                970                 :                :     /* copy plan to procedure context */
 5552                           971                 :              0 :     result = _SPI_make_plan_non_temp(&plan);
                                972                 :                : 
10674 bruce@momjian.us          973                 :              0 :     _SPI_end_call(true);
                                974                 :                : 
 7198 tgl@sss.pgh.pa.us         975                 :              0 :     return result;
                                976                 :                : }
                                977                 :                : 
                                978                 :                : int
 5552 tgl@sss.pgh.pa.us         979                 :CBC       20122 : SPI_keepplan(SPIPlanPtr plan)
                                980                 :                : {
                                981                 :                :     ListCell   *lc;
                                982                 :                : 
 5076                           983   [ +  -  +  - ]:          20122 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
                                984   [ +  -  -  + ]:          20122 :         plan->saved || plan->oneshot)
 5552 tgl@sss.pgh.pa.us         985                 :UBC           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                 :                :      */
 5552 tgl@sss.pgh.pa.us         992                 :CBC       20122 :     plan->saved = true;
                                993                 :          20122 :     MemoryContextSetParent(plan->plancxt, CacheMemoryContext);
                                994                 :                : 
                                995   [ +  -  +  +  :          40244 :     foreach(lc, plan->plancache_list)
                                              +  + ]
                                996                 :                :     {
                                997                 :          20122 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
                                998                 :                : 
                                999                 :          20122 :         SaveCachedPlan(plansource);
                               1000                 :                :     }
                               1001                 :                : 
                               1002                 :          20122 :     return 0;
                               1003                 :                : }
                               1004                 :                : 
                               1005                 :                : SPIPlanPtr
 7198 tgl@sss.pgh.pa.us        1006                 :UBC           0 : SPI_saveplan(SPIPlanPtr plan)
                               1007                 :                : {
                               1008                 :                :     SPIPlanPtr  newplan;
                               1009                 :                : 
 5552                          1010   [ #  #  #  # ]:              0 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
                               1011                 :                :     {
10674 bruce@momjian.us         1012                 :              0 :         SPI_result = SPI_ERROR_ARGUMENT;
10315                          1013                 :              0 :         return NULL;
                               1014                 :                :     }
                               1015                 :                : 
 3447 tgl@sss.pgh.pa.us        1016                 :              0 :     SPI_result = _SPI_begin_call(false);    /* don't change context */
10674 bruce@momjian.us         1017         [ #  # ]:              0 :     if (SPI_result < 0)
10315                          1018                 :              0 :         return NULL;
                               1019                 :                : 
 7198 tgl@sss.pgh.pa.us        1020                 :              0 :     newplan = _SPI_save_plan(plan);
                               1021                 :                : 
 5552                          1022                 :              0 :     SPI_result = _SPI_end_call(false);
                               1023                 :                : 
 7198                          1024                 :              0 :     return newplan;
                               1025                 :                : }
                               1026                 :                : 
                               1027                 :                : int
 7198 tgl@sss.pgh.pa.us        1028                 :CBC        5571 : SPI_freeplan(SPIPlanPtr plan)
                               1029                 :                : {
                               1030                 :                :     ListCell   *lc;
                               1031                 :                : 
                               1032   [ +  -  -  + ]:           5571 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
 9322 JanWieck@Yahoo.com       1033                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                               1034                 :                : 
                               1035                 :                :     /* Release the plancache entries */
 5552 tgl@sss.pgh.pa.us        1036   [ +  -  +  +  :CBC       11142 :     foreach(lc, plan->plancache_list)
                                              +  + ]
                               1037                 :                :     {
                               1038                 :           5571 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
                               1039                 :                : 
                               1040                 :           5571 :         DropCachedPlan(plansource);
                               1041                 :                :     }
                               1042                 :                : 
                               1043                 :                :     /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
 7198                          1044                 :           5571 :     MemoryContextDelete(plan->plancxt);
                               1045                 :                : 
 9322 JanWieck@Yahoo.com       1046                 :           5571 :     return 0;
                               1047                 :                : }
                               1048                 :                : 
                               1049                 :                : HeapTuple
10669 vadim4o@yahoo.com        1050                 :           1413 : SPI_copytuple(HeapTuple tuple)
                               1051                 :                : {
                               1052                 :                :     MemoryContext oldcxt;
                               1053                 :                :     HeapTuple   ctuple;
                               1054                 :                : 
                               1055         [ -  + ]:           1413 :     if (tuple == NULL)
                               1056                 :                :     {
10669 vadim4o@yahoo.com        1057                 :UBC           0 :         SPI_result = SPI_ERROR_ARGUMENT;
10315 bruce@momjian.us         1058                 :              0 :         return NULL;
                               1059                 :                :     }
                               1060                 :                : 
 3672 tgl@sss.pgh.pa.us        1061         [ -  + ]:CBC        1413 :     if (_SPI_current == NULL)
                               1062                 :                :     {
 3672 tgl@sss.pgh.pa.us        1063                 :UBC           0 :         SPI_result = SPI_ERROR_UNCONNECTED;
                               1064                 :              0 :         return NULL;
                               1065                 :                :     }
                               1066                 :                : 
 3672 tgl@sss.pgh.pa.us        1067                 :CBC        1413 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
                               1068                 :                : 
10669 vadim4o@yahoo.com        1069                 :           1413 :     ctuple = heap_copytuple(tuple);
                               1070                 :                : 
 3672 tgl@sss.pgh.pa.us        1071                 :           1413 :     MemoryContextSwitchTo(oldcxt);
                               1072                 :                : 
10315 bruce@momjian.us         1073                 :           1413 :     return ctuple;
                               1074                 :                : }
                               1075                 :                : 
                               1076                 :                : HeapTupleHeader
 8276 tgl@sss.pgh.pa.us        1077                 :          11278 : SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
                               1078                 :                : {
                               1079                 :                :     MemoryContext oldcxt;
                               1080                 :                :     HeapTupleHeader dtup;
                               1081                 :                : 
 9154                          1082   [ +  -  -  + ]:          11278 :     if (tuple == NULL || tupdesc == NULL)
                               1083                 :                :     {
 9154 tgl@sss.pgh.pa.us        1084                 :UBC           0 :         SPI_result = SPI_ERROR_ARGUMENT;
                               1085                 :              0 :         return NULL;
                               1086                 :                :     }
                               1087                 :                : 
 3672 tgl@sss.pgh.pa.us        1088         [ -  + ]:CBC       11278 :     if (_SPI_current == NULL)
                               1089                 :                :     {
 3672 tgl@sss.pgh.pa.us        1090                 :UBC           0 :         SPI_result = SPI_ERROR_UNCONNECTED;
                               1091                 :              0 :         return NULL;
                               1092                 :                :     }
                               1093                 :                : 
                               1094                 :                :     /* For RECORD results, make sure a typmod has been assigned */
 8276 tgl@sss.pgh.pa.us        1095         [ +  + ]:CBC       11278 :     if (tupdesc->tdtypeid == RECORDOID &&
                               1096         [ -  + ]:           3261 :         tupdesc->tdtypmod < 0)
 8276 tgl@sss.pgh.pa.us        1097                 :UBC           0 :         assign_record_type_typmod(tupdesc);
                               1098                 :                : 
 3672 tgl@sss.pgh.pa.us        1099                 :CBC       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                 :                : 
 4594                          1108                 :          11278 :     dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
                               1109                 :                : 
 3672                          1110                 :          11278 :     MemoryContextSwitchTo(oldcxt);
                               1111                 :                : 
 8276                          1112                 :          11278 :     return dtup;
                               1113                 :                : }
                               1114                 :                : 
                               1115                 :                : HeapTuple
  151 peter@eisentraut.org     1116                 :UNC           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                 :                : 
 8474 tgl@sss.pgh.pa.us        1126   [ #  #  #  #  :UBC           0 :     if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
                                     #  #  #  #  #  
                                                 # ]
                               1127                 :                :     {
10669 vadim4o@yahoo.com        1128                 :              0 :         SPI_result = SPI_ERROR_ARGUMENT;
10315 bruce@momjian.us         1129                 :              0 :         return NULL;
                               1130                 :                :     }
                               1131                 :                : 
 3672 tgl@sss.pgh.pa.us        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                 :                : 
10669 vadim4o@yahoo.com        1140                 :              0 :     SPI_result = 0;
                               1141                 :                : 
                               1142                 :              0 :     numberOfAttributes = rel->rd_att->natts;
  353 michael@paquier.xyz      1143                 :              0 :     v = palloc_array(Datum, numberOfAttributes);
                               1144                 :              0 :     n = palloc_array(bool, numberOfAttributes);
                               1145                 :                : 
                               1146                 :                :     /* fetch old values and nulls */
 6600 tgl@sss.pgh.pa.us        1147                 :              0 :     heap_deform_tuple(tuple, rel->rd_att, v, n);
                               1148                 :                : 
                               1149                 :                :     /* replace values and nulls */
10669 vadim4o@yahoo.com        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];
 1907 michael@paquier.xyz      1155   [ #  #  #  # ]:              0 :         n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n');
                               1156                 :                :     }
                               1157                 :                : 
10315 bruce@momjian.us         1158         [ #  # ]:              0 :     if (i == natts)             /* no errors in *attnum */
                               1159                 :                :     {
 6600 tgl@sss.pgh.pa.us        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                 :                :          */
   19 andres@anarazel.de       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;
 8853 tgl@sss.pgh.pa.us        1175                 :              0 :         mtuple->t_self = tuple->t_self;
                               1176                 :              0 :         mtuple->t_tableOid = tuple->t_tableOid;
                               1177                 :                :     }
                               1178                 :                :     else
                               1179                 :                :     {
10669 vadim4o@yahoo.com        1180                 :              0 :         mtuple = NULL;
                               1181                 :              0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
                               1182                 :                :     }
                               1183                 :                : 
                               1184                 :              0 :     pfree(v);
                               1185                 :              0 :     pfree(n);
                               1186                 :                : 
 3672 tgl@sss.pgh.pa.us        1187                 :              0 :     MemoryContextSwitchTo(oldcxt);
                               1188                 :                : 
10315 bruce@momjian.us         1189                 :              0 :     return mtuple;
                               1190                 :                : }
                               1191                 :                : 
                               1192                 :                : int
 8734 tgl@sss.pgh.pa.us        1193                 :CBC       13110 : SPI_fnumber(TupleDesc tupdesc, const char *fname)
                               1194                 :                : {
                               1195                 :                :     int         res;
                               1196                 :                :     const FormData_pg_attribute *sysatt;
                               1197                 :                : 
10674 bruce@momjian.us         1198         [ +  + ]:          70936 :     for (res = 0; res < tupdesc->natts; res++)
                               1199                 :                :     {
 3387 andres@anarazel.de       1200                 :          70929 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, res);
                               1201                 :                : 
                               1202         [ +  + ]:          70929 :         if (namestrcmp(&attr->attname, fname) == 0 &&
                               1203         [ +  - ]:          13103 :             !attr->attisdropped)
10315 bruce@momjian.us         1204                 :          13103 :             return res + 1;
                               1205                 :                :     }
                               1206                 :                : 
 2930 andres@anarazel.de       1207                 :              7 :     sysatt = SystemAttributeByName(fname);
 9167 tgl@sss.pgh.pa.us        1208         [ -  + ]:              7 :     if (sysatt != NULL)
 9167 tgl@sss.pgh.pa.us        1209                 :UBC           0 :         return sysatt->attnum;
                               1210                 :                : 
                               1211                 :                :     /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
10315 bruce@momjian.us         1212                 :CBC           7 :     return SPI_ERROR_NOATTRIBUTE;
                               1213                 :                : }
                               1214                 :                : 
                               1215                 :                : char *
10670 vadim4o@yahoo.com        1216                 :            644 : SPI_fname(TupleDesc tupdesc, int fnumber)
                               1217                 :                : {
                               1218                 :                :     const FormData_pg_attribute *att;
                               1219                 :                : 
                               1220                 :            644 :     SPI_result = 0;
                               1221                 :                : 
 9167 tgl@sss.pgh.pa.us        1222   [ +  -  +  -  :            644 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                                              -  + ]
                               1223                 :                :         fnumber <= FirstLowInvalidHeapAttributeNumber)
                               1224                 :                :     {
10670 vadim4o@yahoo.com        1225                 :UBC           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
10315 bruce@momjian.us         1226                 :              0 :         return NULL;
                               1227                 :                :     }
                               1228                 :                : 
 9167 tgl@sss.pgh.pa.us        1229         [ +  - ]:CBC         644 :     if (fnumber > 0)
 3387 andres@anarazel.de       1230                 :            644 :         att = TupleDescAttr(tupdesc, fnumber - 1);
                               1231                 :                :     else
 2930 andres@anarazel.de       1232                 :UBC           0 :         att = SystemAttributeDefinition(fnumber);
                               1233                 :                : 
 9167 tgl@sss.pgh.pa.us        1234                 :CBC         644 :     return pstrdup(NameStr(att->attname));
                               1235                 :                : }
                               1236                 :                : 
                               1237                 :                : char *
10674 bruce@momjian.us         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                 :                : 
 6617 tgl@sss.pgh.pa.us        1248   [ +  -  +  -  :           5609 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                                              -  + ]
                               1249                 :                :         fnumber <= FirstLowInvalidHeapAttributeNumber)
                               1250                 :                :     {
10652 vadim4o@yahoo.com        1251                 :UBC           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
10315 bruce@momjian.us         1252                 :              0 :         return NULL;
                               1253                 :                :     }
                               1254                 :                : 
 4773 tgl@sss.pgh.pa.us        1255                 :CBC        5609 :     val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
10674 bruce@momjian.us         1256         [ +  + ]:           5609 :     if (isnull)
10315                          1257                 :             66 :         return NULL;
                               1258                 :                : 
 9167 tgl@sss.pgh.pa.us        1259         [ +  - ]:           5543 :     if (fnumber > 0)
 3387 andres@anarazel.de       1260                 :           5543 :         typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
                               1261                 :                :     else
 2930 andres@anarazel.de       1262                 :UBC           0 :         typoid = (SystemAttributeDefinition(fnumber))->atttypid;
                               1263                 :                : 
 7881 tgl@sss.pgh.pa.us        1264                 :CBC        5543 :     getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
                               1265                 :                : 
 4773                          1266                 :           5543 :     return OidOutputFunctionCall(foutoid, val);
                               1267                 :                : }
                               1268                 :                : 
                               1269                 :                : Datum
10502 bruce@momjian.us         1270                 :          36059 : SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
                               1271                 :                : {
10674                          1272                 :          36059 :     SPI_result = 0;
                               1273                 :                : 
 6617 tgl@sss.pgh.pa.us        1274   [ +  -  +  -  :          36059 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                                              -  + ]
                               1275                 :                :         fnumber <= FirstLowInvalidHeapAttributeNumber)
                               1276                 :                :     {
10652 vadim4o@yahoo.com        1277                 :UBC           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
 9167 tgl@sss.pgh.pa.us        1278                 :              0 :         *isnull = true;
  477                          1279                 :              0 :         return (Datum) 0;
                               1280                 :                :     }
                               1281                 :                : 
 9167 tgl@sss.pgh.pa.us        1282                 :CBC       36059 :     return heap_getattr(tuple, fnumber, tupdesc, isnull);
                               1283                 :                : }
                               1284                 :                : 
                               1285                 :                : char *
10674 bruce@momjian.us         1286                 :UBC           0 : SPI_gettype(TupleDesc tupdesc, int fnumber)
                               1287                 :                : {
                               1288                 :                :     Oid         typoid;
                               1289                 :                :     HeapTuple   typeTuple;
                               1290                 :                :     char       *result;
                               1291                 :                : 
                               1292                 :              0 :     SPI_result = 0;
                               1293                 :                : 
 9167 tgl@sss.pgh.pa.us        1294   [ #  #  #  #  :              0 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                                              #  # ]
                               1295                 :                :         fnumber <= FirstLowInvalidHeapAttributeNumber)
                               1296                 :                :     {
10674 bruce@momjian.us         1297                 :              0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
10315                          1298                 :              0 :         return NULL;
                               1299                 :                :     }
                               1300                 :                : 
 9167 tgl@sss.pgh.pa.us        1301         [ #  # ]:              0 :     if (fnumber > 0)
 3387 andres@anarazel.de       1302                 :              0 :         typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
                               1303                 :                :     else
 2930                          1304                 :              0 :         typoid = (SystemAttributeDefinition(fnumber))->atttypid;
                               1305                 :                : 
 6131 rhaas@postgresql.org     1306                 :              0 :     typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
                               1307                 :                : 
10674 bruce@momjian.us         1308         [ #  # ]:              0 :     if (!HeapTupleIsValid(typeTuple))
                               1309                 :                :     {
                               1310                 :              0 :         SPI_result = SPI_ERROR_TYPUNKNOWN;
10315                          1311                 :              0 :         return NULL;
                               1312                 :                :     }
                               1313                 :                : 
 9508 tgl@sss.pgh.pa.us        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
10674 bruce@momjian.us         1326                 :CBC         782 : SPI_gettypeid(TupleDesc tupdesc, int fnumber)
                               1327                 :                : {
                               1328                 :            782 :     SPI_result = 0;
                               1329                 :                : 
 9167 tgl@sss.pgh.pa.us        1330   [ +  -  +  -  :            782 :     if (fnumber > tupdesc->natts || fnumber == 0 ||
                                              -  + ]
                               1331                 :                :         fnumber <= FirstLowInvalidHeapAttributeNumber)
                               1332                 :                :     {
10674 bruce@momjian.us         1333                 :UBC           0 :         SPI_result = SPI_ERROR_NOATTRIBUTE;
10315                          1334                 :              0 :         return InvalidOid;
                               1335                 :                :     }
                               1336                 :                : 
 9167 tgl@sss.pgh.pa.us        1337         [ +  - ]:CBC         782 :     if (fnumber > 0)
 3387 andres@anarazel.de       1338                 :            782 :         return TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
                               1339                 :                :     else
 2930 andres@anarazel.de       1340                 :UBC           0 :         return (SystemAttributeDefinition(fnumber))->atttypid;
                               1341                 :                : }
                               1342                 :                : 
                               1343                 :                : char *
10674 bruce@momjian.us         1344                 :CBC         187 : SPI_getrelname(Relation rel)
                               1345                 :                : {
 9883                          1346                 :            187 :     return pstrdup(RelationGetRelationName(rel));
                               1347                 :                : }
                               1348                 :                : 
                               1349                 :                : char *
 7914 neilc@samurai.com        1350                 :            143 : SPI_getnspname(Relation rel)
                               1351                 :                : {
 7714 bruce@momjian.us         1352                 :            143 :     return get_namespace_name(RelationGetNamespace(rel));
                               1353                 :                : }
                               1354                 :                : 
                               1355                 :                : void *
10502                          1356                 :             28 : SPI_palloc(Size size)
                               1357                 :                : {
 3672 tgl@sss.pgh.pa.us        1358         [ -  + ]:             28 :     if (_SPI_current == NULL)
 3672 tgl@sss.pgh.pa.us        1359         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_palloc called while not connected to SPI");
                               1360                 :                : 
 3672 tgl@sss.pgh.pa.us        1361                 :CBC          28 :     return MemoryContextAlloc(_SPI_current->savedcxt, size);
                               1362                 :                : }
                               1363                 :                : 
                               1364                 :                : void *
10502 bruce@momjian.us         1365                 :UBC           0 : SPI_repalloc(void *pointer, Size size)
                               1366                 :                : {
                               1367                 :                :     /* No longer need to worry which context chunk was in... */
 9649 tgl@sss.pgh.pa.us        1368                 :              0 :     return repalloc(pointer, size);
                               1369                 :                : }
                               1370                 :                : 
                               1371                 :                : void
10502 bruce@momjian.us         1372                 :              0 : SPI_pfree(void *pointer)
                               1373                 :                : {
                               1374                 :                :     /* No longer need to worry which context chunk was in... */
                               1375                 :              0 :     pfree(pointer);
10657 vadim4o@yahoo.com        1376                 :              0 : }
                               1377                 :                : 
                               1378                 :                : Datum
 4216 tgl@sss.pgh.pa.us        1379                 :CBC        3718 : SPI_datumTransfer(Datum value, bool typByVal, int typLen)
                               1380                 :                : {
                               1381                 :                :     MemoryContext oldcxt;
                               1382                 :                :     Datum       result;
                               1383                 :                : 
 3672                          1384         [ -  + ]:           3718 :     if (_SPI_current == NULL)
 3672 tgl@sss.pgh.pa.us        1385         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
                               1386                 :                : 
 3672 tgl@sss.pgh.pa.us        1387                 :CBC        3718 :     oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
                               1388                 :                : 
 4216                          1389                 :           3718 :     result = datumTransfer(value, typByVal, typLen);
                               1390                 :                : 
 3672                          1391                 :           3718 :     MemoryContextSwitchTo(oldcxt);
                               1392                 :                : 
 4216                          1393                 :           3718 :     return result;
                               1394                 :                : }
                               1395                 :                : 
                               1396                 :                : void
 9844 JanWieck@Yahoo.com       1397                 :UBC           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
 9322 JanWieck@Yahoo.com       1404                 :CBC      142545 : SPI_freetuptable(SPITupleTable *tuptable)
                               1405                 :                : {
 4874 tgl@sss.pgh.pa.us        1406                 :         142545 :     bool        found = false;
                               1407                 :                : 
                               1408                 :                :     /* ignore call if NULL pointer */
                               1409         [ +  + ]:         142545 :     if (tuptable == NULL)
                               1410                 :          88485 :         return;
                               1411                 :                : 
                               1412                 :                :     /*
                               1413                 :                :      * Search only the topmost SPI context for a matching tuple table.
                               1414                 :                :      */
 3672                          1415         [ +  - ]:          54060 :     if (_SPI_current != NULL)
                               1416                 :                :     {
                               1417                 :                :         slist_mutable_iter siter;
                               1418                 :                : 
                               1419                 :                :         /* find tuptable in active list, then remove it */
 4874                          1420   [ +  -  +  -  :          54062 :         slist_foreach_modify(siter, &_SPI_current->tuptables)
                                              +  - ]
                               1421                 :                :         {
                               1422                 :                :             SPITupleTable *tt;
                               1423                 :                : 
                               1424                 :          54062 :             tt = slist_container(SPITupleTable, next, siter.cur);
                               1425         [ +  + ]:          54062 :             if (tt == tuptable)
                               1426                 :                :             {
                               1427                 :          54060 :                 slist_delete_current(&siter);
                               1428                 :          54060 :                 found = true;
                               1429                 :          54060 :                 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         [ -  + ]:          54060 :     if (!found)
                               1441                 :                :     {
 4874 tgl@sss.pgh.pa.us        1442         [ #  # ]:UBC           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 */
 4874 tgl@sss.pgh.pa.us        1447         [ -  + ]:CBC       54060 :     if (tuptable == _SPI_current->tuptable)
 4874 tgl@sss.pgh.pa.us        1448                 :UBC           0 :         _SPI_current->tuptable = NULL;
 4874 tgl@sss.pgh.pa.us        1449         [ +  + ]:CBC       54060 :     if (tuptable == SPI_tuptable)
                               1450                 :          48817 :         SPI_tuptable = NULL;
                               1451                 :                : 
                               1452                 :                :     /* release all memory belonging to tuptable */
                               1453                 :          54060 :     MemoryContextDelete(tuptable->tuptabcxt);
                               1454                 :                : }
                               1455                 :                : 
                               1456                 :                : 
                               1457                 :                : /*
                               1458                 :                :  * SPI_cursor_open()
                               1459                 :                :  *
                               1460                 :                :  *  Open a prepared SPI plan as a portal
                               1461                 :                :  */
                               1462                 :                : Portal
 7198                          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 */
 6233                          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
 6754 tgl@sss.pgh.pa.us        1490                 :UBC           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;
 2154                          1512                 :              0 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 6754                          1513                 :              0 :     plan.cursor_options = cursorOptions;
                               1514                 :              0 :     plan.nargs = nargs;
                               1515                 :              0 :     plan.argtypes = argtypes;
 6233                          1516                 :              0 :     plan.parserSetup = NULL;
                               1517                 :              0 :     plan.parserSetupArg = NULL;
                               1518                 :                : 
                               1519                 :                :     /* build transient ParamListInfo in executor context */
 6754                          1520                 :              0 :     paramLI = _SPI_convert_params(nargs, argtypes,
                               1521                 :                :                                   Values, Nulls);
                               1522                 :                : 
 5076                          1523                 :              0 :     _SPI_prepare_plan(src, &plan);
                               1524                 :                : 
                               1525                 :                :     /* We needn't copy the plan; SPI_cursor_open_internal will do so */
                               1526                 :                : 
 6233                          1527                 :              0 :     result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
                               1528                 :                : 
                               1529                 :                :     /* And clean up */
 6754                          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
 6233 tgl@sss.pgh.pa.us        1543                 :CBC        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
 2132                          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)
 2132 tgl@sss.pgh.pa.us        1559         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_cursor_parse_open called with invalid arguments");
                               1560                 :                : 
 2360 tgl@sss.pgh.pa.us        1561                 :CBC        6370 :     SPI_result = _SPI_begin_call(true);
                               1562         [ -  + ]:           6370 :     if (SPI_result < 0)
 2132 tgl@sss.pgh.pa.us        1563         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_cursor_parse_open called while not connected");
                               1564                 :                : 
 2360 tgl@sss.pgh.pa.us        1565                 :CBC        6370 :     memset(&plan, 0, sizeof(_SPI_plan));
                               1566                 :           6370 :     plan.magic = _SPI_PLAN_MAGIC;
 2154                          1567                 :           6370 :     plan.parse_mode = RAW_PARSE_DEFAULT;
 2132                          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                 :                : 
 2360                          1575                 :           6370 :     _SPI_prepare_plan(src, &plan);
                               1576                 :                : 
                               1577                 :                :     /* We needn't copy the plan; SPI_cursor_open_internal will do so */
                               1578                 :                : 
 2132                          1579                 :           6370 :     result = SPI_cursor_open_internal(name, &plan,
                               1580                 :           6370 :                                       options->params, options->read_only);
                               1581                 :                : 
                               1582                 :                :     /* And clean up */
 2360                          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
 6754                          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                 :                :      */
 7198                          1612         [ -  + ]:           8341 :     if (!SPI_is_cursor_plan(plan))
                               1613                 :                :     {
                               1614                 :                :         /* try to give a good error message */
                               1615                 :                :         const char *cmdtag;
                               1616                 :                : 
 7198 tgl@sss.pgh.pa.us        1617         [ #  # ]:UBC           0 :         if (list_length(plan->plancache_list) != 1)
 7411                          1618         [ #  # ]:              0 :             ereport(ERROR,
                               1619                 :                :                     (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
                               1620                 :                :                      errmsg("cannot open multi-query plan as cursor")));
 7198                          1621                 :              0 :         plansource = (CachedPlanSource *) linitial(plan->plancache_list);
                               1622                 :                :         /* A SELECT that fails SPI_is_cursor_plan() must be SELECT INTO */
 1925                          1623         [ #  # ]:              0 :         if (plansource->commandTag == CMDTAG_SELECT)
                               1624                 :              0 :             cmdtag = "SELECT INTO";
                               1625                 :                :         else
                               1626                 :              0 :             cmdtag = GetCommandTagName(plansource->commandTag);
 7413                          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                 :                : 
 7198 tgl@sss.pgh.pa.us        1633         [ -  + ]:CBC        8341 :     Assert(list_length(plan->plancache_list) == 1);
                               1634                 :           8341 :     plansource = (CachedPlanSource *) linitial(plan->plancache_list);
                               1635                 :                : 
                               1636                 :                :     /* Push the SPI stack */
 5552                          1637         [ -  + ]:           8341 :     if (_SPI_begin_call(true) < 0)
 6864 tgl@sss.pgh.pa.us        1638         [ #  # ]:UBC           0 :         elog(ERROR, "SPI_cursor_open called while not connected");
                               1639                 :                : 
                               1640                 :                :     /* Reset SPI result (note we deliberately don't touch lastoid) */
 9322 JanWieck@Yahoo.com       1641                 :CBC        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 */
 8611 tgl@sss.pgh.pa.us        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 */
 3269 peter_e@gmx.net          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                 :                :      */
 2154 tgl@sss.pgh.pa.us        1666                 :           8341 :     spicallbackarg.query = plansource->query_string;
                               1667                 :           8341 :     spicallbackarg.mode = plan->parse_mode;
 5050                          1668                 :           8341 :     spierrcontext.callback = _SPI_error_callback;
 2154                          1669                 :           8341 :     spierrcontext.arg = &spicallbackarg;
 5050                          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 */
 2133                          1680                 :           8341 :     cplan = GetCachedPlan(plansource, paramLI, NULL, _SPI_current->queryEnv);
 5552                          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                 :                :          */
 3269 peter_e@gmx.net          1691                 :           6497 :         oldcontext = MemoryContextSwitchTo(portal->portalContext);
 5552 tgl@sss.pgh.pa.us        1692                 :           6497 :         stmt_list = copyObject(stmt_list);
 7198                          1693                 :           6497 :         MemoryContextSwitchTo(oldcontext);
 2133                          1694                 :           6497 :         ReleaseCachedPlan(cplan, NULL);
 7198                          1695                 :           6497 :         cplan = NULL;           /* portal shouldn't depend on cplan */
                               1696                 :                :     }
                               1697                 :                : 
                               1698                 :                :     /*
                               1699                 :                :      * Set up the portal.
                               1700                 :                :      */
 8611                          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                 :                :      */
 7166                          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 &&
 3447                          1716         [ +  - ]:            298 :             linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
 3519                          1717   [ +  +  +  + ]:            587 :             linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
                               1718                 :            289 :             ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
 7166                          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                 :                :      */
 6975                          1729         [ +  + ]:           8337 :     if (portal->cursorOptions & CURSOR_OPT_SCROLL)
                               1730                 :                :     {
                               1731         [ +  - ]:            281 :         if (list_length(stmt_list) == 1 &&
 3447                          1732         [ +  - ]:            281 :             linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
 3519                          1733         [ -  + ]:            281 :             linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
 6975 tgl@sss.pgh.pa.us        1734         [ #  # ]:UBC           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. */
 3525 kgrittn@postgresql.o     1741                 :CBC        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                 :                :      */
 2508 rhaas@postgresql.org     1750         [ +  + ]:           8337 :     if (read_only)
                               1751                 :                :     {
                               1752                 :                :         ListCell   *lc;
                               1753                 :                : 
 7196 tgl@sss.pgh.pa.us        1754   [ +  -  +  +  :            216 :         foreach(lc, stmt_list)
                                              +  + ]
                               1755                 :                :         {
 3519                          1756                 :            112 :             PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
                               1757                 :                : 
 7196                          1758         [ +  + ]:            112 :             if (!CommandIsReadOnly(pstmt))
 2508 rhaas@postgresql.org     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. */
 5115 tgl@sss.pgh.pa.us        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                 :                :      */
 6233                          1781         [ +  + ]:           8329 :     if (paramLI)
                               1782                 :                :     {
 3269 peter_e@gmx.net          1783                 :            461 :         oldcontext = MemoryContextSwitchTo(portal->portalContext);
 6233 tgl@sss.pgh.pa.us        1784                 :            461 :         paramLI = copyParamList(paramLI);
                               1785                 :            461 :         MemoryContextSwitchTo(oldcontext);
                               1786                 :                :     }
                               1787                 :                : 
                               1788                 :                :     /*
                               1789                 :                :      * Start portal execution.
                               1790                 :                :      */
 5115                          1791                 :           8329 :     PortalStart(portal, paramLI, 0, snapshot);
                               1792                 :                : 
 7411                          1793         [ -  + ]:           8325 :     Assert(portal->strategy != PORTAL_MULTI_QUERY);
                               1794                 :                : 
                               1795                 :                :     /* Pop the error context stack */
 3511                          1796                 :           8325 :     error_context_stack = spierrcontext.previous;
                               1797                 :                : 
                               1798                 :                :     /* Pop the SPI stack */
 5552                          1799                 :           8325 :     _SPI_end_call(true);
                               1800                 :                : 
                               1801                 :                :     /* Return the created portal */
 9322 JanWieck@Yahoo.com       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
 8734 tgl@sss.pgh.pa.us        1812                 :            414 : SPI_cursor_find(const char *name)
                               1813                 :                : {
 9322 JanWieck@Yahoo.com       1814                 :            414 :     return GetPortalByName(name);
                               1815                 :                : }
                               1816                 :                : 
                               1817                 :                : 
                               1818                 :                : /*
                               1819                 :                :  * SPI_cursor_fetch()
                               1820                 :                :  *
                               1821                 :                :  *  Fetch rows in a cursor
                               1822                 :                :  */
                               1823                 :                : void
 7391 bruce@momjian.us         1824                 :          29625 : SPI_cursor_fetch(Portal portal, bool forward, long count)
                               1825                 :                : {
 7166 tgl@sss.pgh.pa.us        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 */
 9322 JanWieck@Yahoo.com       1830                 :          29616 : }
                               1831                 :                : 
                               1832                 :                : 
                               1833                 :                : /*
                               1834                 :                :  * SPI_cursor_move()
                               1835                 :                :  *
                               1836                 :                :  *  Move in a cursor
                               1837                 :                :  */
                               1838                 :                : void
 7391 bruce@momjian.us         1839                 :UBC           0 : SPI_cursor_move(Portal portal, bool forward, long count)
                               1840                 :                : {
 7166 tgl@sss.pgh.pa.us        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
 7166 tgl@sss.pgh.pa.us        1853                 :CBC         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);
 9322 JanWieck@Yahoo.com       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                 :                : {
 9185 tgl@sss.pgh.pa.us        1882         [ -  + ]:           8224 :     if (!PortalIsValid(portal))
 9322 JanWieck@Yahoo.com       1883         [ #  # ]:UBC           0 :         elog(ERROR, "invalid portal in SPI cursor operation");
                               1884                 :                : 
 8647 bruce@momjian.us         1885                 :CBC        8224 :     PortalDrop(portal, false);
 9322 JanWieck@Yahoo.com       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
 7198 tgl@sss.pgh.pa.us        1893                 :UBC           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                 :                :     {
 8287                          1898                 :              0 :         SPI_result = SPI_ERROR_ARGUMENT;
                               1899                 :              0 :         return InvalidOid;
                               1900                 :                :     }
 7198                          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                 :                :     {
 8287                          1912                 :              0 :         SPI_result = SPI_ERROR_ARGUMENT;
                               1913                 :              0 :         return -1;
                               1914                 :                :     }
 7198                          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
 7198 tgl@sss.pgh.pa.us        1928                 :CBC        8341 : SPI_is_cursor_plan(SPIPlanPtr plan)
                               1929                 :                : {
                               1930                 :                :     CachedPlanSource *plansource;
                               1931                 :                : 
                               1932   [ +  -  -  + ]:           8341 :     if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
                               1933                 :                :     {
 8287 tgl@sss.pgh.pa.us        1934                 :UBC           0 :         SPI_result = SPI_ERROR_ARGUMENT;
                               1935                 :              0 :         return false;
                               1936                 :                :     }
                               1937                 :                : 
 7198 tgl@sss.pgh.pa.us        1938         [ -  + ]:CBC        8341 :     if (list_length(plan->plancache_list) != 1)
                               1939                 :                :     {
 6864 tgl@sss.pgh.pa.us        1940                 :UBC           0 :         SPI_result = 0;
 7411                          1941                 :              0 :         return false;           /* not exactly 1 pre-rewrite command */
                               1942                 :                :     }
 7198 tgl@sss.pgh.pa.us        1943                 :CBC        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                 :                :      */
 6864                          1950                 :           8341 :     SPI_result = 0;
                               1951                 :                : 
                               1952                 :                :     /* Does it return tuples? */
 7198                          1953         [ +  - ]:           8341 :     if (plansource->resultDesc)
                               1954                 :           8341 :         return true;
                               1955                 :                : 
 8287 tgl@sss.pgh.pa.us        1956                 :UBC           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
 6648 tgl@sss.pgh.pa.us        1966                 :CBC        1675 : SPI_plan_is_valid(SPIPlanPtr plan)
                               1967                 :                : {
                               1968                 :                :     ListCell   *lc;
                               1969                 :                : 
 5552                          1970         [ -  + ]:           1675 :     Assert(plan->magic == _SPI_PLAN_MAGIC);
                               1971                 :                : 
                               1972   [ +  -  +  +  :           3076 :     foreach(lc, plan->plancache_list)
                                              +  + ]
                               1973                 :                :     {
                               1974                 :           1675 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
                               1975                 :                : 
                               1976         [ +  + ]:           1675 :         if (!CachedPlanIsValid(plansource))
                               1977                 :            274 :             return false;
                               1978                 :                :     }
                               1979                 :           1401 :     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 *
 8155                          1990                 :             60 : SPI_result_code_string(int code)
                               1991                 :                : {
                               1992                 :                :     static char buf[64];
                               1993                 :                : 
                               1994   [ -  -  -  -  :             60 :     switch (code)
                                     -  -  +  -  -  
                                     -  -  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                     -  -  -  -  -  
                                           -  -  - ]
                               1995                 :                :     {
 8155 tgl@sss.pgh.pa.us        1996                 :UBC           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";
 8155 tgl@sss.pgh.pa.us        2008                 :CBC           3 :         case SPI_ERROR_TRANSACTION:
                               2009                 :              3 :             return "SPI_ERROR_TRANSACTION";
 8155 tgl@sss.pgh.pa.us        2010                 :UBC           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";
 3529 kgrittn@postgresql.o     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";
 8155 tgl@sss.pgh.pa.us        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";
 8155 tgl@sss.pgh.pa.us        2026                 :CBC           1 :         case SPI_OK_UTILITY:
                               2027                 :              1 :             return "SPI_OK_UTILITY";
                               2028                 :             11 :         case SPI_OK_SELECT:
                               2029                 :             11 :             return "SPI_OK_SELECT";
 8155 tgl@sss.pgh.pa.us        2030                 :UBC           0 :         case SPI_OK_SELINTO:
                               2031                 :              0 :             return "SPI_OK_SELINTO";
 8155 tgl@sss.pgh.pa.us        2032                 :CBC          45 :         case SPI_OK_INSERT:
                               2033                 :             45 :             return "SPI_OK_INSERT";
 8155 tgl@sss.pgh.pa.us        2034                 :UBC           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";
 7398                          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";
 6520 heikki.linnakangas@i     2046                 :              0 :         case SPI_OK_REWRITTEN:
                               2047                 :              0 :             return "SPI_OK_REWRITTEN";
 3529 kgrittn@postgresql.o     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";
 1375 dean.a.rasheed@gmail     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";
  986                          2056                 :              0 :         case SPI_OK_MERGE_RETURNING:
                               2057                 :              0 :             return "SPI_OK_MERGE_RETURNING";
                               2058                 :                :     }
                               2059                 :                :     /* Unrecognized code ... return something useful ... */
 8155 tgl@sss.pgh.pa.us        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 *
 5050 tgl@sss.pgh.pa.us        2075                 :CBC       39838 : SPI_plan_get_plan_sources(SPIPlanPtr plan)
                               2076                 :                : {
                               2077         [ -  + ]:          39838 :     Assert(plan->magic == _SPI_PLAN_MAGIC);
                               2078                 :          39838 :     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                 :          19304 : SPI_plan_get_cached_plan(SPIPlanPtr plan)
                               2095                 :                : {
                               2096                 :                :     CachedPlanSource *plansource;
                               2097                 :                :     CachedPlan *cplan;
                               2098                 :                :     SPICallbackArg spicallbackarg;
                               2099                 :                :     ErrorContextCallback spierrcontext;
                               2100                 :                : 
                               2101         [ -  + ]:          19304 :     Assert(plan->magic == _SPI_PLAN_MAGIC);
                               2102                 :                : 
                               2103                 :                :     /* Can't support one-shot plans here */
                               2104         [ -  + ]:          19304 :     if (plan->oneshot)
 5050 tgl@sss.pgh.pa.us        2105                 :UBC           0 :         return NULL;
                               2106                 :                : 
                               2107                 :                :     /* Must have exactly one CachedPlanSource */
 5050 tgl@sss.pgh.pa.us        2108         [ -  + ]:CBC       19304 :     if (list_length(plan->plancache_list) != 1)
 5050 tgl@sss.pgh.pa.us        2109                 :UBC           0 :         return NULL;
 5050 tgl@sss.pgh.pa.us        2110                 :CBC       19304 :     plansource = (CachedPlanSource *) linitial(plan->plancache_list);
                               2111                 :                : 
                               2112                 :                :     /* Setup error traceback support for ereport() */
 2154                          2113                 :          19304 :     spicallbackarg.query = plansource->query_string;
                               2114                 :          19304 :     spicallbackarg.mode = plan->parse_mode;
 5050                          2115                 :          19304 :     spierrcontext.callback = _SPI_error_callback;
 2154                          2116                 :          19304 :     spierrcontext.arg = &spicallbackarg;
 5050                          2117                 :          19304 :     spierrcontext.previous = error_context_stack;
                               2118                 :          19304 :     error_context_stack = &spierrcontext;
                               2119                 :                : 
                               2120                 :                :     /* Get the generic plan for the query */
 2133                          2121                 :          19304 :     cplan = GetCachedPlan(plansource, NULL,
                               2122                 :          19304 :                           plan->saved ? CurrentResourceOwner : NULL,
 3529 kgrittn@postgresql.o     2123         [ +  + ]:          19304 :                           _SPI_current->queryEnv);
 5050 tgl@sss.pgh.pa.us        2124         [ -  + ]:          19275 :     Assert(cplan == plansource->gplan);
                               2125                 :                : 
                               2126                 :                :     /* Pop the error context stack */
                               2127                 :          19275 :     error_context_stack = spierrcontext.previous;
                               2128                 :                : 
                               2129                 :          19275 :     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
 8605                          2141                 :          63067 : spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
                               2142                 :                : {
                               2143                 :                :     SPITupleTable *tuptable;
                               2144                 :                :     MemoryContext oldcxt;
                               2145                 :                :     MemoryContext tuptabcxt;
                               2146                 :                : 
 3672                          2147         [ -  + ]:          63067 :     if (_SPI_current == NULL)
 3672 tgl@sss.pgh.pa.us        2148         [ #  # ]:UBC           0 :         elog(ERROR, "spi_dest_startup called while not connected to SPI");
                               2149                 :                : 
 8712 tgl@sss.pgh.pa.us        2150         [ -  + ]:CBC       63067 :     if (_SPI_current->tuptable != NULL)
 8531 tgl@sss.pgh.pa.us        2151         [ #  # ]:UBC           0 :         elog(ERROR, "improper call to spi_dest_startup");
                               2152                 :                : 
                               2153                 :                :     /* We create the tuple table context as a child of procCxt */
                               2154                 :                : 
 8712 tgl@sss.pgh.pa.us        2155                 :CBC       63067 :     oldcxt = _SPI_procmem();    /* switch to procedure memory context */
                               2156                 :                : 
                               2157                 :          63067 :     tuptabcxt = AllocSetContextCreate(CurrentMemoryContext,
                               2158                 :                :                                       "SPI TupTable",
                               2159                 :                :                                       ALLOCSET_DEFAULT_SIZES);
                               2160                 :          63067 :     MemoryContextSwitchTo(tuptabcxt);
                               2161                 :                : 
  353 michael@paquier.xyz      2162                 :          63067 :     _SPI_current->tuptable = tuptable = palloc0_object(SPITupleTable);
 8712 tgl@sss.pgh.pa.us        2163                 :          63067 :     tuptable->tuptabcxt = tuptabcxt;
 4874                          2164                 :          63067 :     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                 :          63067 :     slist_push_head(&_SPI_current->tuptables, &tuptable->next);
                               2172                 :                : 
                               2173                 :                :     /* set up initial allocations */
 2690                          2174                 :          63067 :     tuptable->alloced = 128;
  353 michael@paquier.xyz      2175                 :          63067 :     tuptable->vals = palloc_array(HeapTuple, tuptable->alloced);
 2690 tgl@sss.pgh.pa.us        2176                 :          63067 :     tuptable->numvals = 0;
 8712                          2177                 :          63067 :     tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
                               2178                 :                : 
                               2179                 :          63067 :     MemoryContextSwitchTo(oldcxt);
                               2180                 :          63067 : }
                               2181                 :                : 
                               2182                 :                : /*
                               2183                 :                :  * spi_printtup
                               2184                 :                :  *      store tuple retrieved by Executor into SPITupleTable
                               2185                 :                :  *      of current SPI procedure
                               2186                 :                :  */
                               2187                 :                : bool
 7927                          2188                 :          76275 : spi_printtup(TupleTableSlot *slot, DestReceiver *self)
                               2189                 :                : {
                               2190                 :                :     SPITupleTable *tuptable;
                               2191                 :                :     MemoryContext oldcxt;
                               2192                 :                : 
 3672                          2193         [ -  + ]:          76275 :     if (_SPI_current == NULL)
 3672 tgl@sss.pgh.pa.us        2194         [ #  # ]:UBC           0 :         elog(ERROR, "spi_printtup called while not connected to SPI");
                               2195                 :                : 
10674 bruce@momjian.us         2196                 :CBC       76275 :     tuptable = _SPI_current->tuptable;
                               2197         [ -  + ]:          76275 :     if (tuptable == NULL)
 8531 tgl@sss.pgh.pa.us        2198         [ #  # ]:UBC           0 :         elog(ERROR, "improper call to spi_printtup");
                               2199                 :                : 
 8712 tgl@sss.pgh.pa.us        2200                 :CBC       76275 :     oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
                               2201                 :                : 
 2690                          2202         [ -  + ]:          76275 :     if (tuptable->numvals >= tuptable->alloced)
                               2203                 :                :     {
                               2204                 :                :         /* Double the size of the pointer array */
 2690 tgl@sss.pgh.pa.us        2205                 :UBC           0 :         uint64      newalloced = tuptable->alloced * 2;
                               2206                 :                : 
 3911                          2207                 :              0 :         tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
                               2208                 :                :                                                      newalloced * sizeof(HeapTuple));
 2690                          2209                 :              0 :         tuptable->alloced = newalloced;
                               2210                 :                :     }
                               2211                 :                : 
 2690 tgl@sss.pgh.pa.us        2212                 :CBC       76275 :     tuptable->vals[tuptable->numvals] = ExecCopySlotHeapTuple(slot);
                               2213                 :          76275 :     (tuptable->numvals)++;
                               2214                 :                : 
10674 bruce@momjian.us         2215                 :          76275 :     MemoryContextSwitchTo(oldcxt);
                               2216                 :                : 
 3827 rhaas@postgresql.org     2217                 :          76275 :     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
 5076 tgl@sss.pgh.pa.us        2238                 :          27547 : _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                 :                :      */
 2154                          2249                 :          27547 :     spicallbackarg.query = src;
                               2250                 :          27547 :     spicallbackarg.mode = plan->parse_mode;
 8287                          2251                 :          27547 :     spierrcontext.callback = _SPI_error_callback;
 2154                          2252                 :          27547 :     spierrcontext.arg = &spicallbackarg;
 8287                          2253                 :          27547 :     spierrcontext.previous = error_context_stack;
                               2254                 :          27547 :     error_context_stack = &spierrcontext;
                               2255                 :                : 
                               2256                 :                :     /*
                               2257                 :                :      * Parse the request string into a list of raw parse trees.
                               2258                 :                :      */
 2154                          2259                 :          27547 :     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                 :                :      */
 7198                          2265                 :          27547 :     plancache_list = NIL;
                               2266                 :                : 
 8811                          2267   [ +  -  +  +  :          55032 :     foreach(list_item, raw_parsetree_list)
                                              +  + ]
                               2268                 :                :     {
 3519                          2269                 :          27547 :         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                 :                :          */
 5552                          2277                 :          27547 :         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                 :                :          */
 6233                          2285         [ +  + ]:          27547 :         if (plan->parserSetup != NULL)
                               2286                 :                :         {
                               2287         [ -  + ]:          18580 :             Assert(plan->nargs == 0);
 1730 peter@eisentraut.org     2288                 :          18580 :             stmt_list = pg_analyze_and_rewrite_withcb(parsetree,
                               2289                 :                :                                                       src,
                               2290                 :                :                                                       plan->parserSetup,
                               2291                 :                :                                                       plan->parserSetupArg,
 3529 kgrittn@postgresql.o     2292                 :          18580 :                                                       _SPI_current->queryEnv);
                               2293                 :                :         }
                               2294                 :                :         else
                               2295                 :                :         {
 1730 peter@eisentraut.org     2296                 :           8967 :             stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
                               2297                 :                :                                                            src,
 1661 tgl@sss.pgh.pa.us        2298                 :ECB      (8982) :                                                            plan->argtypes,
                               2299                 :                :                                                            plan->nargs,
 1661 tgl@sss.pgh.pa.us        2300                 :CBC        8967 :                                                            _SPI_current->queryEnv);
                               2301                 :                :         }
                               2302                 :                : 
                               2303                 :                :         /* Finish filling in the CachedPlanSource */
 5552                          2304                 :          27485 :         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                 :                : 
 7198                          2314                 :          27485 :         plancache_list = lappend(plancache_list, plansource);
                               2315                 :                :     }
                               2316                 :                : 
                               2317                 :          27485 :     plan->plancache_list = plancache_list;
 5076                          2318                 :          27485 :     plan->oneshot = false;
                               2319                 :                : 
                               2320                 :                :     /*
                               2321                 :                :      * Pop the error context stack
                               2322                 :                :      */
                               2323                 :          27485 :     error_context_stack = spierrcontext.previous;
                               2324                 :          27485 : }
                               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                 :          14328 : _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                 :                :      */
 2154                          2357                 :          14328 :     spicallbackarg.query = src;
                               2358                 :          14328 :     spicallbackarg.mode = plan->parse_mode;
 5076                          2359                 :          14328 :     spierrcontext.callback = _SPI_error_callback;
 2154                          2360                 :          14328 :     spierrcontext.arg = &spicallbackarg;
 5076                          2361                 :          14328 :     spierrcontext.previous = error_context_stack;
                               2362                 :          14328 :     error_context_stack = &spierrcontext;
                               2363                 :                : 
                               2364                 :                :     /*
                               2365                 :                :      * Parse the request string into a list of raw parse trees.
                               2366                 :                :      */
 2154                          2367                 :          14328 :     raw_parsetree_list = raw_parser(src, plan->parse_mode);
                               2368                 :                : 
                               2369                 :                :     /*
                               2370                 :                :      * Construct plancache entries, but don't do parse analysis yet.
                               2371                 :                :      */
 5076                          2372                 :          14322 :     plancache_list = NIL;
                               2373                 :                : 
                               2374   [ +  -  +  +  :          28649 :     foreach(list_item, raw_parsetree_list)
                                              +  + ]
                               2375                 :                :     {
 3519                          2376                 :          14327 :         RawStmt    *parsetree = lfirst_node(RawStmt, list_item);
                               2377                 :                :         CachedPlanSource *plansource;
                               2378                 :                : 
 5076                          2379                 :          14327 :         plansource = CreateOneShotCachedPlan(parsetree,
                               2380                 :                :                                              src,
                               2381                 :                :                                              CreateCommandTag(parsetree->stmt));
                               2382                 :                : 
                               2383                 :          14327 :         plancache_list = lappend(plancache_list, plansource);
                               2384                 :                :     }
                               2385                 :                : 
                               2386                 :          14322 :     plan->plancache_list = plancache_list;
                               2387                 :          14322 :     plan->oneshot = true;
                               2388                 :                : 
                               2389                 :                :     /*
                               2390                 :                :      * Pop the error context stack
                               2391                 :                :      */
 8287                          2392                 :          14322 :     error_context_stack = spierrcontext.previous;
10683 vadim4o@yahoo.com        2393                 :          14322 : }
                               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
 1882 tgl@sss.pgh.pa.us        2416                 :          85908 : _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
                               2417                 :                :                   Snapshot snapshot, Snapshot crosscheck_snapshot,
                               2418                 :                :                   bool fire_triggers)
                               2419                 :                : {
 6774 alvherre@alvh.no-ip.     2420                 :          85908 :     int         my_res = 0;
 3913 tgl@sss.pgh.pa.us        2421                 :          85908 :     uint64      my_processed = 0;
 6774 alvherre@alvh.no-ip.     2422                 :          85908 :     SPITupleTable *my_tuptable = NULL;
                               2423                 :          85908 :     int         res = 0;
                               2424                 :                :     bool        allow_nonatomic;
 5752 tgl@sss.pgh.pa.us        2425                 :          85908 :     bool        pushed_active_snap = false;
 1882                          2426                 :          85908 :     ResourceOwner plan_owner = options->owner;
                               2427                 :                :     SPICallbackArg spicallbackarg;
                               2428                 :                :     ErrorContextCallback spierrcontext;
 6774 alvherre@alvh.no-ip.     2429                 :          85908 :     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                 :                :      */
  773 tgl@sss.pgh.pa.us        2438                 :         171875 :     allow_nonatomic = options->allow_nonatomic &&
                               2439   [ +  +  +  +  :          85908 :         !_SPI_current->atomic && !IsSubTransaction();
                                              +  + ]
                               2440                 :                : 
                               2441                 :                :     /*
                               2442                 :                :      * Setup error traceback support for ereport()
                               2443                 :                :      */
 2154                          2444                 :          85908 :     spicallbackarg.query = NULL;    /* we'll fill this below */
                               2445                 :          85908 :     spicallbackarg.mode = plan->parse_mode;
 6774 alvherre@alvh.no-ip.     2446                 :          85908 :     spierrcontext.callback = _SPI_error_callback;
 2154 tgl@sss.pgh.pa.us        2447                 :          85908 :     spierrcontext.arg = &spicallbackarg;
 6774 alvherre@alvh.no-ip.     2448                 :          85908 :     spierrcontext.previous = error_context_stack;
                               2449                 :          85908 :     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                 :                :      */
 2017 tgl@sss.pgh.pa.us        2478         [ +  + ]:          85908 :     if (snapshot != InvalidSnapshot)
                               2479                 :                :     {
                               2480                 :                :         /* this intentionally tests the options field not the derived value */
 1882                          2481         [ -  + ]:            828 :         Assert(!options->allow_nonatomic);
                               2482         [ +  + ]:            828 :         if (options->read_only)
                               2483                 :                :         {
 5752                          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                 :                :      */
 2133                          2499         [ +  + ]:          85908 :     if (!plan->saved)
                               2500                 :          15188 :         plan_owner = NULL;
                               2501         [ +  + ]:          70720 :     else if (plan_owner == NULL)
                               2502                 :          70665 :         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                 :                :      */
 1882                          2510   [ +  +  -  + ]:          85908 :     if (options->must_return_tuples && plan->plancache_list == NIL)
 1882 tgl@sss.pgh.pa.us        2511         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2512                 :                :                 (errcode(ERRCODE_SYNTAX_ERROR),
                               2513                 :                :                  errmsg("empty query does not return tuples")));
                               2514                 :                : 
 6774 alvherre@alvh.no-ip.     2515   [ +  -  +  +  :CBC      168266 :     foreach(lc1, plan->plancache_list)
                                              +  + ]
                               2516                 :                :     {
                               2517                 :          85912 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
                               2518                 :                :         List       *stmt_list;
                               2519                 :                :         ListCell   *lc2;
                               2520                 :                : 
 2154 tgl@sss.pgh.pa.us        2521                 :          85912 :         spicallbackarg.query = plansource->query_string;
                               2522                 :                : 
                               2523                 :                :         /*
                               2524                 :                :          * If this is a one-shot plan, we still need to do parse analysis.
                               2525                 :                :          */
 5076                          2526         [ +  + ]:          85912 :         if (plan->oneshot)
                               2527                 :                :         {
 3605                          2528                 :          14326 :             RawStmt    *parsetree = plansource->raw_parse_tree;
 5076                          2529                 :          14326 :             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                 :                :              */
 4399                          2536         [ -  + ]:          14326 :             if (parsetree == NULL)
 1515 drowley@postgresql.o     2537                 :UBC           0 :                 querytree_list = NIL;
 4399 tgl@sss.pgh.pa.us        2538         [ +  + ]:CBC       14326 :             else if (plan->parserSetup != NULL)
                               2539                 :                :             {
 5076                          2540         [ -  + ]:            289 :                 Assert(plan->nargs == 0);
 1515 drowley@postgresql.o     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                 :          14037 :                 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree,
                               2550                 :                :                                                                     src,
 1515 drowley@postgresql.o     2551                 :ECB     (14021) :                                                                     plan->argtypes,
                               2552                 :                :                                                                     plan->nargs,
 1515 drowley@postgresql.o     2553                 :CBC       14037 :                                                                     _SPI_current->queryEnv);
                               2554                 :                :             }
                               2555                 :                : 
                               2556                 :                :             /* Finish filling in the CachedPlanSource */
 5076 tgl@sss.pgh.pa.us        2557                 :          14319 :             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                 :                :          */
 1882                          2574   [ +  +  +  + ]:          85905 :         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
 1882 tgl@sss.pgh.pa.us        2583                 :UBC           0 :                 cmdtag = GetCommandTagName(plansource->commandTag);
 1882 tgl@sss.pgh.pa.us        2584         [ +  - ]:CBC           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                 :          85897 :         cplan = GetCachedPlan(plansource, options->params,
 2133                          2595                 :          85897 :                               plan_owner, _SPI_current->queryEnv);
                               2596                 :                : 
 5552                          2597                 :          85798 :         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                 :                :          */
 2017                          2603   [ +  +  +  - ]:         170768 :         if (snapshot == InvalidSnapshot &&
                               2604         [ +  - ]:         169940 :             (list_length(stmt_list) > 1 ||
                               2605         [ +  + ]:         169940 :              (list_length(stmt_list) == 1 &&
                               2606                 :          84970 :               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                 :          76323 :             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                 :                :              */
  904                          2626   [ +  +  +  + ]:          76323 :             if (!options->read_only && !allow_nonatomic)
                               2627                 :                :             {
 2017                          2628         [ +  + ]:          73259 :                 if (pushed_active_snap)
                               2629                 :              4 :                     PopActiveSnapshot();
                               2630                 :          73259 :                 PushActiveSnapshot(GetTransactionSnapshot());
                               2631                 :          73259 :                 pushed_active_snap = true;
                               2632                 :                :             }
                               2633                 :                :         }
                               2634                 :                : 
 6774 alvherre@alvh.no-ip.     2635   [ +  -  +  +  :         168156 :         foreach(lc2, stmt_list)
                                              +  + ]
                               2636                 :                :         {
 3519 tgl@sss.pgh.pa.us        2637                 :          85798 :             PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
 3605                          2638                 :          85798 :             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                 :                :              */
 6774 alvherre@alvh.no-ip.     2647                 :          85798 :             _SPI_current->processed = 0;
                               2648                 :          85798 :             _SPI_current->tuptable = NULL;
                               2649                 :                : 
                               2650                 :                :             /* Check for unsupported cases. */
 3605 tgl@sss.pgh.pa.us        2651         [ +  + ]:          85798 :             if (stmt->utilityStmt)
                               2652                 :                :             {
                               2653         [ +  + ]:          20160 :                 if (IsA(stmt->utilityStmt, CopyStmt))
                               2654                 :                :                 {
                               2655                 :              9 :                     CopyStmt   *cstmt = (CopyStmt *) stmt->utilityStmt;
                               2656                 :                : 
 6774 alvherre@alvh.no-ip.     2657         [ +  + ]:              9 :                     if (cstmt->filename == NULL)
                               2658                 :                :                     {
                               2659                 :              4 :                         my_res = SPI_ERROR_COPY;
 8111 tgl@sss.pgh.pa.us        2660                 :              9 :                         goto fail;
                               2661                 :                :                     }
                               2662                 :                :                 }
 3605                          2663         [ +  + ]:          20151 :                 else if (IsA(stmt->utilityStmt, TransactionStmt))
                               2664                 :                :                 {
 6774 alvherre@alvh.no-ip.     2665                 :              5 :                     my_res = SPI_ERROR_TRANSACTION;
                               2666                 :              5 :                     goto fail;
                               2667                 :                :                 }
                               2668                 :                :             }
                               2669                 :                : 
 1882 tgl@sss.pgh.pa.us        2670   [ +  +  -  + ]:          85789 :             if (options->read_only && !CommandIsReadOnly(stmt))
 6774 alvherre@alvh.no-ip.     2671         [ #  # ]:UBC           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                 :                :              */
 1882 tgl@sss.pgh.pa.us        2682   [ +  +  +  + ]:CBC       85789 :             if (!options->read_only && pushed_active_snap)
                               2683                 :                :             {
 6774 alvherre@alvh.no-ip.     2684                 :          73291 :                 CommandCounterIncrement();
 5752 tgl@sss.pgh.pa.us        2685                 :          73291 :                 UpdateActiveSnapshotCommandId();
                               2686                 :                :             }
                               2687                 :                : 
                               2688                 :                :             /*
                               2689                 :                :              * Select appropriate tuple receiver.  Output from non-canSetTag
                               2690                 :                :              * subqueries always goes to the bit bucket.
                               2691                 :                :              */
 2360                          2692         [ -  + ]:          85789 :             if (!canSetTag)
 2360 tgl@sss.pgh.pa.us        2693                 :UBC           0 :                 dest = CreateDestReceiver(DestNone);
 1882 tgl@sss.pgh.pa.us        2694         [ +  + ]:CBC       85789 :             else if (options->dest)
                               2695                 :           1853 :                 dest = options->dest;
                               2696                 :                :             else
 2360                          2697                 :          83936 :                 dest = CreateDestReceiver(DestSPI);
                               2698                 :                : 
 3605                          2699         [ +  + ]:          85789 :             if (stmt->utilityStmt == NULL)
                               2700                 :                :             {
                               2701                 :                :                 QueryDesc  *qdesc;
                               2702                 :                :                 Snapshot    snap;
                               2703                 :                : 
 6774 alvherre@alvh.no-ip.     2704         [ +  - ]:          65638 :                 if (ActiveSnapshotSet())
                               2705                 :          65638 :                     snap = GetActiveSnapshot();
                               2706                 :                :                 else
 6774 alvherre@alvh.no-ip.     2707                 :UBC           0 :                     snap = InvalidSnapshot;
                               2708                 :                : 
 3605 tgl@sss.pgh.pa.us        2709                 :CBC       65638 :                 qdesc = CreateQueryDesc(stmt,
                               2710                 :                :                                         plansource->query_string,
                               2711                 :                :                                         snap, crosscheck_snapshot,
                               2712                 :                :                                         dest,
 1882                          2713                 :          65638 :                                         options->params,
                               2714                 :          65638 :                                         _SPI_current->queryEnv,
                               2715                 :                :                                         0);
  555 amitlan@postgresql.o     2716         [ +  - ]:          65638 :                 res = _SPI_pquery(qdesc, fire_triggers,
                               2717                 :                :                                   canSetTag ? options->tcount : 0);
 6774 alvherre@alvh.no-ip.     2718                 :          62339 :                 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                 :                :                  */
  904 tgl@sss.pgh.pa.us        2729         [ +  + ]:          20151 :                 if (allow_nonatomic)
 3171 peter_e@gmx.net          2730                 :             51 :                     context = PROCESS_UTILITY_QUERY_NONATOMIC;
                               2731                 :                :                 else
  904 tgl@sss.pgh.pa.us        2732                 :          20100 :                     context = PROCESS_UTILITY_QUERY;
                               2733                 :                : 
 2462 alvherre@alvh.no-ip.     2734                 :          20151 :                 InitializeQueryCompletion(&qc);
 6774                          2735                 :          20151 :                 ProcessUtility(stmt,
                               2736                 :                :                                plansource->query_string,
                               2737                 :                :                                true,    /* protect plancache's node tree */
                               2738                 :                :                                context,
 1882 tgl@sss.pgh.pa.us        2739                 :          20151 :                                options->params,
 3529 kgrittn@postgresql.o     2740                 :          20151 :                                _SPI_current->queryEnv,
                               2741                 :                :                                dest,
                               2742                 :                :                                &qc);
                               2743                 :                : 
                               2744                 :                :                 /* Update "processed" if stmt returned tuples */
 6774 alvherre@alvh.no-ip.     2745         [ +  + ]:          20019 :                 if (_SPI_current->tuptable)
 2690 tgl@sss.pgh.pa.us        2746                 :           1206 :                     _SPI_current->processed = _SPI_current->tuptable->numvals;
                               2747                 :                : 
 5169 heikki.linnakangas@i     2748                 :          20019 :                 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                 :                :                  */
 3605 tgl@sss.pgh.pa.us        2754         [ +  + ]:          20019 :                 if (IsA(stmt->utilityStmt, CreateTableAsStmt))
                               2755                 :                :                 {
                               2756                 :             33 :                     CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
                               2757                 :                : 
 2462 alvherre@alvh.no-ip.     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                 :                :                          */
 3761 tgl@sss.pgh.pa.us        2766   [ +  -  -  + ]:              4 :                         Assert(ctastmt->if_not_exists ||
                               2767                 :                :                                ctastmt->into->skipData);
 3883                          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)
 5367 tgl@sss.pgh.pa.us        2776                 :UBC           0 :                         res = SPI_OK_SELINTO;
                               2777                 :                :                 }
 3605 tgl@sss.pgh.pa.us        2778         [ +  + ]:CBC       19986 :                 else if (IsA(stmt->utilityStmt, CopyStmt))
                               2779                 :                :                 {
 2462 alvherre@alvh.no-ip.     2780         [ -  + ]:              5 :                     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                 :                :              */
 6774                          2790         [ +  - ]:          82358 :             if (canSetTag)
                               2791                 :                :             {
                               2792                 :          82358 :                 my_processed = _SPI_current->processed;
                               2793                 :          82358 :                 SPI_freetuptable(my_tuptable);
                               2794                 :          82358 :                 my_tuptable = _SPI_current->tuptable;
                               2795                 :          82358 :                 my_res = res;
                               2796                 :                :             }
                               2797                 :                :             else
                               2798                 :                :             {
 6774 alvherre@alvh.no-ip.     2799                 :UBC           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                 :                : 
 6774 alvherre@alvh.no-ip.     2809         [ -  + ]:CBC       82358 :             if (res < 0)
                               2810                 :                :             {
 6774 alvherre@alvh.no-ip.     2811                 :UBC           0 :                 my_res = res;
                               2812                 :              0 :                 goto fail;
                               2813                 :                :             }
                               2814                 :                :         }
                               2815                 :                : 
                               2816                 :                :         /* Done with this plan, so release refcount */
 2133 tgl@sss.pgh.pa.us        2817                 :CBC       82358 :         ReleaseCachedPlan(cplan, plan_owner);
 6774 alvherre@alvh.no-ip.     2818                 :          82358 :         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                 :                :          */
 1882 tgl@sss.pgh.pa.us        2825         [ +  + ]:          82358 :         if (!options->read_only)
 6774 alvherre@alvh.no-ip.     2826                 :          78599 :             CommandCounterIncrement();
                               2827                 :                :     }
                               2828                 :                : 
                               2829                 :          82363 : fail:
                               2830                 :                : 
                               2831                 :                :     /* Pop the snapshot off the stack if we pushed one */
 5752 tgl@sss.pgh.pa.us        2832         [ +  + ]:          82363 :     if (pushed_active_snap)
                               2833                 :          70723 :         PopActiveSnapshot();
                               2834                 :                : 
                               2835                 :                :     /* We no longer need the cached plan refcount, if any */
 6774 alvherre@alvh.no-ip.     2836         [ +  + ]:          82363 :     if (cplan)
 2133 tgl@sss.pgh.pa.us        2837                 :              9 :         ReleaseCachedPlan(cplan, plan_owner);
                               2838                 :                : 
                               2839                 :                :     /*
                               2840                 :                :      * Pop the error context stack
                               2841                 :                :      */
 6774 alvherre@alvh.no-ip.     2842                 :          82363 :     error_context_stack = spierrcontext.previous;
                               2843                 :                : 
                               2844                 :                :     /* Save results for caller */
 7728 tgl@sss.pgh.pa.us        2845                 :          82363 :     SPI_processed = my_processed;
                               2846                 :          82363 :     SPI_tuptable = my_tuptable;
                               2847                 :                : 
                               2848                 :                :     /* tuptable now is caller's responsibility, not SPI's */
 7295                          2849                 :          82363 :     _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                 :                :      */
 7277                          2856         [ -  + ]:          82363 :     if (my_res == 0)
 6520 heikki.linnakangas@i     2857                 :UBC           0 :         my_res = SPI_OK_REWRITTEN;
                               2858                 :                : 
 7411 tgl@sss.pgh.pa.us        2859                 :CBC       82363 :     return my_res;
                               2860                 :                : }
                               2861                 :                : 
                               2862                 :                : /*
                               2863                 :                :  * Convert arrays of query parameters to form wanted by planner and executor
                               2864                 :                :  */
                               2865                 :                : static ParamListInfo
  151 peter@eisentraut.org     2866                 :GNC        6343 : _SPI_convert_params(int nargs, const Oid *argtypes,
                               2867                 :                :                     const Datum *Values, const char *Nulls)
                               2868                 :                : {
                               2869                 :                :     ParamListInfo paramLI;
                               2870                 :                : 
 6815 tgl@sss.pgh.pa.us        2871         [ +  + ]:CBC        6343 :     if (nargs > 0)
                               2872                 :                :     {
 2816 peter@eisentraut.org     2873                 :           5333 :         paramLI = makeParamList(nargs);
                               2874                 :                : 
                               2875         [ +  + ]:          14158 :         for (int i = 0; i < nargs; i++)
                               2876                 :                :         {
 6815 tgl@sss.pgh.pa.us        2877                 :           8825 :             ParamExternData *prm = &paramLI->params[i];
                               2878                 :                : 
                               2879                 :           8825 :             prm->value = Values[i];
                               2880   [ +  +  -  + ]:           8825 :             prm->isnull = (Nulls && Nulls[i] == 'n');
 5552                          2881                 :           8825 :             prm->pflags = PARAM_FLAG_CONST;
 6815                          2882                 :           8825 :             prm->ptype = argtypes[i];
                               2883                 :                :         }
                               2884                 :                :     }
                               2885                 :                :     else
                               2886                 :           1010 :         paramLI = NULL;
                               2887                 :           6343 :     return paramLI;
                               2888                 :                : }
                               2889                 :                : 
                               2890                 :                : static int
  555 amitlan@postgresql.o     2891                 :          65638 : _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
                               2892                 :                : {
10656 vadim4o@yahoo.com        2893                 :          65638 :     int         operation = queryDesc->operation;
                               2894                 :                :     int         eflags;
                               2895                 :                :     int         res;
                               2896                 :                : 
10674 bruce@momjian.us         2897   [ +  +  +  +  :          65638 :     switch (operation)
                                              +  - ]
                               2898                 :                :     {
10673                          2899                 :          32739 :         case CMD_SELECT:
 2360 tgl@sss.pgh.pa.us        2900         [ -  + ]:          32739 :             if (queryDesc->dest->mydest == DestNone)
                               2901                 :                :             {
                               2902                 :                :                 /* Don't return SPI_OK_SELECT if we're discarding result */
 7728 tgl@sss.pgh.pa.us        2903                 :UBC           0 :                 res = SPI_OK_UTILITY;
                               2904                 :                :             }
                               2905                 :                :             else
 7413 tgl@sss.pgh.pa.us        2906                 :CBC       32739 :                 res = SPI_OK_SELECT;
10673 bruce@momjian.us         2907                 :          32739 :             break;
                               2908                 :          25935 :         case CMD_INSERT:
 6258 tgl@sss.pgh.pa.us        2909         [ +  + ]:          25935 :             if (queryDesc->plannedstmt->hasReturning)
 7398                          2910                 :           1070 :                 res = SPI_OK_INSERT_RETURNING;
                               2911                 :                :             else
                               2912                 :          24865 :                 res = SPI_OK_INSERT;
10673 bruce@momjian.us         2913                 :          25935 :             break;
                               2914                 :           5821 :         case CMD_DELETE:
 6258 tgl@sss.pgh.pa.us        2915         [ -  + ]:           5821 :             if (queryDesc->plannedstmt->hasReturning)
 7398 tgl@sss.pgh.pa.us        2916                 :UBC           0 :                 res = SPI_OK_DELETE_RETURNING;
                               2917                 :                :             else
 7398 tgl@sss.pgh.pa.us        2918                 :CBC        5821 :                 res = SPI_OK_DELETE;
10673 bruce@momjian.us         2919                 :           5821 :             break;
                               2920                 :           1099 :         case CMD_UPDATE:
 6258 tgl@sss.pgh.pa.us        2921         [ +  + ]:           1099 :             if (queryDesc->plannedstmt->hasReturning)
 7398                          2922                 :             11 :                 res = SPI_OK_UPDATE_RETURNING;
                               2923                 :                :             else
                               2924                 :           1088 :                 res = SPI_OK_UPDATE;
10673 bruce@momjian.us         2925                 :           1099 :             break;
 1706 alvherre@alvh.no-ip.     2926                 :             44 :         case CMD_MERGE:
  986 dean.a.rasheed@gmail     2927         [ +  + ]:             44 :             if (queryDesc->plannedstmt->hasReturning)
                               2928                 :             12 :                 res = SPI_OK_MERGE_RETURNING;
                               2929                 :                :             else
                               2930                 :             32 :                 res = SPI_OK_MERGE;
 1706 alvherre@alvh.no-ip.     2931                 :             44 :             break;
10673 bruce@momjian.us         2932                 :UBC           0 :         default:
10315                          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 */
 7045 tgl@sss.pgh.pa.us        2942         [ +  + ]:CBC       65638 :     if (fire_triggers)
 5753                          2943                 :          62081 :         eflags = 0;             /* default run-to-completion flags */
                               2944                 :                :     else
                               2945                 :           3557 :         eflags = EXEC_FLAG_SKIP_TRIGGERS;
                               2946                 :                : 
  555 amitlan@postgresql.o     2947                 :          65638 :     ExecutorStart(queryDesc, eflags);
                               2948                 :                : 
  719 tgl@sss.pgh.pa.us        2949                 :          65633 :     ExecutorRun(queryDesc, ForwardScanDirection, tcount);
                               2950                 :                : 
 8759                          2951                 :          62468 :     _SPI_current->processed = queryDesc->estate->es_processed;
                               2952                 :                : 
 6258                          2953   [ +  +  +  + ]:          62468 :     if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
 7398                          2954         [ +  + ]:          30770 :         queryDesc->dest->mydest == DestSPI)
                               2955                 :                :     {
10656 vadim4o@yahoo.com        2956         [ -  + ]:          28962 :         if (_SPI_checktuples())
 8531 tgl@sss.pgh.pa.us        2957         [ #  # ]:UBC           0 :             elog(ERROR, "consistency check on SPI tuple count failed");
                               2958                 :                :     }
                               2959                 :                : 
 5753 tgl@sss.pgh.pa.us        2960                 :CBC       62468 :     ExecutorFinish(queryDesc);
 7918                          2961                 :          62339 :     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                 :                : 
 8749                          2969                 :          62339 :     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
 8287                          2978                 :           4165 : _SPI_error_callback(void *arg)
                               2979                 :                : {
 2154                          2980                 :           4165 :     SPICallbackArg *carg = (SPICallbackArg *) arg;
                               2981                 :           4165 :     const char *query = carg->query;
                               2982                 :                :     int         syntaxerrposition;
                               2983                 :                : 
 3274                          2984         [ -  + ]:           4165 :     if (query == NULL)          /* in case arg wasn't set yet */
 3274 tgl@sss.pgh.pa.us        2985                 :UBC           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                 :                :      */
 8287 tgl@sss.pgh.pa.us        2991                 :CBC        4165 :     syntaxerrposition = geterrposition();
                               2992         [ +  + ]:           4165 :     if (syntaxerrposition > 0)
                               2993                 :                :     {
                               2994                 :             59 :         errposition(0);
                               2995                 :             59 :         internalerrposition(syntaxerrposition);
                               2996                 :             59 :         internalerrquery(query);
                               2997                 :                :     }
                               2998                 :                :     else
                               2999                 :                :     {
                               3000                 :                :         /* Use the parse mode to decide how to describe the query */
 2154                          3001      [ +  +  + ]:           4106 :         switch (carg->mode)
                               3002                 :                :         {
                               3003                 :             51 :             case RAW_PARSE_PLPGSQL_EXPR:
  814 peter@eisentraut.org     3004                 :             51 :                 errcontext("PL/pgSQL expression \"%s\"", query);
 2154 tgl@sss.pgh.pa.us        3005                 :             51 :                 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                 :           4047 :             default:
                               3012                 :           4047 :                 errcontext("SQL statement \"%s\"", query);
                               3013                 :           4047 :                 break;
                               3014                 :                :         }
                               3015                 :                :     }
                               3016                 :                : }
                               3017                 :                : 
                               3018                 :                : /*
                               3019                 :                :  * _SPI_cursor_operation()
                               3020                 :                :  *
                               3021                 :                :  *  Do a FETCH or MOVE in a cursor
                               3022                 :                :  */
                               3023                 :                : static void
 7166                          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 */
 9322 JanWieck@Yahoo.com       3030         [ -  + ]:          29874 :     if (!PortalIsValid(portal))
 9322 JanWieck@Yahoo.com       3031         [ #  # ]:UBC           0 :         elog(ERROR, "invalid portal in SPI cursor operation");
                               3032                 :                : 
                               3033                 :                :     /* Push the SPI stack */
 8467 tgl@sss.pgh.pa.us        3034         [ -  + ]:CBC       29874 :     if (_SPI_begin_call(true) < 0)
 8467 tgl@sss.pgh.pa.us        3035         [ #  # ]:UBC           0 :         elog(ERROR, "SPI cursor operation called while not connected");
                               3036                 :                : 
                               3037                 :                :     /* Reset the SPI result (note we deliberately don't touch lastoid) */
 9322 JanWieck@Yahoo.com       3038                 :CBC       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 */
 8513 tgl@sss.pgh.pa.us        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                 :                : 
 7695 alvherre@alvh.no-ip.     3059   [ +  +  -  + ]:          29857 :     if (dest->mydest == DestSPI && _SPI_checktuples())
 8531 tgl@sss.pgh.pa.us        3060         [ #  # ]:UBC           0 :         elog(ERROR, "consistency check on SPI tuple count failed");
                               3061                 :                : 
                               3062                 :                :     /* Put the result into place for access by caller */
 9322 JanWieck@Yahoo.com       3063                 :CBC       29857 :     SPI_processed = _SPI_current->processed;
 9165 bruce@momjian.us         3064                 :          29857 :     SPI_tuptable = _SPI_current->tuptable;
                               3065                 :                : 
                               3066                 :                :     /* tuptable now is caller's responsibility, not SPI's */
 7295 tgl@sss.pgh.pa.us        3067                 :          29857 :     _SPI_current->tuptable = NULL;
                               3068                 :                : 
                               3069                 :                :     /* Pop the SPI stack */
 9322 JanWieck@Yahoo.com       3070                 :          29857 :     _SPI_end_call(true);
                               3071                 :          29857 : }
                               3072                 :                : 
                               3073                 :                : 
                               3074                 :                : static MemoryContext
 8081 neilc@samurai.com        3075                 :         151676 : _SPI_execmem(void)
                               3076                 :                : {
 9649 tgl@sss.pgh.pa.us        3077                 :         151676 :     return MemoryContextSwitchTo(_SPI_current->execCxt);
                               3078                 :                : }
                               3079                 :                : 
                               3080                 :                : static MemoryContext
 8081 neilc@samurai.com        3081                 :         211097 : _SPI_procmem(void)
                               3082                 :                : {
 9649 tgl@sss.pgh.pa.us        3083                 :         211097 :     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
 3340                          3094                 :         226298 : _SPI_begin_call(bool use_exec)
                               3095                 :                : {
 3672                          3096         [ -  + ]:         226298 :     if (_SPI_current == NULL)
10315 bruce@momjian.us         3097                 :UBC           0 :         return SPI_ERROR_UNCONNECTED;
                               3098                 :                : 
 3340 tgl@sss.pgh.pa.us        3099         [ +  + ]:CBC      226298 :     if (use_exec)
                               3100                 :                :     {
                               3101                 :                :         /* remember when the Executor operation started */
                               3102                 :         151676 :         _SPI_current->execSubid = GetCurrentSubTransactionId();
                               3103                 :                :         /* switch to the Executor memory context */
10674 bruce@momjian.us         3104                 :         151676 :         _SPI_execmem();
                               3105                 :                :     }
                               3106                 :                : 
10315                          3107                 :         226298 :     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
 3340 tgl@sss.pgh.pa.us        3118                 :         148548 : _SPI_end_call(bool use_exec)
                               3119                 :                : {
                               3120         [ +  + ]:         148548 :     if (use_exec)
                               3121                 :                :     {
                               3122                 :                :         /* switch to the procedure memory context */
10674 bruce@momjian.us         3123                 :         148030 :         _SPI_procmem();
                               3124                 :                :         /* mark Executor context no longer in use */
 3340 tgl@sss.pgh.pa.us        3125                 :         148030 :         _SPI_current->execSubid = InvalidSubTransactionId;
                               3126                 :                :         /* and free Executor memory */
 1109 nathan@postgresql.or     3127                 :         148030 :         MemoryContextReset(_SPI_current->execCxt);
                               3128                 :                :     }
                               3129                 :                : 
10315 bruce@momjian.us         3130                 :         148548 :     return 0;
                               3131                 :                : }
                               3132                 :                : 
                               3133                 :                : static bool
 9249 tgl@sss.pgh.pa.us        3134                 :          58791 : _SPI_checktuples(void)
                               3135                 :                : {
 3913                          3136                 :          58791 :     uint64      processed = _SPI_current->processed;
10673 bruce@momjian.us         3137                 :          58791 :     SPITupleTable *tuptable = _SPI_current->tuptable;
                               3138                 :          58791 :     bool        failed = false;
                               3139                 :                : 
 8517                          3140         [ -  + ]:          58791 :     if (tuptable == NULL)       /* spi_dest_startup was not called */
 8712 tgl@sss.pgh.pa.us        3141                 :UBC           0 :         failed = true;
 2690 tgl@sss.pgh.pa.us        3142         [ -  + ]:CBC       58791 :     else if (processed != tuptable->numvals)
 8712 tgl@sss.pgh.pa.us        3143                 :UBC           0 :         failed = true;
                               3144                 :                : 
10315 bruce@momjian.us         3145                 :CBC       58791 :     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
 5552 tgl@sss.pgh.pa.us        3158                 :          21115 : _SPI_make_plan_non_temp(SPIPlanPtr plan)
                               3159                 :                : {
                               3160                 :                :     SPIPlanPtr  newplan;
                               3161                 :          21115 :     MemoryContext parentcxt = _SPI_current->procCxt;
                               3162                 :                :     MemoryContext plancxt;
                               3163                 :                :     MemoryContext oldcxt;
                               3164                 :                :     ListCell   *lc;
                               3165                 :                : 
                               3166                 :                :     /* Assert the input is a temporary SPIPlan */
                               3167         [ -  + ]:          21115 :     Assert(plan->magic == _SPI_PLAN_MAGIC);
                               3168         [ -  + ]:          21115 :     Assert(plan->plancxt == NULL);
                               3169                 :                :     /* One-shot plans can't be saved */
 5076                          3170         [ -  + ]:          21115 :     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                 :                :      */
 9322 JanWieck@Yahoo.com       3176                 :          21115 :     plancxt = AllocSetContextCreate(parentcxt,
                               3177                 :                :                                     "SPI Plan",
                               3178                 :                :                                     ALLOCSET_SMALL_SIZES);
                               3179                 :          21115 :     oldcxt = MemoryContextSwitchTo(plancxt);
                               3180                 :                : 
                               3181                 :                :     /* Copy the _SPI_plan struct and subsidiary data into the new context */
  353 michael@paquier.xyz      3182                 :          21115 :     newplan = palloc0_object(_SPI_plan);
 7198 tgl@sss.pgh.pa.us        3183                 :          21115 :     newplan->magic = _SPI_PLAN_MAGIC;
 9322 JanWieck@Yahoo.com       3184                 :          21115 :     newplan->plancxt = plancxt;
 2154 tgl@sss.pgh.pa.us        3185                 :          21115 :     newplan->parse_mode = plan->parse_mode;
 7166                          3186                 :          21115 :     newplan->cursor_options = plan->cursor_options;
10674 bruce@momjian.us         3187                 :          21115 :     newplan->nargs = plan->nargs;
                               3188         [ +  + ]:          21115 :     if (plan->nargs > 0)
                               3189                 :                :     {
                               3190                 :                :         Oid        *newplan_argtypes;
                               3191                 :                : 
  151 peter@eisentraut.org     3192                 :GNC        1594 :         newplan_argtypes = palloc_array(Oid, plan->nargs);
                               3193                 :           1594 :         memcpy(newplan_argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
                               3194                 :           1594 :         newplan->argtypes = newplan_argtypes;
                               3195                 :                :     }
                               3196                 :                :     else
10674 bruce@momjian.us         3197                 :CBC       19521 :         newplan->argtypes = NULL;
 6233 tgl@sss.pgh.pa.us        3198                 :          21115 :     newplan->parserSetup = plan->parserSetup;
                               3199                 :          21115 :     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                 :                :      */
 7198                          3207   [ +  -  +  +  :          42230 :     foreach(lc, plan->plancache_list)
                                              +  + ]
                               3208                 :                :     {
                               3209                 :          21115 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
                               3210                 :                : 
 5552                          3211                 :          21115 :         CachedPlanSetParentContext(plansource, parentcxt);
                               3212                 :                : 
                               3213                 :                :         /* Build new list, with list cells in plancxt */
                               3214                 :          21115 :         newplan->plancache_list = lappend(newplan->plancache_list, plansource);
                               3215                 :                :     }
                               3216                 :                : 
 7198                          3217                 :          21115 :     MemoryContextSwitchTo(oldcxt);
                               3218                 :                : 
                               3219                 :                :     /* For safety, unlink the CachedPlanSources from the temporary plan */
 5552                          3220                 :          21115 :     plan->plancache_list = NIL;
                               3221                 :                : 
 7198                          3222                 :          21115 :     return newplan;
                               3223                 :                : }
                               3224                 :                : 
                               3225                 :                : /*
                               3226                 :                :  * Make a "saved" copy of the given plan.
                               3227                 :                :  */
                               3228                 :                : static SPIPlanPtr
 7198 tgl@sss.pgh.pa.us        3229                 :UBC           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 */
 5076                          3237         [ #  # ]:              0 :     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                 :                :      */
 5552                          3244                 :              0 :     plancxt = AllocSetContextCreate(CurrentMemoryContext,
                               3245                 :                :                                     "SPI Plan",
                               3246                 :                :                                     ALLOCSET_SMALL_SIZES);
 7198                          3247                 :              0 :     oldcxt = MemoryContextSwitchTo(plancxt);
                               3248                 :                : 
                               3249                 :                :     /* Copy the SPI plan into its own context */
  353 michael@paquier.xyz      3250                 :              0 :     newplan = palloc0_object(_SPI_plan);
 7198 tgl@sss.pgh.pa.us        3251                 :              0 :     newplan->magic = _SPI_PLAN_MAGIC;
                               3252                 :              0 :     newplan->plancxt = plancxt;
 2154                          3253                 :              0 :     newplan->parse_mode = plan->parse_mode;
 7166                          3254                 :              0 :     newplan->cursor_options = plan->cursor_options;
 7198                          3255                 :              0 :     newplan->nargs = plan->nargs;
                               3256         [ #  # ]:              0 :     if (plan->nargs > 0)
                               3257                 :                :     {
                               3258                 :                :         Oid        *newplan_argtypes;
                               3259                 :                : 
  151 peter@eisentraut.org     3260                 :UNC           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
 7198 tgl@sss.pgh.pa.us        3265                 :UBC           0 :         newplan->argtypes = NULL;
 6233                          3266                 :              0 :     newplan->parserSetup = plan->parserSetup;
                               3267                 :              0 :     newplan->parserSetupArg = plan->parserSetupArg;
                               3268                 :                : 
                               3269                 :                :     /* Copy all the plancache entries */
 7198                          3270   [ #  #  #  #  :              0 :     foreach(lc, plan->plancache_list)
                                              #  # ]
                               3271                 :                :     {
                               3272                 :              0 :         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
                               3273                 :                :         CachedPlanSource *newsource;
                               3274                 :                : 
 5552                          3275                 :              0 :         newsource = CopyCachedPlan(plansource);
 7198                          3276                 :              0 :         newplan->plancache_list = lappend(newplan->plancache_list, newsource);
                               3277                 :                :     }
                               3278                 :                : 
 9322 JanWieck@Yahoo.com       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                 :                :      */
 5552 tgl@sss.pgh.pa.us        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                 :                : 
10315 bruce@momjian.us         3296                 :              0 :     return newplan;
                               3297                 :                : }
                               3298                 :                : 
                               3299                 :                : /*
                               3300                 :                :  * Internal lookup of ephemeral named relation by name.
                               3301                 :                :  */
                               3302                 :                : static EphemeralNamedRelation
 3529 kgrittn@postgresql.o     3303                 :CBC         518 : _SPI_find_ENR_by_name(const char *name)
                               3304                 :                : {
                               3305                 :                :     /* internal static function; any error is bug in SPI itself */
                               3306         [ -  + ]:            518 :     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)
 3529 kgrittn@postgresql.o     3331                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                               3332                 :                : 
 3447 tgl@sss.pgh.pa.us        3333                 :CBC         518 :     res = _SPI_begin_call(false);   /* keep current memory context */
 3529 kgrittn@postgresql.o     3334         [ -  + ]:            518 :     if (res < 0)
 3529 kgrittn@postgresql.o     3335                 :UBC           0 :         return res;
                               3336                 :                : 
 3529 kgrittn@postgresql.o     3337                 :CBC         518 :     match = _SPI_find_ENR_by_name(enr->md.name);
                               3338         [ -  + ]:            518 :     if (match)
 3529 kgrittn@postgresql.o     3339                 :UBC           0 :         res = SPI_ERROR_REL_DUPLICATE;
                               3340                 :                :     else
                               3341                 :                :     {
 3529 kgrittn@postgresql.o     3342         [ +  + ]:CBC         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
 3529 kgrittn@postgresql.o     3359                 :UBC           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                 :                : 
 3447 tgl@sss.pgh.pa.us        3367                 :              0 :     res = _SPI_begin_call(false);   /* keep current memory context */
 3529 kgrittn@postgresql.o     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
 3525 kgrittn@postgresql.o     3397                 :CBC       10430 : SPI_register_trigger_data(TriggerData *tdata)
                               3398                 :                : {
                               3399         [ -  + ]:          10430 :     if (tdata == NULL)
 3525 kgrittn@postgresql.o     3400                 :UBC           0 :         return SPI_ERROR_ARGUMENT;
                               3401                 :                : 
 3525 kgrittn@postgresql.o     3402         [ +  + ]:CBC       10430 :     if (tdata->tg_newtable)
                               3403                 :                :     {
                               3404                 :                :         EphemeralNamedRelation enr =
  353 michael@paquier.xyz      3405                 :            291 :             palloc_object(EphemeralNamedRelationData);
                               3406                 :                :         int         rc;
                               3407                 :                : 
 3525 kgrittn@postgresql.o     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)
 3525 kgrittn@postgresql.o     3416                 :UBC           0 :             return rc;
                               3417                 :                :     }
                               3418                 :                : 
 3525 kgrittn@postgresql.o     3419         [ +  + ]:CBC       10430 :     if (tdata->tg_oldtable)
                               3420                 :                :     {
                               3421                 :                :         EphemeralNamedRelation enr =
  353 michael@paquier.xyz      3422                 :            227 :             palloc_object(EphemeralNamedRelationData);
                               3423                 :                :         int         rc;
                               3424                 :                : 
 3525 kgrittn@postgresql.o     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)
 3525 kgrittn@postgresql.o     3433                 :UBC           0 :             return rc;
                               3434                 :                :     }
                               3435                 :                : 
 3525 kgrittn@postgresql.o     3436                 :CBC       10430 :     return SPI_OK_TD_REGISTER;
                               3437                 :                : }
        

Generated by: LCOV version 2.0-1