PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
spi.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/printtup.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "catalog/heap.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi_priv.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for spi.c:

Go to the source code of this file.

Data Structures

struct  SPICallbackArg
 

Typedefs

typedef struct SPICallbackArg SPICallbackArg
 

Functions

static Portal SPI_cursor_open_internal (const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
 
static void _SPI_prepare_plan (const char *src, SPIPlanPtr plan)
 
static void _SPI_prepare_oneshot_plan (const char *src, SPIPlanPtr plan)
 
static int _SPI_execute_plan (SPIPlanPtr plan, const SPIExecuteOptions *options, Snapshot snapshot, Snapshot crosscheck_snapshot, bool fire_triggers)
 
static ParamListInfo _SPI_convert_params (int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
 
static int _SPI_pquery (QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
 
static void _SPI_error_callback (void *arg)
 
static void _SPI_cursor_operation (Portal portal, FetchDirection direction, long count, DestReceiver *dest)
 
static SPIPlanPtr _SPI_make_plan_non_temp (SPIPlanPtr plan)
 
static SPIPlanPtr _SPI_save_plan (SPIPlanPtr plan)
 
static int _SPI_begin_call (bool use_exec)
 
static int _SPI_end_call (bool use_exec)
 
static MemoryContext _SPI_execmem (void)
 
static MemoryContext _SPI_procmem (void)
 
static bool _SPI_checktuples (void)
 
int SPI_connect (void)
 
int SPI_connect_ext (int options)
 
int SPI_finish (void)
 
void SPI_start_transaction (void)
 
static void _SPI_commit (bool chain)
 
void SPI_commit (void)
 
void SPI_commit_and_chain (void)
 
static void _SPI_rollback (bool chain)
 
void SPI_rollback (void)
 
void SPI_rollback_and_chain (void)
 
void AtEOXact_SPI (bool isCommit)
 
void AtEOSubXact_SPI (bool isCommit, SubTransactionId mySubid)
 
bool SPI_inside_nonatomic_context (void)
 
int SPI_execute (const char *src, bool read_only, long tcount)
 
int SPI_exec (const char *src, long tcount)
 
int SPI_execute_extended (const char *src, const SPIExecuteOptions *options)
 
int SPI_execute_plan (SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
 
int SPI_execp (SPIPlanPtr plan, Datum *Values, const char *Nulls, long tcount)
 
int SPI_execute_plan_extended (SPIPlanPtr plan, const SPIExecuteOptions *options)
 
int SPI_execute_plan_with_paramlist (SPIPlanPtr plan, ParamListInfo params, bool read_only, long tcount)
 
int SPI_execute_snapshot (SPIPlanPtr plan, Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
 
int SPI_execute_with_args (const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, long tcount)
 
SPIPlanPtr SPI_prepare (const char *src, int nargs, Oid *argtypes)
 
SPIPlanPtr SPI_prepare_cursor (const char *src, int nargs, Oid *argtypes, int cursorOptions)
 
SPIPlanPtr SPI_prepare_extended (const char *src, const SPIPrepareOptions *options)
 
SPIPlanPtr SPI_prepare_params (const char *src, ParserSetupHook parserSetup, void *parserSetupArg, int cursorOptions)
 
int SPI_keepplan (SPIPlanPtr plan)
 
SPIPlanPtr SPI_saveplan (SPIPlanPtr plan)
 
int SPI_freeplan (SPIPlanPtr plan)
 
HeapTuple SPI_copytuple (HeapTuple tuple)
 
HeapTupleHeader SPI_returntuple (HeapTuple tuple, TupleDesc tupdesc)
 
HeapTuple SPI_modifytuple (Relation rel, HeapTuple tuple, int natts, int *attnum, Datum *Values, const char *Nulls)
 
int SPI_fnumber (TupleDesc tupdesc, const char *fname)
 
char * SPI_fname (TupleDesc tupdesc, int fnumber)
 
char * SPI_getvalue (HeapTuple tuple, TupleDesc tupdesc, int fnumber)
 
Datum SPI_getbinval (HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
 
char * SPI_gettype (TupleDesc tupdesc, int fnumber)
 
Oid SPI_gettypeid (TupleDesc tupdesc, int fnumber)
 
char * SPI_getrelname (Relation rel)
 
char * SPI_getnspname (Relation rel)
 
void * SPI_palloc (Size size)
 
void * SPI_repalloc (void *pointer, Size size)
 
void SPI_pfree (void *pointer)
 
Datum SPI_datumTransfer (Datum value, bool typByVal, int typLen)
 
void SPI_freetuple (HeapTuple tuple)
 
void SPI_freetuptable (SPITupleTable *tuptable)
 
Portal SPI_cursor_open (const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
 
Portal SPI_cursor_open_with_args (const char *name, const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, int cursorOptions)
 
Portal SPI_cursor_open_with_paramlist (const char *name, SPIPlanPtr plan, ParamListInfo params, bool read_only)
 
Portal SPI_cursor_parse_open (const char *name, const char *src, const SPIParseOpenOptions *options)
 
Portal SPI_cursor_find (const char *name)
 
void SPI_cursor_fetch (Portal portal, bool forward, long count)
 
void SPI_cursor_move (Portal portal, bool forward, long count)
 
void SPI_scroll_cursor_fetch (Portal portal, FetchDirection direction, long count)
 
void SPI_scroll_cursor_move (Portal portal, FetchDirection direction, long count)
 
void SPI_cursor_close (Portal portal)
 
Oid SPI_getargtypeid (SPIPlanPtr plan, int argIndex)
 
int SPI_getargcount (SPIPlanPtr plan)
 
bool SPI_is_cursor_plan (SPIPlanPtr plan)
 
bool SPI_plan_is_valid (SPIPlanPtr plan)
 
const char * SPI_result_code_string (int code)
 
ListSPI_plan_get_plan_sources (SPIPlanPtr plan)
 
CachedPlanSPI_plan_get_cached_plan (SPIPlanPtr plan)
 
void spi_dest_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
bool spi_printtup (TupleTableSlot *slot, DestReceiver *self)
 
static EphemeralNamedRelation _SPI_find_ENR_by_name (const char *name)
 
int SPI_register_relation (EphemeralNamedRelation enr)
 
int SPI_unregister_relation (const char *name)
 
int SPI_register_trigger_data (TriggerData *tdata)
 

Variables

uint64 SPI_processed = 0
 
SPITupleTableSPI_tuptable = NULL
 
int SPI_result = 0
 
static _SPI_connection_SPI_stack = NULL
 
static _SPI_connection_SPI_current = NULL
 
static int _SPI_stack_depth = 0
 
static int _SPI_connected = -1
 

Typedef Documentation

◆ SPICallbackArg

Function Documentation

◆ _SPI_begin_call()

static int _SPI_begin_call ( bool  use_exec)
static

Definition at line 3077 of file spi.c.

3078 {
3079  if (_SPI_current == NULL)
3080  return SPI_ERROR_UNCONNECTED;
3081 
3082  if (use_exec)
3083  {
3084  /* remember when the Executor operation started */
3086  /* switch to the Executor memory context */
3087  _SPI_execmem();
3088  }
3089 
3090  return 0;
3091 }
static _SPI_connection * _SPI_current
Definition: spi.c:49
static MemoryContext _SPI_execmem(void)
Definition: spi.c:3058
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:71
SubTransactionId execSubid
Definition: spi_priv.h:29
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:790

References _SPI_current, _SPI_execmem(), _SPI_connection::execSubid, GetCurrentSubTransactionId(), and SPI_ERROR_UNCONNECTED.

Referenced by _SPI_cursor_operation(), SPI_cursor_open_internal(), SPI_cursor_open_with_args(), SPI_cursor_parse_open(), SPI_execute(), SPI_execute_extended(), SPI_execute_plan(), SPI_execute_plan_extended(), SPI_execute_plan_with_paramlist(), SPI_execute_snapshot(), SPI_execute_with_args(), SPI_finish(), SPI_prepare_cursor(), SPI_prepare_extended(), SPI_prepare_params(), SPI_register_relation(), SPI_saveplan(), and SPI_unregister_relation().

◆ _SPI_checktuples()

static bool _SPI_checktuples ( void  )
static

Definition at line 3117 of file spi.c.

3118 {
3119  uint64 processed = _SPI_current->processed;
3120  SPITupleTable *tuptable = _SPI_current->tuptable;
3121  bool failed = false;
3122 
3123  if (tuptable == NULL) /* spi_dest_startup was not called */
3124  failed = true;
3125  else if (processed != tuptable->numvals)
3126  failed = true;
3127 
3128  return failed;
3129 }
uint64 numvals
Definition: spi.h:27
uint64 processed
Definition: spi_priv.h:25
SPITupleTable * tuptable
Definition: spi_priv.h:26

References _SPI_current, SPITupleTable::numvals, _SPI_connection::processed, and _SPI_connection::tuptable.

Referenced by _SPI_cursor_operation(), and _SPI_pquery().

◆ _SPI_commit()

static void _SPI_commit ( bool  chain)
static

Definition at line 227 of file spi.c.

228 {
229  MemoryContext oldcontext = CurrentMemoryContext;
231 
232  /*
233  * Complain if we are in a context that doesn't permit transaction
234  * termination. (Note: here and _SPI_rollback should be the only places
235  * that throw ERRCODE_INVALID_TRANSACTION_TERMINATION, so that callers can
236  * test for that with security that they know what happened.)
237  */
238  if (_SPI_current->atomic)
239  ereport(ERROR,
240  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
241  errmsg("invalid transaction termination")));
242 
243  /*
244  * This restriction is required by PLs implemented on top of SPI. They
245  * use subtransactions to establish exception blocks that are supposed to
246  * be rolled back together if there is an error. Terminating the
247  * top-level transaction in such a block violates that idea. A future PL
248  * implementation might have different ideas about this, in which case
249  * this restriction would have to be refined or the check possibly be
250  * moved out of SPI into the PLs. Note however that the code below relies
251  * on not being within a subtransaction.
252  */
253  if (IsSubTransaction())
254  ereport(ERROR,
255  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
256  errmsg("cannot commit while a subtransaction is active")));
257 
258  if (chain)
260 
261  /* Catch any error occurring during the COMMIT */
262  PG_TRY();
263  {
264  /* Protect current SPI stack entry against deletion */
265  _SPI_current->internal_xact = true;
266 
267  /*
268  * Hold any pinned portals that any PLs might be using. We have to do
269  * this before changing transaction state, since this will run
270  * user-defined code that might throw an error.
271  */
273 
274  /* Release snapshots associated with portals */
276 
277  /* Do the deed */
279 
280  /* Immediately start a new transaction */
282  if (chain)
284 
285  MemoryContextSwitchTo(oldcontext);
286 
287  _SPI_current->internal_xact = false;
288  }
289  PG_CATCH();
290  {
291  ErrorData *edata;
292 
293  /* Save error info in caller's context */
294  MemoryContextSwitchTo(oldcontext);
295  edata = CopyErrorData();
296  FlushErrorState();
297 
298  /*
299  * Abort the failed transaction. If this fails too, we'll just
300  * propagate the error out ... there's not that much we can do.
301  */
303 
304  /* ... and start a new one */
306  if (chain)
308 
309  MemoryContextSwitchTo(oldcontext);
310 
311  _SPI_current->internal_xact = false;
312 
313  /* Now that we've cleaned up the transaction, re-throw the error */
314  ReThrowError(edata);
315  }
316  PG_END_TRY();
317 }
void ReThrowError(ErrorData *edata)
Definition: elog.c:1954
void FlushErrorState(void)
Definition: elog.c:1867
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
ErrorData * CopyErrorData(void)
Definition: elog.c:1746
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:381
#define ereport(elevel,...)
Definition: elog.h:149
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void HoldPinnedPortals(void)
Definition: portalmem.c:1207
void ForgetPortalSnapshots(void)
Definition: portalmem.c:1256
MemoryContextSwitchTo(old_ctx)
bool internal_xact
Definition: spi_priv.h:42
void SaveTransactionCharacteristics(SavedTransactionCharacteristics *s)
Definition: xact.c:3128
void RestoreTransactionCharacteristics(const SavedTransactionCharacteristics *s)
Definition: xact.c:3136
void StartTransactionCommand(void)
Definition: xact.c:3051
bool IsSubTransaction(void)
Definition: xact.c:5049
void CommitTransactionCommand(void)
Definition: xact.c:3149
void AbortCurrentTransaction(void)
Definition: xact.c:3443

References _SPI_current, AbortCurrentTransaction(), _SPI_connection::atomic, CommitTransactionCommand(), CopyErrorData(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, FlushErrorState(), ForgetPortalSnapshots(), HoldPinnedPortals(), _SPI_connection::internal_xact, IsSubTransaction(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_TRY, RestoreTransactionCharacteristics(), ReThrowError(), SaveTransactionCharacteristics(), and StartTransactionCommand().

Referenced by SPI_commit(), and SPI_commit_and_chain().

◆ _SPI_convert_params()

static ParamListInfo _SPI_convert_params ( int  nargs,
Oid argtypes,
Datum Values,
const char *  Nulls 
)
static

Definition at line 2849 of file spi.c.

2851 {
2852  ParamListInfo paramLI;
2853 
2854  if (nargs > 0)
2855  {
2856  paramLI = makeParamList(nargs);
2857 
2858  for (int i = 0; i < nargs; i++)
2859  {
2860  ParamExternData *prm = &paramLI->params[i];
2861 
2862  prm->value = Values[i];
2863  prm->isnull = (Nulls && Nulls[i] == 'n');
2864  prm->pflags = PARAM_FLAG_CONST;
2865  prm->ptype = argtypes[i];
2866  }
2867  }
2868  else
2869  paramLI = NULL;
2870  return paramLI;
2871 }
static bool Nulls[MAXATTR]
Definition: bootstrap.c:152
int i
Definition: isn.c:72
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
#define PARAM_FLAG_CONST
Definition: params.h:88
bool isnull
Definition: params.h:93
uint16 pflags
Definition: params.h:94
Datum value
Definition: params.h:92
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125

References i, ParamExternData::isnull, makeParamList(), Nulls, PARAM_FLAG_CONST, ParamListInfoData::params, ParamExternData::pflags, ParamExternData::ptype, and ParamExternData::value.

Referenced by SPI_cursor_open(), SPI_cursor_open_with_args(), SPI_execute_plan(), SPI_execute_snapshot(), and SPI_execute_with_args().

◆ _SPI_cursor_operation()

static void _SPI_cursor_operation ( Portal  portal,
FetchDirection  direction,
long  count,
DestReceiver dest 
)
static

Definition at line 3007 of file spi.c.

3009 {
3010  uint64 nfetched;
3011 
3012  /* Check that the portal is valid */
3013  if (!PortalIsValid(portal))
3014  elog(ERROR, "invalid portal in SPI cursor operation");
3015 
3016  /* Push the SPI stack */
3017  if (_SPI_begin_call(true) < 0)
3018  elog(ERROR, "SPI cursor operation called while not connected");
3019 
3020  /* Reset the SPI result (note we deliberately don't touch lastoid) */
3021  SPI_processed = 0;
3022  SPI_tuptable = NULL;
3023  _SPI_current->processed = 0;
3024  _SPI_current->tuptable = NULL;
3025 
3026  /* Run the cursor */
3027  nfetched = PortalRunFetch(portal,
3028  direction,
3029  count,
3030  dest);
3031 
3032  /*
3033  * Think not to combine this store with the preceding function call. If
3034  * the portal contains calls to functions that use SPI, then _SPI_stack is
3035  * likely to move around while the portal runs. When control returns,
3036  * _SPI_current will point to the correct stack entry... but the pointer
3037  * may be different than it was beforehand. So we must be sure to re-fetch
3038  * the pointer after the function call completes.
3039  */
3040  _SPI_current->processed = nfetched;
3041 
3042  if (dest->mydest == DestSPI && _SPI_checktuples())
3043  elog(ERROR, "consistency check on SPI tuple count failed");
3044 
3045  /* Put the result into place for access by caller */
3048 
3049  /* tuptable now is caller's responsibility, not SPI's */
3050  _SPI_current->tuptable = NULL;
3051 
3052  /* Pop the SPI stack */
3053  _SPI_end_call(true);
3054 }
@ DestSPI
Definition: dest.h:92
#define elog(elevel,...)
Definition: elog.h:225
#define PortalIsValid(p)
Definition: portal.h:212
uint64 PortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1391
static int _SPI_end_call(bool use_exec)
Definition: spi.c:3101
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
static int _SPI_begin_call(bool use_exec)
Definition: spi.c:3077
static bool _SPI_checktuples(void)
Definition: spi.c:3117

References _SPI_begin_call(), _SPI_checktuples(), _SPI_current, _SPI_end_call(), generate_unaccent_rules::dest, DestSPI, elog, ERROR, PortalIsValid, PortalRunFetch(), _SPI_connection::processed, SPI_processed, SPI_tuptable, and _SPI_connection::tuptable.

Referenced by SPI_cursor_fetch(), SPI_cursor_move(), SPI_scroll_cursor_fetch(), and SPI_scroll_cursor_move().

◆ _SPI_end_call()

static int _SPI_end_call ( bool  use_exec)
static

Definition at line 3101 of file spi.c.

3102 {
3103  if (use_exec)
3104  {
3105  /* switch to the procedure memory context */
3106  _SPI_procmem();
3107  /* mark Executor context no longer in use */
3109  /* and free Executor memory */
3111  }
3112 
3113  return 0;
3114 }
#define InvalidSubTransactionId
Definition: c.h:663
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
static MemoryContext _SPI_procmem(void)
Definition: spi.c:3064
MemoryContext execCxt
Definition: spi_priv.h:34

References _SPI_current, _SPI_procmem(), _SPI_connection::execCxt, _SPI_connection::execSubid, InvalidSubTransactionId, and MemoryContextReset().

Referenced by _SPI_cursor_operation(), SPI_cursor_open_internal(), SPI_cursor_open_with_args(), SPI_cursor_parse_open(), SPI_execute(), SPI_execute_extended(), SPI_execute_plan(), SPI_execute_plan_extended(), SPI_execute_plan_with_paramlist(), SPI_execute_snapshot(), SPI_execute_with_args(), SPI_prepare_cursor(), SPI_prepare_extended(), SPI_prepare_params(), SPI_register_relation(), SPI_saveplan(), and SPI_unregister_relation().

◆ _SPI_error_callback()

static void _SPI_error_callback ( void *  arg)
static

Definition at line 2961 of file spi.c.

2962 {
2963  SPICallbackArg *carg = (SPICallbackArg *) arg;
2964  const char *query = carg->query;
2965  int syntaxerrposition;
2966 
2967  if (query == NULL) /* in case arg wasn't set yet */
2968  return;
2969 
2970  /*
2971  * If there is a syntax error position, convert to internal syntax error;
2972  * otherwise treat the query as an item of context stack
2973  */
2974  syntaxerrposition = geterrposition();
2975  if (syntaxerrposition > 0)
2976  {
2977  errposition(0);
2978  internalerrposition(syntaxerrposition);
2979  internalerrquery(query);
2980  }
2981  else
2982  {
2983  /* Use the parse mode to decide how to describe the query */
2984  switch (carg->mode)
2985  {
2987  errcontext("PL/pgSQL expression \"%s\"", query);
2988  break;
2992  errcontext("PL/pgSQL assignment \"%s\"", query);
2993  break;
2994  default:
2995  errcontext("SQL statement \"%s\"", query);
2996  break;
2997  }
2998  }
2999 }
int internalerrquery(const char *query)
Definition: elog.c:1482
int internalerrposition(int cursorpos)
Definition: elog.c:1462
int geterrposition(void)
Definition: elog.c:1595
int errposition(int cursorpos)
Definition: elog.c:1446
#define errcontext
Definition: elog.h:196
@ RAW_PARSE_PLPGSQL_EXPR
Definition: parser.h:41
@ RAW_PARSE_PLPGSQL_ASSIGN2
Definition: parser.h:43
@ RAW_PARSE_PLPGSQL_ASSIGN1
Definition: parser.h:42
@ RAW_PARSE_PLPGSQL_ASSIGN3
Definition: parser.h:44
void * arg
const char * query
Definition: spi.c:55
RawParseMode mode
Definition: spi.c:56

References arg, errcontext, errposition(), geterrposition(), internalerrposition(), internalerrquery(), SPICallbackArg::mode, SPICallbackArg::query, RAW_PARSE_PLPGSQL_ASSIGN1, RAW_PARSE_PLPGSQL_ASSIGN2, RAW_PARSE_PLPGSQL_ASSIGN3, and RAW_PARSE_PLPGSQL_EXPR.

Referenced by _SPI_execute_plan(), _SPI_prepare_oneshot_plan(), _SPI_prepare_plan(), SPI_cursor_open_internal(), and SPI_plan_get_cached_plan().

◆ _SPI_execmem()

static MemoryContext _SPI_execmem ( void  )
static

Definition at line 3058 of file spi.c.

3059 {
3061 }

References _SPI_current, _SPI_connection::execCxt, and MemoryContextSwitchTo().

Referenced by _SPI_begin_call().

◆ _SPI_execute_plan()

static int _SPI_execute_plan ( SPIPlanPtr  plan,
const SPIExecuteOptions options,
Snapshot  snapshot,
Snapshot  crosscheck_snapshot,
bool  fire_triggers 
)
static

Definition at line 2399 of file spi.c.

2402 {
2403  int my_res = 0;
2404  uint64 my_processed = 0;
2405  SPITupleTable *my_tuptable = NULL;
2406  int res = 0;
2407  bool allow_nonatomic;
2408  bool pushed_active_snap = false;
2409  ResourceOwner plan_owner = options->owner;
2410  SPICallbackArg spicallbackarg;
2411  ErrorContextCallback spierrcontext;
2412  CachedPlan *cplan = NULL;
2413  ListCell *lc1;
2414 
2415  /*
2416  * We allow nonatomic behavior only if options->allow_nonatomic is set
2417  * *and* the SPI_OPT_NONATOMIC flag was given when connecting and we are
2418  * not inside a subtransaction. The latter two tests match whether
2419  * _SPI_commit() would allow a commit; see there for more commentary.
2420  */
2421  allow_nonatomic = options->allow_nonatomic &&
2423 
2424  /*
2425  * Setup error traceback support for ereport()
2426  */
2427  spicallbackarg.query = NULL; /* we'll fill this below */
2428  spicallbackarg.mode = plan->parse_mode;
2429  spierrcontext.callback = _SPI_error_callback;
2430  spierrcontext.arg = &spicallbackarg;
2431  spierrcontext.previous = error_context_stack;
2432  error_context_stack = &spierrcontext;
2433 
2434  /*
2435  * We support four distinct snapshot management behaviors:
2436  *
2437  * snapshot != InvalidSnapshot, read_only = true: use exactly the given
2438  * snapshot.
2439  *
2440  * snapshot != InvalidSnapshot, read_only = false: use the given snapshot,
2441  * modified by advancing its command ID before each querytree.
2442  *
2443  * snapshot == InvalidSnapshot, read_only = true: do nothing for queries
2444  * that require no snapshot. For those that do, ensure that a Portal
2445  * snapshot exists; then use that, or use the entry-time ActiveSnapshot if
2446  * that exists and is different.
2447  *
2448  * snapshot == InvalidSnapshot, read_only = false: do nothing for queries
2449  * that require no snapshot. For those that do, ensure that a Portal
2450  * snapshot exists; then, in atomic execution (!allow_nonatomic) take a
2451  * full new snapshot for each user command, and advance its command ID
2452  * before each querytree within the command. In allow_nonatomic mode we
2453  * just use the Portal snapshot unmodified.
2454  *
2455  * In the first two cases, we can just push the snap onto the stack once
2456  * for the whole plan list.
2457  *
2458  * Note that snapshot != InvalidSnapshot implies an atomic execution
2459  * context.
2460  */
2461  if (snapshot != InvalidSnapshot)
2462  {
2463  /* this intentionally tests the options field not the derived value */
2464  Assert(!options->allow_nonatomic);
2465  if (options->read_only)
2466  {
2467  PushActiveSnapshot(snapshot);
2468  pushed_active_snap = true;
2469  }
2470  else
2471  {
2472  /* Make sure we have a private copy of the snapshot to modify */
2473  PushCopiedSnapshot(snapshot);
2474  pushed_active_snap = true;
2475  }
2476  }
2477 
2478  /*
2479  * Ensure that we have a resource owner if plan is saved, and not if it
2480  * isn't.
2481  */
2482  if (!plan->saved)
2483  plan_owner = NULL;
2484  else if (plan_owner == NULL)
2485  plan_owner = CurrentResourceOwner;
2486 
2487  /*
2488  * We interpret must_return_tuples as "there must be at least one query,
2489  * and all of them must return tuples". This is a bit laxer than
2490  * SPI_is_cursor_plan's check, but there seems no reason to enforce that
2491  * there be only one query.
2492  */
2493  if (options->must_return_tuples && plan->plancache_list == NIL)
2494  ereport(ERROR,
2495  (errcode(ERRCODE_SYNTAX_ERROR),
2496  errmsg("empty query does not return tuples")));
2497 
2498  foreach(lc1, plan->plancache_list)
2499  {
2500  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
2501  List *stmt_list;
2502  ListCell *lc2;
2503 
2504  spicallbackarg.query = plansource->query_string;
2505 
2506  /*
2507  * If this is a one-shot plan, we still need to do parse analysis.
2508  */
2509  if (plan->oneshot)
2510  {
2511  RawStmt *parsetree = plansource->raw_parse_tree;
2512  const char *src = plansource->query_string;
2513  List *querytree_list;
2514 
2515  /*
2516  * Parameter datatypes are driven by parserSetup hook if provided,
2517  * otherwise we use the fixed parameter list.
2518  */
2519  if (parsetree == NULL)
2520  querytree_list = NIL;
2521  else if (plan->parserSetup != NULL)
2522  {
2523  Assert(plan->nargs == 0);
2524  querytree_list = pg_analyze_and_rewrite_withcb(parsetree,
2525  src,
2526  plan->parserSetup,
2527  plan->parserSetupArg,
2529  }
2530  else
2531  {
2532  querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree,
2533  src,
2534  plan->argtypes,
2535  plan->nargs,
2537  }
2538 
2539  /* Finish filling in the CachedPlanSource */
2540  CompleteCachedPlan(plansource,
2541  querytree_list,
2542  NULL,
2543  plan->argtypes,
2544  plan->nargs,
2545  plan->parserSetup,
2546  plan->parserSetupArg,
2547  plan->cursor_options,
2548  false); /* not fixed result */
2549  }
2550 
2551  /*
2552  * If asked to, complain when query does not return tuples.
2553  * (Replanning can't change this, so we can check it before that.
2554  * However, we can't check it till after parse analysis, so in the
2555  * case of a one-shot plan this is the earliest we could check.)
2556  */
2557  if (options->must_return_tuples && !plansource->resultDesc)
2558  {
2559  /* try to give a good error message */
2560  const char *cmdtag;
2561 
2562  /* A SELECT without resultDesc must be SELECT INTO */
2563  if (plansource->commandTag == CMDTAG_SELECT)
2564  cmdtag = "SELECT INTO";
2565  else
2566  cmdtag = GetCommandTagName(plansource->commandTag);
2567  ereport(ERROR,
2568  (errcode(ERRCODE_SYNTAX_ERROR),
2569  /* translator: %s is name of a SQL command, eg INSERT */
2570  errmsg("%s query does not return tuples", cmdtag)));
2571  }
2572 
2573  /*
2574  * Replan if needed, and increment plan refcount. If it's a saved
2575  * plan, the refcount must be backed by the plan_owner.
2576  */
2577  cplan = GetCachedPlan(plansource, options->params,
2578  plan_owner, _SPI_current->queryEnv);
2579 
2580  stmt_list = cplan->stmt_list;
2581 
2582  /*
2583  * If we weren't given a specific snapshot to use, and the statement
2584  * list requires a snapshot, set that up.
2585  */
2586  if (snapshot == InvalidSnapshot &&
2587  (list_length(stmt_list) > 1 ||
2588  (list_length(stmt_list) == 1 &&
2590  stmt_list)))))
2591  {
2592  /*
2593  * First, ensure there's a Portal-level snapshot. This back-fills
2594  * the snapshot stack in case the previous operation was a COMMIT
2595  * or ROLLBACK inside a procedure or DO block. (We can't put back
2596  * the Portal snapshot any sooner, or we'd break cases like doing
2597  * SET or LOCK just after COMMIT.) It's enough to check once per
2598  * statement list, since COMMIT/ROLLBACK/CALL/DO can't appear
2599  * within a multi-statement list.
2600  */
2602 
2603  /*
2604  * In the default non-read-only case, get a new per-statement-list
2605  * snapshot, replacing any that we pushed in a previous cycle.
2606  * Skip it when doing non-atomic execution, though (we rely
2607  * entirely on the Portal snapshot in that case).
2608  */
2609  if (!options->read_only && !allow_nonatomic)
2610  {
2611  if (pushed_active_snap)
2614  pushed_active_snap = true;
2615  }
2616  }
2617 
2618  foreach(lc2, stmt_list)
2619  {
2621  bool canSetTag = stmt->canSetTag;
2622  DestReceiver *dest;
2623 
2624  /*
2625  * Reset output state. (Note that if a non-SPI receiver is used,
2626  * _SPI_current->processed will stay zero, and that's what we'll
2627  * report to the caller. It's the receiver's job to count tuples
2628  * in that case.)
2629  */
2630  _SPI_current->processed = 0;
2631  _SPI_current->tuptable = NULL;
2632 
2633  /* Check for unsupported cases. */
2634  if (stmt->utilityStmt)
2635  {
2636  if (IsA(stmt->utilityStmt, CopyStmt))
2637  {
2638  CopyStmt *cstmt = (CopyStmt *) stmt->utilityStmt;
2639 
2640  if (cstmt->filename == NULL)
2641  {
2642  my_res = SPI_ERROR_COPY;
2643  goto fail;
2644  }
2645  }
2646  else if (IsA(stmt->utilityStmt, TransactionStmt))
2647  {
2648  my_res = SPI_ERROR_TRANSACTION;
2649  goto fail;
2650  }
2651  }
2652 
2653  if (options->read_only && !CommandIsReadOnly(stmt))
2654  ereport(ERROR,
2655  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2656  /* translator: %s is a SQL statement name */
2657  errmsg("%s is not allowed in a non-volatile function",
2658  CreateCommandName((Node *) stmt))));
2659 
2660  /*
2661  * If not read-only mode, advance the command counter before each
2662  * command and update the snapshot. (But skip it if the snapshot
2663  * isn't under our control.)
2664  */
2665  if (!options->read_only && pushed_active_snap)
2666  {
2669  }
2670 
2671  /*
2672  * Select appropriate tuple receiver. Output from non-canSetTag
2673  * subqueries always goes to the bit bucket.
2674  */
2675  if (!canSetTag)
2677  else if (options->dest)
2678  dest = options->dest;
2679  else
2681 
2682  if (stmt->utilityStmt == NULL)
2683  {
2684  QueryDesc *qdesc;
2685  Snapshot snap;
2686 
2687  if (ActiveSnapshotSet())
2688  snap = GetActiveSnapshot();
2689  else
2690  snap = InvalidSnapshot;
2691 
2692  qdesc = CreateQueryDesc(stmt,
2693  plansource->query_string,
2694  snap, crosscheck_snapshot,
2695  dest,
2696  options->params,
2698  0);
2699  res = _SPI_pquery(qdesc, fire_triggers,
2700  canSetTag ? options->tcount : 0);
2701  FreeQueryDesc(qdesc);
2702  }
2703  else
2704  {
2706  QueryCompletion qc;
2707 
2708  /*
2709  * If we're not allowing nonatomic operations, tell
2710  * ProcessUtility this is an atomic execution context.
2711  */
2712  if (allow_nonatomic)
2714  else
2716 
2719  plansource->query_string,
2720  true, /* protect plancache's node tree */
2721  context,
2722  options->params,
2724  dest,
2725  &qc);
2726 
2727  /* Update "processed" if stmt returned tuples */
2728  if (_SPI_current->tuptable)
2730 
2731  res = SPI_OK_UTILITY;
2732 
2733  /*
2734  * Some utility statements return a row count, even though the
2735  * tuples are not returned to the caller.
2736  */
2737  if (IsA(stmt->utilityStmt, CreateTableAsStmt))
2738  {
2739  CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
2740 
2741  if (qc.commandTag == CMDTAG_SELECT)
2743  else
2744  {
2745  /*
2746  * Must be an IF NOT EXISTS that did nothing, or a
2747  * CREATE ... WITH NO DATA.
2748  */
2749  Assert(ctastmt->if_not_exists ||
2750  ctastmt->into->skipData);
2751  _SPI_current->processed = 0;
2752  }
2753 
2754  /*
2755  * For historical reasons, if CREATE TABLE AS was spelled
2756  * as SELECT INTO, return a special return code.
2757  */
2758  if (ctastmt->is_select_into)
2759  res = SPI_OK_SELINTO;
2760  }
2761  else if (IsA(stmt->utilityStmt, CopyStmt))
2762  {
2763  Assert(qc.commandTag == CMDTAG_COPY);
2765  }
2766  }
2767 
2768  /*
2769  * The last canSetTag query sets the status values returned to the
2770  * caller. Be careful to free any tuptables not returned, to
2771  * avoid intra-transaction memory leak.
2772  */
2773  if (canSetTag)
2774  {
2775  my_processed = _SPI_current->processed;
2776  SPI_freetuptable(my_tuptable);
2777  my_tuptable = _SPI_current->tuptable;
2778  my_res = res;
2779  }
2780  else
2781  {
2783  _SPI_current->tuptable = NULL;
2784  }
2785 
2786  /*
2787  * We don't issue a destroy call to the receiver. The SPI and
2788  * None receivers would ignore it anyway, while if the caller
2789  * supplied a receiver, it's not our job to destroy it.
2790  */
2791 
2792  if (res < 0)
2793  {
2794  my_res = res;
2795  goto fail;
2796  }
2797  }
2798 
2799  /* Done with this plan, so release refcount */
2800  ReleaseCachedPlan(cplan, plan_owner);
2801  cplan = NULL;
2802 
2803  /*
2804  * If not read-only mode, advance the command counter after the last
2805  * command. This ensures that its effects are visible, in case it was
2806  * DDL that would affect the next CachedPlanSource.
2807  */
2808  if (!options->read_only)
2810  }
2811 
2812 fail:
2813 
2814  /* Pop the snapshot off the stack if we pushed one */
2815  if (pushed_active_snap)
2817 
2818  /* We no longer need the cached plan refcount, if any */
2819  if (cplan)
2820  ReleaseCachedPlan(cplan, plan_owner);
2821 
2822  /*
2823  * Pop the error context stack
2824  */
2825  error_context_stack = spierrcontext.previous;
2826 
2827  /* Save results for caller */
2828  SPI_processed = my_processed;
2829  SPI_tuptable = my_tuptable;
2830 
2831  /* tuptable now is caller's responsibility, not SPI's */
2832  _SPI_current->tuptable = NULL;
2833 
2834  /*
2835  * If none of the queries had canSetTag, return SPI_OK_REWRITTEN. Prior to
2836  * 8.4, we used return the last query's result code, but not its auxiliary
2837  * results, but that's confusing.
2838  */
2839  if (my_res == 0)
2840  my_res = SPI_OK_REWRITTEN;
2841 
2842  return my_res;
2843 }
#define Assert(condition)
Definition: c.h:863
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:40
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:47
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
@ DestNone
Definition: dest.h:87
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define stmt
Definition: indent_codes.h:59
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define NIL
Definition: pg_list.h:68
#define plan(x)
Definition: pg_regress.c:161
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:366
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, ResourceOwner owner, QueryEnvironment *queryEnv)
Definition: plancache.c:1168
void ReleaseCachedPlan(CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1291
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:769
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:676
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
bool PlannedStmtRequiresSnapshot(PlannedStmt *pstmt)
Definition: pquery.c:1732
void EnsurePortalSnapshotExists(void)
Definition: pquery.c:1780
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
tree context
Definition: radixtree.h:1835
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:712
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:782
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:700
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:770
#define InvalidSnapshot
Definition: snapshot.h:123
static void _SPI_error_callback(void *arg)
Definition: spi.c:2961
static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
Definition: spi.c:2874
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1386
#define SPI_ERROR_TRANSACTION
Definition: spi.h:75
#define SPI_OK_UTILITY
Definition: spi.h:85
#define SPI_OK_REWRITTEN
Definition: spi.h:95
#define SPI_OK_SELINTO
Definition: spi.h:87
#define SPI_ERROR_COPY
Definition: spi.h:69
CommandTag commandTag
Definition: plancache.h:101
const char * query_string
Definition: plancache.h:100
struct RawStmt * raw_parse_tree
Definition: plancache.h:99
TupleDesc resultDesc
Definition: plancache.h:108
List * stmt_list
Definition: plancache.h:150
char * filename
Definition: parsenodes.h:2605
IntoClause * into
Definition: parsenodes.h:3920
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
bool skipData
Definition: primnodes.h:170
Definition: pg_list.h:54
Definition: nodes.h:129
uint64 nprocessed
Definition: cmdtag.h:32
CommandTag commandTag
Definition: cmdtag.h:31
QueryEnvironment * queryEnv
Definition: spi_priv.h:37
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:499
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:94
static const char * CreateCommandName(Node *parsetree)
Definition: utility.h:103
ProcessUtilityContext
Definition: utility.h:21
@ PROCESS_UTILITY_QUERY_NONATOMIC
Definition: utility.h:24
@ PROCESS_UTILITY_QUERY
Definition: utility.h:23
void CommandCounterIncrement(void)
Definition: xact.c:1099

References _SPI_current, _SPI_error_callback(), _SPI_pquery(), ActiveSnapshotSet(), ErrorContextCallback::arg, Assert, _SPI_connection::atomic, ErrorContextCallback::callback, CommandCounterIncrement(), CommandIsReadOnly(), QueryCompletion::commandTag, CachedPlanSource::commandTag, CompleteCachedPlan(), context, CreateCommandName(), CreateDestReceiver(), CreateQueryDesc(), CurrentResourceOwner, generate_unaccent_rules::dest, DestNone, DestSPI, EnsurePortalSnapshotExists(), ereport, errcode(), errmsg(), ERROR, error_context_stack, CopyStmt::filename, FreeQueryDesc(), GetActiveSnapshot(), GetCachedPlan(), GetCommandTagName(), GetTransactionSnapshot(), if(), CreateTableAsStmt::if_not_exists, InitializeQueryCompletion(), CreateTableAsStmt::into, InvalidSnapshot, CreateTableAsStmt::is_select_into, IsA, IsSubTransaction(), lfirst, lfirst_node, linitial_node, list_length(), SPICallbackArg::mode, NIL, QueryCompletion::nprocessed, SPITupleTable::numvals, pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_withcb(), plan, PlannedStmtRequiresSnapshot(), PopActiveSnapshot(), ErrorContextCallback::previous, PROCESS_UTILITY_QUERY, PROCESS_UTILITY_QUERY_NONATOMIC, _SPI_connection::processed, ProcessUtility(), PushActiveSnapshot(), PushCopiedSnapshot(), SPICallbackArg::query, CachedPlanSource::query_string, _SPI_connection::queryEnv, CachedPlanSource::raw_parse_tree, ReleaseCachedPlan(), res, CachedPlanSource::resultDesc, IntoClause::skipData, SPI_ERROR_COPY, SPI_ERROR_TRANSACTION, SPI_freetuptable(), SPI_OK_REWRITTEN, SPI_OK_SELINTO, SPI_OK_UTILITY, SPI_processed, SPI_tuptable, stmt, CachedPlan::stmt_list, _SPI_connection::tuptable, and UpdateActiveSnapshotCommandId().

Referenced by SPI_execute(), SPI_execute_extended(), SPI_execute_plan(), SPI_execute_plan_extended(), SPI_execute_plan_with_paramlist(), SPI_execute_snapshot(), and SPI_execute_with_args().

◆ _SPI_find_ENR_by_name()

static EphemeralNamedRelation _SPI_find_ENR_by_name ( const char *  name)
static

Definition at line 3280 of file spi.c.

3281 {
3282  /* internal static function; any error is bug in SPI itself */
3283  Assert(name != NULL);
3284 
3285  /* fast exit if no tuplestores have been added */
3286  if (_SPI_current->queryEnv == NULL)
3287  return NULL;
3288 
3289  return get_ENR(_SPI_current->queryEnv, name);
3290 }
EphemeralNamedRelation get_ENR(QueryEnvironment *queryEnv, const char *name)
const char * name

References _SPI_current, Assert, get_ENR(), name, and _SPI_connection::queryEnv.

Referenced by SPI_register_relation(), and SPI_unregister_relation().

◆ _SPI_make_plan_non_temp()

static SPIPlanPtr _SPI_make_plan_non_temp ( SPIPlanPtr  plan)
static

Definition at line 3141 of file spi.c.

3142 {
3143  SPIPlanPtr newplan;
3144  MemoryContext parentcxt = _SPI_current->procCxt;
3145  MemoryContext plancxt;
3146  MemoryContext oldcxt;
3147  ListCell *lc;
3148 
3149  /* Assert the input is a temporary SPIPlan */
3150  Assert(plan->magic == _SPI_PLAN_MAGIC);
3151  Assert(plan->plancxt == NULL);
3152  /* One-shot plans can't be saved */
3153  Assert(!plan->oneshot);
3154 
3155  /*
3156  * Create a memory context for the plan, underneath the procedure context.
3157  * We don't expect the plan to be very large.
3158  */
3159  plancxt = AllocSetContextCreate(parentcxt,
3160  "SPI Plan",
3162  oldcxt = MemoryContextSwitchTo(plancxt);
3163 
3164  /* Copy the _SPI_plan struct and subsidiary data into the new context */
3165  newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
3166  newplan->magic = _SPI_PLAN_MAGIC;
3167  newplan->plancxt = plancxt;
3168  newplan->parse_mode = plan->parse_mode;
3169  newplan->cursor_options = plan->cursor_options;
3170  newplan->nargs = plan->nargs;
3171  if (plan->nargs > 0)
3172  {
3173  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
3174  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
3175  }
3176  else
3177  newplan->argtypes = NULL;
3178  newplan->parserSetup = plan->parserSetup;
3179  newplan->parserSetupArg = plan->parserSetupArg;
3180 
3181  /*
3182  * Reparent all the CachedPlanSources into the procedure context. In
3183  * theory this could fail partway through due to the pallocs, but we don't
3184  * care too much since both the procedure context and the executor context
3185  * would go away on error.
3186  */
3187  foreach(lc, plan->plancache_list)
3188  {
3189  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3190 
3191  CachedPlanSetParentContext(plansource, parentcxt);
3192 
3193  /* Build new list, with list cells in plancxt */
3194  newplan->plancache_list = lappend(newplan->plancache_list, plansource);
3195  }
3196 
3197  MemoryContextSwitchTo(oldcxt);
3198 
3199  /* For safety, unlink the CachedPlanSources from the temporary plan */
3200  plan->plancache_list = NIL;
3201 
3202  return newplan;
3203 }
List * lappend(List *list, void *datum)
Definition: list.c:339
void * palloc0(Size size)
Definition: mcxt.c:1347
void * palloc(Size size)
Definition: mcxt.c:1317
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
void CachedPlanSetParentContext(CachedPlanSource *plansource, MemoryContext newcontext)
Definition: plancache.c:1498
unsigned int Oid
Definition: postgres_ext.h:31
struct _SPI_plan * SPIPlanPtr
Definition: spi.h:66
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
MemoryContext procCxt
Definition: spi_priv.h:33
ParserSetupHook parserSetup
Definition: spi_priv.h:101
List * plancache_list
Definition: spi_priv.h:95
int magic
Definition: spi_priv.h:92
int cursor_options
Definition: spi_priv.h:98
Oid * argtypes
Definition: spi_priv.h:100
int nargs
Definition: spi_priv.h:99
MemoryContext plancxt
Definition: spi_priv.h:96
RawParseMode parse_mode
Definition: spi_priv.h:97
void * parserSetupArg
Definition: spi_priv.h:102

References _SPI_current, _SPI_PLAN_MAGIC, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, _SPI_plan::argtypes, Assert, CachedPlanSetParentContext(), _SPI_plan::cursor_options, lappend(), lfirst, _SPI_plan::magic, MemoryContextSwitchTo(), _SPI_plan::nargs, NIL, palloc(), palloc0(), _SPI_plan::parse_mode, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, plan, _SPI_plan::plancache_list, _SPI_plan::plancxt, and _SPI_connection::procCxt.

Referenced by SPI_prepare_cursor(), SPI_prepare_extended(), and SPI_prepare_params().

◆ _SPI_pquery()

static int _SPI_pquery ( QueryDesc queryDesc,
bool  fire_triggers,
uint64  tcount 
)
static

Definition at line 2874 of file spi.c.

2875 {
2876  int operation = queryDesc->operation;
2877  int eflags;
2878  int res;
2879 
2880  switch (operation)
2881  {
2882  case CMD_SELECT:
2883  if (queryDesc->dest->mydest == DestNone)
2884  {
2885  /* Don't return SPI_OK_SELECT if we're discarding result */
2886  res = SPI_OK_UTILITY;
2887  }
2888  else
2889  res = SPI_OK_SELECT;
2890  break;
2891  case CMD_INSERT:
2892  if (queryDesc->plannedstmt->hasReturning)
2894  else
2895  res = SPI_OK_INSERT;
2896  break;
2897  case CMD_DELETE:
2898  if (queryDesc->plannedstmt->hasReturning)
2900  else
2901  res = SPI_OK_DELETE;
2902  break;
2903  case CMD_UPDATE:
2904  if (queryDesc->plannedstmt->hasReturning)
2906  else
2907  res = SPI_OK_UPDATE;
2908  break;
2909  case CMD_MERGE:
2910  if (queryDesc->plannedstmt->hasReturning)
2912  else
2913  res = SPI_OK_MERGE;
2914  break;
2915  default:
2916  return SPI_ERROR_OPUNKNOWN;
2917  }
2918 
2919 #ifdef SPI_EXECUTOR_STATS
2920  if (ShowExecutorStats)
2921  ResetUsage();
2922 #endif
2923 
2924  /* Select execution options */
2925  if (fire_triggers)
2926  eflags = 0; /* default run-to-completion flags */
2927  else
2928  eflags = EXEC_FLAG_SKIP_TRIGGERS;
2929 
2930  ExecutorStart(queryDesc, eflags);
2931 
2932  ExecutorRun(queryDesc, ForwardScanDirection, tcount, true);
2933 
2934  _SPI_current->processed = queryDesc->estate->es_processed;
2935 
2936  if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
2937  queryDesc->dest->mydest == DestSPI)
2938  {
2939  if (_SPI_checktuples())
2940  elog(ERROR, "consistency check on SPI tuple count failed");
2941  }
2942 
2943  ExecutorFinish(queryDesc);
2944  ExecutorEnd(queryDesc);
2945  /* FreeQueryDesc is done by the caller */
2946 
2947 #ifdef SPI_EXECUTOR_STATS
2948  if (ShowExecutorStats)
2949  ShowUsage("SPI EXECUTOR STATS");
2950 #endif
2951 
2952  return res;
2953 }
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:466
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:406
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:121
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:296
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:70
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
void ShowUsage(const char *title)
Definition: postgres.c:5118
void ResetUsage(void)
Definition: postgres.c:5111
@ ForwardScanDirection
Definition: sdir.h:28
#define SPI_OK_INSERT
Definition: spi.h:88
#define SPI_OK_UPDATE
Definition: spi.h:90
#define SPI_OK_MERGE
Definition: spi.h:99
#define SPI_ERROR_OPUNKNOWN
Definition: spi.h:70
#define SPI_OK_UPDATE_RETURNING
Definition: spi.h:94
#define SPI_OK_DELETE
Definition: spi.h:89
#define SPI_OK_INSERT_RETURNING
Definition: spi.h:92
#define SPI_OK_DELETE_RETURNING
Definition: spi.h:93
#define SPI_OK_MERGE_RETURNING
Definition: spi.h:100
#define SPI_OK_SELECT
Definition: spi.h:86
uint64 es_processed
Definition: execnodes.h:679
bool hasReturning
Definition: plannodes.h:56
DestReceiver * dest
Definition: execdesc.h:41
EState * estate
Definition: execdesc.h:48
CmdType operation
Definition: execdesc.h:36
PlannedStmt * plannedstmt
Definition: execdesc.h:37
CommandDest mydest
Definition: dest.h:128

References _SPI_checktuples(), _SPI_current, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_SELECT, CMD_UPDATE, QueryDesc::dest, DestNone, DestSPI, elog, ERROR, EState::es_processed, QueryDesc::estate, EXEC_FLAG_SKIP_TRIGGERS, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, PlannedStmt::hasReturning, _DestReceiver::mydest, QueryDesc::operation, QueryDesc::plannedstmt, _SPI_connection::processed, res, ResetUsage(), ShowUsage(), SPI_ERROR_OPUNKNOWN, SPI_OK_DELETE, SPI_OK_DELETE_RETURNING, SPI_OK_INSERT, SPI_OK_INSERT_RETURNING, SPI_OK_MERGE, SPI_OK_MERGE_RETURNING, SPI_OK_SELECT, SPI_OK_UPDATE, SPI_OK_UPDATE_RETURNING, and SPI_OK_UTILITY.

Referenced by _SPI_execute_plan().

◆ _SPI_prepare_oneshot_plan()

static void _SPI_prepare_oneshot_plan ( const char *  src,
SPIPlanPtr  plan 
)
static

Definition at line 2329 of file spi.c.

2330 {
2331  List *raw_parsetree_list;
2332  List *plancache_list;
2333  ListCell *list_item;
2334  SPICallbackArg spicallbackarg;
2335  ErrorContextCallback spierrcontext;
2336 
2337  /*
2338  * Setup error traceback support for ereport()
2339  */
2340  spicallbackarg.query = src;
2341  spicallbackarg.mode = plan->parse_mode;
2342  spierrcontext.callback = _SPI_error_callback;
2343  spierrcontext.arg = &spicallbackarg;
2344  spierrcontext.previous = error_context_stack;
2345  error_context_stack = &spierrcontext;
2346 
2347  /*
2348  * Parse the request string into a list of raw parse trees.
2349  */
2350  raw_parsetree_list = raw_parser(src, plan->parse_mode);
2351 
2352  /*
2353  * Construct plancache entries, but don't do parse analysis yet.
2354  */
2355  plancache_list = NIL;
2356 
2357  foreach(list_item, raw_parsetree_list)
2358  {
2359  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
2360  CachedPlanSource *plansource;
2361 
2362  plansource = CreateOneShotCachedPlan(parsetree,
2363  src,
2364  CreateCommandTag(parsetree->stmt));
2365 
2366  plancache_list = lappend(plancache_list, plansource);
2367  }
2368 
2369  plan->plancache_list = plancache_list;
2370  plan->oneshot = true;
2371 
2372  /*
2373  * Pop the error context stack
2374  */
2375  error_context_stack = spierrcontext.previous;
2376 }
List * raw_parser(const char *str, RawParseMode mode)
Definition: parser.c:42
CachedPlanSource * CreateOneShotCachedPlan(RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:276
Node * stmt
Definition: parsenodes.h:2022
CommandTag CreateCommandTag(Node *parsetree)
Definition: utility.c:2362

References _SPI_error_callback(), ErrorContextCallback::arg, ErrorContextCallback::callback, CreateCommandTag(), CreateOneShotCachedPlan(), error_context_stack, lappend(), lfirst_node, SPICallbackArg::mode, NIL, plan, ErrorContextCallback::previous, SPICallbackArg::query, raw_parser(), and RawStmt::stmt.

Referenced by SPI_execute(), SPI_execute_extended(), and SPI_execute_with_args().

◆ _SPI_prepare_plan()

static void _SPI_prepare_plan ( const char *  src,
SPIPlanPtr  plan 
)
static

Definition at line 2221 of file spi.c.

2222 {
2223  List *raw_parsetree_list;
2224  List *plancache_list;
2225  ListCell *list_item;
2226  SPICallbackArg spicallbackarg;
2227  ErrorContextCallback spierrcontext;
2228 
2229  /*
2230  * Setup error traceback support for ereport()
2231  */
2232  spicallbackarg.query = src;
2233  spicallbackarg.mode = plan->parse_mode;
2234  spierrcontext.callback = _SPI_error_callback;
2235  spierrcontext.arg = &spicallbackarg;
2236  spierrcontext.previous = error_context_stack;
2237  error_context_stack = &spierrcontext;
2238 
2239  /*
2240  * Parse the request string into a list of raw parse trees.
2241  */
2242  raw_parsetree_list = raw_parser(src, plan->parse_mode);
2243 
2244  /*
2245  * Do parse analysis and rule rewrite for each raw parsetree, storing the
2246  * results into unsaved plancache entries.
2247  */
2248  plancache_list = NIL;
2249 
2250  foreach(list_item, raw_parsetree_list)
2251  {
2252  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
2253  List *stmt_list;
2254  CachedPlanSource *plansource;
2255 
2256  /*
2257  * Create the CachedPlanSource before we do parse analysis, since it
2258  * needs to see the unmodified raw parse tree.
2259  */
2260  plansource = CreateCachedPlan(parsetree,
2261  src,
2262  CreateCommandTag(parsetree->stmt));
2263 
2264  /*
2265  * Parameter datatypes are driven by parserSetup hook if provided,
2266  * otherwise we use the fixed parameter list.
2267  */
2268  if (plan->parserSetup != NULL)
2269  {
2270  Assert(plan->nargs == 0);
2271  stmt_list = pg_analyze_and_rewrite_withcb(parsetree,
2272  src,
2273  plan->parserSetup,
2274  plan->parserSetupArg,
2276  }
2277  else
2278  {
2279  stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
2280  src,
2281  plan->argtypes,
2282  plan->nargs,
2284  }
2285 
2286  /* Finish filling in the CachedPlanSource */
2287  CompleteCachedPlan(plansource,
2288  stmt_list,
2289  NULL,
2290  plan->argtypes,
2291  plan->nargs,
2292  plan->parserSetup,
2293  plan->parserSetupArg,
2294  plan->cursor_options,
2295  false); /* not fixed result */
2296 
2297  plancache_list = lappend(plancache_list, plansource);
2298  }
2299 
2300  plan->plancache_list = plancache_list;
2301  plan->oneshot = false;
2302 
2303  /*
2304  * Pop the error context stack
2305  */
2306  error_context_stack = spierrcontext.previous;
2307 }
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:192

References _SPI_current, _SPI_error_callback(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CompleteCachedPlan(), CreateCachedPlan(), CreateCommandTag(), error_context_stack, lappend(), lfirst_node, SPICallbackArg::mode, NIL, pg_analyze_and_rewrite_fixedparams(), pg_analyze_and_rewrite_withcb(), plan, ErrorContextCallback::previous, SPICallbackArg::query, _SPI_connection::queryEnv, raw_parser(), and RawStmt::stmt.

Referenced by SPI_cursor_open_with_args(), SPI_cursor_parse_open(), SPI_prepare_cursor(), SPI_prepare_extended(), and SPI_prepare_params().

◆ _SPI_procmem()

static MemoryContext _SPI_procmem ( void  )
static

Definition at line 3064 of file spi.c.

3065 {
3067 }

References _SPI_current, MemoryContextSwitchTo(), and _SPI_connection::procCxt.

Referenced by _SPI_end_call(), and spi_dest_startup().

◆ _SPI_rollback()

static void _SPI_rollback ( bool  chain)
static

Definition at line 332 of file spi.c.

333 {
334  MemoryContext oldcontext = CurrentMemoryContext;
336 
337  /* see comments in _SPI_commit() */
338  if (_SPI_current->atomic)
339  ereport(ERROR,
340  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
341  errmsg("invalid transaction termination")));
342 
343  /* see comments in _SPI_commit() */
344  if (IsSubTransaction())
345  ereport(ERROR,
346  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
347  errmsg("cannot roll back while a subtransaction is active")));
348 
349  if (chain)
351 
352  /* Catch any error occurring during the ROLLBACK */
353  PG_TRY();
354  {
355  /* Protect current SPI stack entry against deletion */
356  _SPI_current->internal_xact = true;
357 
358  /*
359  * Hold any pinned portals that any PLs might be using. We have to do
360  * this before changing transaction state, since this will run
361  * user-defined code that might throw an error, and in any case
362  * couldn't be run in an already-aborted transaction.
363  */
365 
366  /* Release snapshots associated with portals */
368 
369  /* Do the deed */
371 
372  /* Immediately start a new transaction */
374  if (chain)
376 
377  MemoryContextSwitchTo(oldcontext);
378 
379  _SPI_current->internal_xact = false;
380  }
381  PG_CATCH();
382  {
383  ErrorData *edata;
384 
385  /* Save error info in caller's context */
386  MemoryContextSwitchTo(oldcontext);
387  edata = CopyErrorData();
388  FlushErrorState();
389 
390  /*
391  * Try again to abort the failed transaction. If this fails too,
392  * we'll just propagate the error out ... there's not that much we can
393  * do.
394  */
396 
397  /* ... and start a new one */
399  if (chain)
401 
402  MemoryContextSwitchTo(oldcontext);
403 
404  _SPI_current->internal_xact = false;
405 
406  /* Now that we've cleaned up the transaction, re-throw the error */
407  ReThrowError(edata);
408  }
409  PG_END_TRY();
410 }

References _SPI_current, AbortCurrentTransaction(), _SPI_connection::atomic, CopyErrorData(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, FlushErrorState(), ForgetPortalSnapshots(), HoldPinnedPortals(), _SPI_connection::internal_xact, IsSubTransaction(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_TRY, RestoreTransactionCharacteristics(), ReThrowError(), SaveTransactionCharacteristics(), and StartTransactionCommand().

Referenced by SPI_rollback(), and SPI_rollback_and_chain().

◆ _SPI_save_plan()

static SPIPlanPtr _SPI_save_plan ( SPIPlanPtr  plan)
static

Definition at line 3209 of file spi.c.

3210 {
3211  SPIPlanPtr newplan;
3212  MemoryContext plancxt;
3213  MemoryContext oldcxt;
3214  ListCell *lc;
3215 
3216  /* One-shot plans can't be saved */
3217  Assert(!plan->oneshot);
3218 
3219  /*
3220  * Create a memory context for the plan. We don't expect the plan to be
3221  * very large, so use smaller-than-default alloc parameters. It's a
3222  * transient context until we finish copying everything.
3223  */
3225  "SPI Plan",
3227  oldcxt = MemoryContextSwitchTo(plancxt);
3228 
3229  /* Copy the SPI plan into its own context */
3230  newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
3231  newplan->magic = _SPI_PLAN_MAGIC;
3232  newplan->plancxt = plancxt;
3233  newplan->parse_mode = plan->parse_mode;
3234  newplan->cursor_options = plan->cursor_options;
3235  newplan->nargs = plan->nargs;
3236  if (plan->nargs > 0)
3237  {
3238  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
3239  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
3240  }
3241  else
3242  newplan->argtypes = NULL;
3243  newplan->parserSetup = plan->parserSetup;
3244  newplan->parserSetupArg = plan->parserSetupArg;
3245 
3246  /* Copy all the plancache entries */
3247  foreach(lc, plan->plancache_list)
3248  {
3249  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3250  CachedPlanSource *newsource;
3251 
3252  newsource = CopyCachedPlan(plansource);
3253  newplan->plancache_list = lappend(newplan->plancache_list, newsource);
3254  }
3255 
3256  MemoryContextSwitchTo(oldcxt);
3257 
3258  /*
3259  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
3260  * component CachedPlanSources as saved. This sequence cannot fail
3261  * partway through, so there's no risk of long-term memory leakage.
3262  */
3263  newplan->saved = true;
3265 
3266  foreach(lc, newplan->plancache_list)
3267  {
3268  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3269 
3270  SaveCachedPlan(plansource);
3271  }
3272 
3273  return newplan;
3274 }
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:637
MemoryContext CacheMemoryContext
Definition: mcxt.c:152
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:482
CachedPlanSource * CopyCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:1536
bool saved
Definition: spi_priv.h:93

References _SPI_PLAN_MAGIC, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, _SPI_plan::argtypes, Assert, CacheMemoryContext, CopyCachedPlan(), CurrentMemoryContext, _SPI_plan::cursor_options, lappend(), lfirst, _SPI_plan::magic, MemoryContextSetParent(), MemoryContextSwitchTo(), _SPI_plan::nargs, palloc(), palloc0(), _SPI_plan::parse_mode, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, plan, _SPI_plan::plancache_list, _SPI_plan::plancxt, SaveCachedPlan(), and _SPI_plan::saved.

Referenced by SPI_saveplan().

◆ AtEOSubXact_SPI()

void AtEOSubXact_SPI ( bool  isCommit,
SubTransactionId  mySubid 
)

Definition at line 482 of file spi.c.

483 {
484  bool found = false;
485 
486  while (_SPI_connected >= 0)
487  {
489 
490  if (connection->connectSubid != mySubid)
491  break; /* couldn't be any underneath it either */
492 
493  if (connection->internal_xact)
494  break;
495 
496  found = true;
497 
498  /*
499  * Release procedure memory explicitly (see note in SPI_connect)
500  */
501  if (connection->execCxt)
502  {
504  connection->execCxt = NULL;
505  }
506  if (connection->procCxt)
507  {
509  connection->procCxt = NULL;
510  }
511 
512  /*
513  * Restore outer global variables and pop the stack entry. Unlike
514  * SPI_finish(), we don't risk switching to memory contexts that might
515  * be already gone.
516  */
517  SPI_processed = connection->outer_processed;
518  SPI_tuptable = connection->outer_tuptable;
519  SPI_result = connection->outer_result;
520 
521  _SPI_connected--;
522  if (_SPI_connected < 0)
523  _SPI_current = NULL;
524  else
526  }
527 
528  if (found && isCommit)
530  (errcode(ERRCODE_WARNING),
531  errmsg("subtransaction left non-empty SPI stack"),
532  errhint("Check for missing \"SPI_finish\" calls.")));
533 
534  /*
535  * If we are aborting a subtransaction and there is an open SPI context
536  * surrounding the subxact, clean up to prevent memory leakage.
537  */
538  if (_SPI_current && !isCommit)
539  {
540  slist_mutable_iter siter;
541 
542  /*
543  * Throw away executor state if current executor operation was started
544  * within current subxact (essentially, force a _SPI_end_call(true)).
545  */
546  if (_SPI_current->execSubid >= mySubid)
547  {
550  }
551 
552  /* throw away any tuple tables created within current subxact */
554  {
555  SPITupleTable *tuptable;
556 
557  tuptable = slist_container(SPITupleTable, next, siter.cur);
558  if (tuptable->subid >= mySubid)
559  {
560  /*
561  * If we used SPI_freetuptable() here, its internal search of
562  * the tuptables list would make this operation O(N^2).
563  * Instead, just free the tuptable manually. This should
564  * match what SPI_freetuptable() does.
565  */
566  slist_delete_current(&siter);
567  if (tuptable == _SPI_current->tuptable)
568  _SPI_current->tuptable = NULL;
569  if (tuptable == SPI_tuptable)
570  SPI_tuptable = NULL;
571  MemoryContextDelete(tuptable->tuptabcxt);
572  }
573  }
574  }
575 }
static int32 next
Definition: blutils.c:219
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define WARNING
Definition: elog.h:36
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:1084
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:1148
#define slist_container(type, membername, ptr)
Definition: ilist.h:1106
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
static int _SPI_connected
Definition: spi.c:51
static _SPI_connection * _SPI_stack
Definition: spi.c:48
int SPI_result
Definition: spi.c:46
MemoryContext tuptabcxt
Definition: spi.h:31
SubTransactionId subid
Definition: spi.h:33
slist_head tuptables
Definition: spi_priv.h:32
slist_node * cur
Definition: ilist.h:274

References _SPI_connected, _SPI_current, _SPI_stack, slist_mutable_iter::cur, ereport, errcode(), errhint(), errmsg(), _SPI_connection::execCxt, _SPI_connection::execSubid, InvalidSubTransactionId, MemoryContextDelete(), MemoryContextReset(), next, slist_container, slist_delete_current(), slist_foreach_modify, SPI_processed, SPI_result, SPI_tuptable, SPITupleTable::subid, SPITupleTable::tuptabcxt, _SPI_connection::tuptable, _SPI_connection::tuptables, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_SPI()

void AtEOXact_SPI ( bool  isCommit)

Definition at line 428 of file spi.c.

429 {
430  bool found = false;
431 
432  /*
433  * Pop stack entries, stopping if we find one marked internal_xact (that
434  * one belongs to the caller of SPI_commit or SPI_rollback).
435  */
436  while (_SPI_connected >= 0)
437  {
439 
440  if (connection->internal_xact)
441  break;
442 
443  found = true;
444 
445  /*
446  * We need not release the procedure's memory contexts explicitly, as
447  * they'll go away automatically when their parent context does; see
448  * notes in SPI_connect_ext.
449  */
450 
451  /*
452  * Restore outer global variables and pop the stack entry. Unlike
453  * SPI_finish(), we don't risk switching to memory contexts that might
454  * be already gone.
455  */
456  SPI_processed = connection->outer_processed;
457  SPI_tuptable = connection->outer_tuptable;
458  SPI_result = connection->outer_result;
459 
460  _SPI_connected--;
461  if (_SPI_connected < 0)
462  _SPI_current = NULL;
463  else
465  }
466 
467  /* We should only find entries to pop during an ABORT. */
468  if (found && isCommit)
470  (errcode(ERRCODE_WARNING),
471  errmsg("transaction left non-empty SPI stack"),
472  errhint("Check for missing \"SPI_finish\" calls.")));
473 }

References _SPI_connected, _SPI_current, _SPI_stack, ereport, errcode(), errhint(), errmsg(), SPI_processed, SPI_result, SPI_tuptable, and WARNING.

Referenced by AbortTransaction(), CommitTransaction(), and PrepareTransaction().

◆ SPI_commit()

void SPI_commit ( void  )

Definition at line 320 of file spi.c.

321 {
322  _SPI_commit(false);
323 }
static void _SPI_commit(bool chain)
Definition: spi.c:227

References _SPI_commit().

Referenced by exec_stmt_commit(), plperl_spi_commit(), pltcl_commit(), and PLy_commit().

◆ SPI_commit_and_chain()

void SPI_commit_and_chain ( void  )

Definition at line 326 of file spi.c.

327 {
328  _SPI_commit(true);
329 }

References _SPI_commit().

Referenced by exec_stmt_commit().

◆ SPI_connect()

◆ SPI_connect_ext()

int SPI_connect_ext ( int  options)

Definition at line 100 of file spi.c.

101 {
102  int newdepth;
103 
104  /* Enlarge stack if necessary */
105  if (_SPI_stack == NULL)
106  {
107  if (_SPI_connected != -1 || _SPI_stack_depth != 0)
108  elog(ERROR, "SPI stack corrupted");
109  newdepth = 16;
112  newdepth * sizeof(_SPI_connection));
113  _SPI_stack_depth = newdepth;
114  }
115  else
116  {
118  elog(ERROR, "SPI stack corrupted");
119  if (_SPI_stack_depth == _SPI_connected + 1)
120  {
121  newdepth = _SPI_stack_depth * 2;
124  newdepth * sizeof(_SPI_connection));
125  _SPI_stack_depth = newdepth;
126  }
127  }
128 
129  /* Enter new stack level */
130  _SPI_connected++;
132 
134  _SPI_current->processed = 0;
135  _SPI_current->tuptable = NULL;
138  _SPI_current->procCxt = NULL; /* in case we fail to create 'em */
139  _SPI_current->execCxt = NULL;
141  _SPI_current->queryEnv = NULL;
143  _SPI_current->internal_xact = false;
147 
148  /*
149  * Create memory contexts for this procedure
150  *
151  * In atomic contexts (the normal case), we use TopTransactionContext,
152  * otherwise PortalContext, so that it lives across transaction
153  * boundaries.
154  *
155  * XXX It could be better to use PortalContext as the parent context in
156  * all cases, but we may not be inside a portal (consider deferred-trigger
157  * execution). Perhaps CurTransactionContext could be an option? For now
158  * it doesn't matter because we clean up explicitly in AtEOSubXact_SPI();
159  * but see also AtEOXact_SPI().
160  */
162  "SPI Proc",
165  "SPI Exec",
167  /* ... and switch to procedure's context */
169 
170  /*
171  * Reset API global variables so that current caller cannot accidentally
172  * depend on state of an outer caller.
173  */
174  SPI_processed = 0;
175  SPI_tuptable = NULL;
176  SPI_result = 0;
177 
178  return SPI_OK_CONNECT;
179 }
static void slist_init(slist_head *head)
Definition: ilist.h:986
return false
Definition: isn.c:130
MemoryContext TopTransactionContext
Definition: mcxt.c:154
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1541
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
MemoryContext PortalContext
Definition: mcxt.c:158
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static int _SPI_stack_depth
Definition: spi.c:50
#define SPI_OPT_NONATOMIC
Definition: spi.h:102
#define SPI_OK_CONNECT
Definition: spi.h:82
SubTransactionId connectSubid
Definition: spi_priv.h:36
SPITupleTable * outer_tuptable
Definition: spi_priv.h:47
int outer_result
Definition: spi_priv.h:48
uint64 outer_processed
Definition: spi_priv.h:46
MemoryContext savedcxt
Definition: spi_priv.h:35

References _SPI_connected, _SPI_current, _SPI_stack, _SPI_stack_depth, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, _SPI_connection::atomic, _SPI_connection::connectSubid, elog, ERROR, _SPI_connection::execCxt, _SPI_connection::execSubid, false, GetCurrentSubTransactionId(), _SPI_connection::internal_xact, InvalidSubTransactionId, MemoryContextAlloc(), MemoryContextSwitchTo(), _SPI_connection::outer_processed, _SPI_connection::outer_result, _SPI_connection::outer_tuptable, PortalContext, _SPI_connection::procCxt, _SPI_connection::processed, _SPI_connection::queryEnv, repalloc(), _SPI_connection::savedcxt, slist_init(), SPI_OK_CONNECT, SPI_OPT_NONATOMIC, SPI_processed, SPI_result, SPI_tuptable, TopMemoryContext, TopTransactionContext, _SPI_connection::tuptable, and _SPI_connection::tuptables.

Referenced by plperl_func_handler(), plperl_inline_handler(), plpgsql_call_handler(), plpgsql_inline_handler(), plpython3_call_handler(), plpython3_inline_handler(), pltcl_func_handler(), and SPI_connect().

◆ SPI_copytuple()

HeapTuple SPI_copytuple ( HeapTuple  tuple)

Definition at line 1047 of file spi.c.

1048 {
1049  MemoryContext oldcxt;
1050  HeapTuple ctuple;
1051 
1052  if (tuple == NULL)
1053  {
1055  return NULL;
1056  }
1057 
1058  if (_SPI_current == NULL)
1059  {
1061  return NULL;
1062  }
1063 
1065 
1066  ctuple = heap_copytuple(tuple);
1067 
1068  MemoryContextSwitchTo(oldcxt);
1069 
1070  return ctuple;
1071 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:776
#define SPI_ERROR_ARGUMENT
Definition: spi.h:73

References _SPI_current, heap_copytuple(), MemoryContextSwitchTo(), _SPI_connection::savedcxt, SPI_ERROR_ARGUMENT, SPI_ERROR_UNCONNECTED, and SPI_result.

Referenced by get_tuple_of_interest(), and plpgsql_exec_trigger().

◆ SPI_cursor_close()

void SPI_cursor_close ( Portal  portal)

Definition at line 1862 of file spi.c.

1863 {
1864  if (!PortalIsValid(portal))
1865  elog(ERROR, "invalid portal in SPI cursor operation");
1866 
1867  PortalDrop(portal, false);
1868 }
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:468

References elog, ERROR, PortalDrop(), and PortalIsValid.

Referenced by exec_stmt_close(), exec_stmt_dynfors(), exec_stmt_forc(), exec_stmt_fors(), plperl_spi_cursor_close(), plperl_spi_fetchrow(), PLy_cursor_close(), PLy_cursor_dealloc(), query_to_xml_and_xmlschema(), query_to_xmlschema(), ts_stat_sql(), and tsquery_rewrite_query().

◆ SPI_cursor_fetch()

void SPI_cursor_fetch ( Portal  portal,
bool  forward,
long  count 
)

Definition at line 1806 of file spi.c.

1807 {
1808  _SPI_cursor_operation(portal,
1809  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1811  /* we know that the DestSPI receiver doesn't need a destroy call */
1812 }
@ FETCH_FORWARD
Definition: parsenodes.h:3345
@ FETCH_BACKWARD
Definition: parsenodes.h:3346
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:3007

References _SPI_cursor_operation(), CreateDestReceiver(), DestSPI, FETCH_BACKWARD, and FETCH_FORWARD.

Referenced by cursor_to_xml(), exec_for_query(), plperl_spi_fetchrow(), PLy_cursor_fetch(), PLy_cursor_iternext(), ts_stat_sql(), and tsquery_rewrite_query().

◆ SPI_cursor_find()

Portal SPI_cursor_find ( const char *  name)

Definition at line 1794 of file spi.c.

1795 {
1796  return GetPortalByName(name);
1797 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130

References GetPortalByName(), and name.

Referenced by cursor_to_xml(), cursor_to_xmlschema(), exec_stmt_close(), exec_stmt_fetch(), exec_stmt_forc(), exec_stmt_open(), plperl_spi_cursor_close(), and plperl_spi_fetchrow().

◆ SPI_cursor_move()

void SPI_cursor_move ( Portal  portal,
bool  forward,
long  count 
)

Definition at line 1821 of file spi.c.

1822 {
1823  _SPI_cursor_operation(portal,
1824  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1825  None_Receiver);
1826 }
DestReceiver * None_Receiver
Definition: dest.c:96

References _SPI_cursor_operation(), FETCH_BACKWARD, FETCH_FORWARD, and None_Receiver.

◆ SPI_cursor_open()

Portal SPI_cursor_open ( const char *  name,
SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
bool  read_only 
)

Definition at line 1445 of file spi.c.

1448 {
1449  Portal portal;
1450  ParamListInfo paramLI;
1451 
1452  /* build transient ParamListInfo in caller's context */
1453  paramLI = _SPI_convert_params(plan->nargs, plan->argtypes,
1454  Values, Nulls);
1455 
1456  portal = SPI_cursor_open_internal(name, plan, paramLI, read_only);
1457 
1458  /* done with the transient ParamListInfo */
1459  if (paramLI)
1460  pfree(paramLI);
1461 
1462  return portal;
1463 }
void pfree(void *pointer)
Definition: mcxt.c:1521
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2849
static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
Definition: spi.c:1577

References _SPI_convert_params(), name, Nulls, pfree(), plan, and SPI_cursor_open_internal().

Referenced by plperl_spi_query(), plperl_spi_query_prepared(), PLy_cursor_plan(), PLy_cursor_query(), query_to_xml_and_xmlschema(), query_to_xmlschema(), ts_stat_sql(), and tsquery_rewrite_query().

◆ SPI_cursor_open_internal()

static Portal SPI_cursor_open_internal ( const char *  name,
SPIPlanPtr  plan,
ParamListInfo  paramLI,
bool  read_only 
)
static

Definition at line 1577 of file spi.c.

1579 {
1580  CachedPlanSource *plansource;
1581  CachedPlan *cplan;
1582  List *stmt_list;
1583  char *query_string;
1584  Snapshot snapshot;
1585  MemoryContext oldcontext;
1586  Portal portal;
1587  SPICallbackArg spicallbackarg;
1588  ErrorContextCallback spierrcontext;
1589 
1590  /*
1591  * Check that the plan is something the Portal code will special-case as
1592  * returning one tupleset.
1593  */
1594  if (!SPI_is_cursor_plan(plan))
1595  {
1596  /* try to give a good error message */
1597  const char *cmdtag;
1598 
1599  if (list_length(plan->plancache_list) != 1)
1600  ereport(ERROR,
1601  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1602  errmsg("cannot open multi-query plan as cursor")));
1603  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1604  /* A SELECT that fails SPI_is_cursor_plan() must be SELECT INTO */
1605  if (plansource->commandTag == CMDTAG_SELECT)
1606  cmdtag = "SELECT INTO";
1607  else
1608  cmdtag = GetCommandTagName(plansource->commandTag);
1609  ereport(ERROR,
1610  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1611  /* translator: %s is name of a SQL command, eg INSERT */
1612  errmsg("cannot open %s query as cursor", cmdtag)));
1613  }
1614 
1615  Assert(list_length(plan->plancache_list) == 1);
1616  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1617 
1618  /* Push the SPI stack */
1619  if (_SPI_begin_call(true) < 0)
1620  elog(ERROR, "SPI_cursor_open called while not connected");
1621 
1622  /* Reset SPI result (note we deliberately don't touch lastoid) */
1623  SPI_processed = 0;
1624  SPI_tuptable = NULL;
1625  _SPI_current->processed = 0;
1626  _SPI_current->tuptable = NULL;
1627 
1628  /* Create the portal */
1629  if (name == NULL || name[0] == '\0')
1630  {
1631  /* Use a random nonconflicting name */
1632  portal = CreateNewPortal();
1633  }
1634  else
1635  {
1636  /* In this path, error if portal of same name already exists */
1637  portal = CreatePortal(name, false, false);
1638  }
1639 
1640  /* Copy the plan's query string into the portal */
1641  query_string = MemoryContextStrdup(portal->portalContext,
1642  plansource->query_string);
1643 
1644  /*
1645  * Setup error traceback support for ereport(), in case GetCachedPlan
1646  * throws an error.
1647  */
1648  spicallbackarg.query = plansource->query_string;
1649  spicallbackarg.mode = plan->parse_mode;
1650  spierrcontext.callback = _SPI_error_callback;
1651  spierrcontext.arg = &spicallbackarg;
1652  spierrcontext.previous = error_context_stack;
1653  error_context_stack = &spierrcontext;
1654 
1655  /*
1656  * Note: for a saved plan, we mustn't have any failure occur between
1657  * GetCachedPlan and PortalDefineQuery; that would result in leaking our
1658  * plancache refcount.
1659  */
1660 
1661  /* Replan if needed, and increment plan refcount for portal */
1662  cplan = GetCachedPlan(plansource, paramLI, NULL, _SPI_current->queryEnv);
1663  stmt_list = cplan->stmt_list;
1664 
1665  if (!plan->saved)
1666  {
1667  /*
1668  * We don't want the portal to depend on an unsaved CachedPlanSource,
1669  * so must copy the plan into the portal's context. An error here
1670  * will result in leaking our refcount on the plan, but it doesn't
1671  * matter because the plan is unsaved and hence transient anyway.
1672  */
1673  oldcontext = MemoryContextSwitchTo(portal->portalContext);
1674  stmt_list = copyObject(stmt_list);
1675  MemoryContextSwitchTo(oldcontext);
1676  ReleaseCachedPlan(cplan, NULL);
1677  cplan = NULL; /* portal shouldn't depend on cplan */
1678  }
1679 
1680  /*
1681  * Set up the portal.
1682  */
1683  PortalDefineQuery(portal,
1684  NULL, /* no statement name */
1685  query_string,
1686  plansource->commandTag,
1687  stmt_list,
1688  cplan);
1689 
1690  /*
1691  * Set up options for portal. Default SCROLL type is chosen the same way
1692  * as PerformCursorOpen does it.
1693  */
1694  portal->cursorOptions = plan->cursor_options;
1696  {
1697  if (list_length(stmt_list) == 1 &&
1698  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1699  linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
1700  ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
1701  portal->cursorOptions |= CURSOR_OPT_SCROLL;
1702  else
1704  }
1705 
1706  /*
1707  * Disallow SCROLL with SELECT FOR UPDATE. This is not redundant with the
1708  * check in transformDeclareCursorStmt because the cursor options might
1709  * not have come through there.
1710  */
1711  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
1712  {
1713  if (list_length(stmt_list) == 1 &&
1714  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1715  linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
1716  ereport(ERROR,
1717  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1718  errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1719  errdetail("Scrollable cursors must be READ ONLY.")));
1720  }
1721 
1722  /* Make current query environment available to portal at execution time. */
1723  portal->queryEnv = _SPI_current->queryEnv;
1724 
1725  /*
1726  * If told to be read-only, we'd better check for read-only queries. This
1727  * can't be done earlier because we need to look at the finished, planned
1728  * queries. (In particular, we don't want to do it between GetCachedPlan
1729  * and PortalDefineQuery, because throwing an error between those steps
1730  * would result in leaking our plancache refcount.)
1731  */
1732  if (read_only)
1733  {
1734  ListCell *lc;
1735 
1736  foreach(lc, stmt_list)
1737  {
1738  PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
1739 
1740  if (!CommandIsReadOnly(pstmt))
1741  ereport(ERROR,
1742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1743  /* translator: %s is a SQL statement name */
1744  errmsg("%s is not allowed in a non-volatile function",
1745  CreateCommandName((Node *) pstmt))));
1746  }
1747  }
1748 
1749  /* Set up the snapshot to use. */
1750  if (read_only)
1751  snapshot = GetActiveSnapshot();
1752  else
1753  {
1755  snapshot = GetTransactionSnapshot();
1756  }
1757 
1758  /*
1759  * If the plan has parameters, copy them into the portal. Note that this
1760  * must be done after revalidating the plan, because in dynamic parameter
1761  * cases the set of parameters could have changed during re-parsing.
1762  */
1763  if (paramLI)
1764  {
1765  oldcontext = MemoryContextSwitchTo(portal->portalContext);
1766  paramLI = copyParamList(paramLI);
1767  MemoryContextSwitchTo(oldcontext);
1768  }
1769 
1770  /*
1771  * Start portal execution.
1772  */
1773  PortalStart(portal, paramLI, 0, snapshot);
1774 
1775  Assert(portal->strategy != PORTAL_MULTI_QUERY);
1776 
1777  /* Pop the error context stack */
1778  error_context_stack = spierrcontext.previous;
1779 
1780  /* Pop the SPI stack */
1781  _SPI_end_call(true);
1782 
1783  /* Return the created portal */
1784  return portal;
1785 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:510
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1683
#define copyObject(obj)
Definition: nodes.h:224
@ CMD_UTILITY
Definition: nodes.h:270
ParamListInfo copyParamList(ParamListInfo from)
Definition: params.c:78
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:3308
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:3309
#define linitial(l)
Definition: pg_list.h:178
@ PORTAL_MULTI_QUERY
Definition: portal.h:95
Portal CreateNewPortal(void)
Definition: portalmem.c:235
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:282
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:433
bool SPI_is_cursor_plan(SPIPlanPtr plan)
Definition: spi.c:1910
QueryEnvironment * queryEnv
Definition: portal.h:143
MemoryContext portalContext
Definition: portal.h:120
int cursorOptions
Definition: portal.h:147
PortalStrategy strategy
Definition: portal.h:146

References _SPI_begin_call(), _SPI_current, _SPI_end_call(), _SPI_error_callback(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CMD_UTILITY, CommandCounterIncrement(), CommandIsReadOnly(), CachedPlanSource::commandTag, copyObject, copyParamList(), CreateCommandName(), CreateNewPortal(), CreatePortal(), CURSOR_OPT_NO_SCROLL, CURSOR_OPT_SCROLL, PortalData::cursorOptions, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, error_context_stack, ExecSupportsBackwardScan(), GetActiveSnapshot(), GetCachedPlan(), GetCommandTagName(), GetTransactionSnapshot(), lfirst_node, linitial, linitial_node, list_length(), MemoryContextStrdup(), MemoryContextSwitchTo(), SPICallbackArg::mode, name, NIL, plan, PORTAL_MULTI_QUERY, PortalData::portalContext, PortalDefineQuery(), PortalStart(), ErrorContextCallback::previous, _SPI_connection::processed, SPICallbackArg::query, CachedPlanSource::query_string, _SPI_connection::queryEnv, PortalData::queryEnv, ReleaseCachedPlan(), SPI_is_cursor_plan(), SPI_processed, SPI_tuptable, CachedPlan::stmt_list, PortalData::strategy, and _SPI_connection::tuptable.

Referenced by SPI_cursor_open(), SPI_cursor_open_with_args(), SPI_cursor_open_with_paramlist(), and SPI_cursor_parse_open().

◆ SPI_cursor_open_with_args()

Portal SPI_cursor_open_with_args ( const char *  name,
const char *  src,
int  nargs,
Oid argtypes,
Datum Values,
const char *  Nulls,
bool  read_only,
int  cursorOptions 
)

Definition at line 1472 of file spi.c.

1477 {
1478  Portal result;
1479  _SPI_plan plan;
1480  ParamListInfo paramLI;
1481 
1482  if (src == NULL || nargs < 0)
1483  elog(ERROR, "SPI_cursor_open_with_args called with invalid arguments");
1484 
1485  if (nargs > 0 && (argtypes == NULL || Values == NULL))
1486  elog(ERROR, "SPI_cursor_open_with_args called with missing parameters");
1487 
1488  SPI_result = _SPI_begin_call(true);
1489  if (SPI_result < 0)
1490  elog(ERROR, "SPI_cursor_open_with_args called while not connected");
1491 
1492  memset(&plan, 0, sizeof(_SPI_plan));
1493  plan.magic = _SPI_PLAN_MAGIC;
1494  plan.parse_mode = RAW_PARSE_DEFAULT;
1495  plan.cursor_options = cursorOptions;
1496  plan.nargs = nargs;
1497  plan.argtypes = argtypes;
1498  plan.parserSetup = NULL;
1499  plan.parserSetupArg = NULL;
1500 
1501  /* build transient ParamListInfo in executor context */
1502  paramLI = _SPI_convert_params(nargs, argtypes,
1503  Values, Nulls);
1504 
1505  _SPI_prepare_plan(src, &plan);
1506 
1507  /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1508 
1509  result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
1510 
1511  /* And clean up */
1512  _SPI_end_call(true);
1513 
1514  return result;
1515 }
@ RAW_PARSE_DEFAULT
Definition: parser.h:39
static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:2221

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), elog, ERROR, name, Nulls, plan, RAW_PARSE_DEFAULT, SPI_cursor_open_internal(), and SPI_result.

◆ SPI_cursor_open_with_paramlist()

Portal SPI_cursor_open_with_paramlist ( const char *  name,
SPIPlanPtr  plan,
ParamListInfo  params,
bool  read_only 
)

Definition at line 1525 of file spi.c.

1527 {
1528  return SPI_cursor_open_internal(name, plan, params, read_only);
1529 }

References name, plan, and SPI_cursor_open_internal().

Referenced by exec_run_select(), exec_stmt_forc(), and exec_stmt_open().

◆ SPI_cursor_parse_open()

Portal SPI_cursor_parse_open ( const char *  name,
const char *  src,
const SPIParseOpenOptions options 
)

Definition at line 1533 of file spi.c.

1536 {
1537  Portal result;
1538  _SPI_plan plan;
1539 
1540  if (src == NULL || options == NULL)
1541  elog(ERROR, "SPI_cursor_parse_open called with invalid arguments");
1542 
1543  SPI_result = _SPI_begin_call(true);
1544  if (SPI_result < 0)
1545  elog(ERROR, "SPI_cursor_parse_open called while not connected");
1546 
1547  memset(&plan, 0, sizeof(_SPI_plan));
1548  plan.magic = _SPI_PLAN_MAGIC;
1549  plan.parse_mode = RAW_PARSE_DEFAULT;
1550  plan.cursor_options = options->cursorOptions;
1551  if (options->params)
1552  {
1553  plan.parserSetup = options->params->parserSetup;
1554  plan.parserSetupArg = options->params->parserSetupArg;
1555  }
1556 
1557  _SPI_prepare_plan(src, &plan);
1558 
1559  /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1560 
1561  result = SPI_cursor_open_internal(name, &plan,
1562  options->params, options->read_only);
1563 
1564  /* And clean up */
1565  _SPI_end_call(true);
1566 
1567  return result;
1568 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), elog, ERROR, name, plan, RAW_PARSE_DEFAULT, SPI_cursor_open_internal(), and SPI_result.

Referenced by exec_dynquery_with_params().

◆ SPI_datumTransfer()

Datum SPI_datumTransfer ( Datum  value,
bool  typByVal,
int  typLen 
)

Definition at line 1361 of file spi.c.

1362 {
1363  MemoryContext oldcxt;
1364  Datum result;
1365 
1366  if (_SPI_current == NULL)
1367  elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
1368 
1370 
1371  result = datumTransfer(value, typByVal, typLen);
1372 
1373  MemoryContextSwitchTo(oldcxt);
1374 
1375  return result;
1376 }
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:194
static struct @160 value
uintptr_t Datum
Definition: postgres.h:64

References _SPI_current, datumTransfer(), elog, ERROR, MemoryContextSwitchTo(), _SPI_connection::savedcxt, and value.

Referenced by coerce_function_result_tuple(), and plpgsql_exec_function().

◆ spi_dest_startup()

void spi_dest_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)

Definition at line 2123 of file spi.c.

2124 {
2125  SPITupleTable *tuptable;
2126  MemoryContext oldcxt;
2127  MemoryContext tuptabcxt;
2128 
2129  if (_SPI_current == NULL)
2130  elog(ERROR, "spi_dest_startup called while not connected to SPI");
2131 
2132  if (_SPI_current->tuptable != NULL)
2133  elog(ERROR, "improper call to spi_dest_startup");
2134 
2135  /* We create the tuple table context as a child of procCxt */
2136 
2137  oldcxt = _SPI_procmem(); /* switch to procedure memory context */
2138 
2140  "SPI TupTable",
2142  MemoryContextSwitchTo(tuptabcxt);
2143 
2144  _SPI_current->tuptable = tuptable = (SPITupleTable *)
2145  palloc0(sizeof(SPITupleTable));
2146  tuptable->tuptabcxt = tuptabcxt;
2147  tuptable->subid = GetCurrentSubTransactionId();
2148 
2149  /*
2150  * The tuptable is now valid enough to be freed by AtEOSubXact_SPI, so put
2151  * it onto the SPI context's tuptables list. This will ensure it's not
2152  * leaked even in the unlikely event the following few lines fail.
2153  */
2154  slist_push_head(&_SPI_current->tuptables, &tuptable->next);
2155 
2156  /* set up initial allocations */
2157  tuptable->alloced = 128;
2158  tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
2159  tuptable->numvals = 0;
2160  tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
2161 
2162  MemoryContextSwitchTo(oldcxt);
2163 }
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:1006
uint64 alloced
Definition: spi.h:30
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
slist_node next
Definition: spi.h:32
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133

References _SPI_current, _SPI_procmem(), SPITupleTable::alloced, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CreateTupleDescCopy(), CurrentMemoryContext, elog, ERROR, GetCurrentSubTransactionId(), MemoryContextSwitchTo(), SPITupleTable::next, SPITupleTable::numvals, palloc(), palloc0(), slist_push_head(), SPITupleTable::subid, SPITupleTable::tupdesc, SPITupleTable::tuptabcxt, _SPI_connection::tuptable, _SPI_connection::tuptables, and SPITupleTable::vals.

◆ SPI_exec()

int SPI_exec ( const char *  src,
long  tcount 
)

Definition at line 630 of file spi.c.

631 {
632  return SPI_execute(src, false, tcount);
633 }
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:596

References SPI_execute().

Referenced by get_tuple_of_interest(), refresh_by_match_merge(), and xpath_table().

◆ SPI_execp()

int SPI_execp ( SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
long  tcount 
)

Definition at line 704 of file spi.c.

705 {
706  return SPI_execute_plan(plan, Values, Nulls, false, tcount);
707 }
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:672

References Nulls, plan, and SPI_execute_plan().

Referenced by check_foreign_key(), check_primary_key(), and ttdummy().

◆ SPI_execute()

int SPI_execute ( const char *  src,
bool  read_only,
long  tcount 
)

Definition at line 596 of file spi.c.

597 {
598  _SPI_plan plan;
600  int res;
601 
602  if (src == NULL || tcount < 0)
603  return SPI_ERROR_ARGUMENT;
604 
605  res = _SPI_begin_call(true);
606  if (res < 0)
607  return res;
608 
609  memset(&plan, 0, sizeof(_SPI_plan));
610  plan.magic = _SPI_PLAN_MAGIC;
611  plan.parse_mode = RAW_PARSE_DEFAULT;
612  plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
613 
615 
616  memset(&options, 0, sizeof(options));
617  options.read_only = read_only;
618  options.tcount = tcount;
619 
622  true);
623 
624  _SPI_end_call(true);
625  return res;
626 }
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3317
static char ** options
static int _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options, Snapshot snapshot, Snapshot crosscheck_snapshot, bool fire_triggers)
Definition: spi.c:2399
static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:2329

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_prepare_oneshot_plan(), CURSOR_OPT_PARALLEL_OK, InvalidSnapshot, options, plan, RAW_PARSE_DEFAULT, res, and SPI_ERROR_ARGUMENT.

Referenced by build_tuplestore_recursively(), crosstab(), get_crosstab_tuplestore(), initialize_worker_spi(), load_categories_hash(), plperl_spi_exec(), pltcl_SPI_execute(), PLy_spi_execute_query(), query_to_oid_list(), query_to_xml_internal(), refresh_by_match_merge(), SPI_exec(), and worker_spi_main().

◆ SPI_execute_extended()

int SPI_execute_extended ( const char *  src,
const SPIExecuteOptions options 
)

Definition at line 637 of file spi.c.

639 {
640  int res;
641  _SPI_plan plan;
642 
643  if (src == NULL || options == NULL)
644  return SPI_ERROR_ARGUMENT;
645 
646  res = _SPI_begin_call(true);
647  if (res < 0)
648  return res;
649 
650  memset(&plan, 0, sizeof(_SPI_plan));
651  plan.magic = _SPI_PLAN_MAGIC;
652  plan.parse_mode = RAW_PARSE_DEFAULT;
653  plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
654  if (options->params)
655  {
656  plan.parserSetup = options->params->parserSetup;
657  plan.parserSetupArg = options->params->parserSetupArg;
658  }
659 
661 
664  true);
665 
666  _SPI_end_call(true);
667  return res;
668 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_prepare_oneshot_plan(), CURSOR_OPT_PARALLEL_OK, InvalidSnapshot, plan, RAW_PARSE_DEFAULT, res, and SPI_ERROR_ARGUMENT.

Referenced by exec_stmt_dynexecute(), and exec_stmt_return_query().

◆ SPI_execute_plan()

int SPI_execute_plan ( SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
bool  read_only,
long  tcount 
)

Definition at line 672 of file spi.c.

674 {
676  int res;
677 
678  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
679  return SPI_ERROR_ARGUMENT;
680 
681  if (plan->nargs > 0 && Values == NULL)
682  return SPI_ERROR_PARAM;
683 
684  res = _SPI_begin_call(true);
685  if (res < 0)
686  return res;
687 
688  memset(&options, 0, sizeof(options));
689  options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
690  Values, Nulls);
691  options.read_only = read_only;
692  options.tcount = tcount;
693 
696  true);
697 
698  _SPI_end_call(true);
699  return res;
700 }
#define SPI_ERROR_PARAM
Definition: spi.h:74

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, InvalidSnapshot, Nulls, options, plan, res, SPI_ERROR_ARGUMENT, and SPI_ERROR_PARAM.

Referenced by pg_get_ruledef_worker(), pg_get_viewdef_worker(), plperl_spi_exec_prepared(), pltcl_SPI_execute_plan(), PLy_spi_execute_plan(), SPI_execp(), and test_predtest().

◆ SPI_execute_plan_extended()

int SPI_execute_plan_extended ( SPIPlanPtr  plan,
const SPIExecuteOptions options 
)

Definition at line 711 of file spi.c.

713 {
714  int res;
715 
716  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || options == NULL)
717  return SPI_ERROR_ARGUMENT;
718 
719  res = _SPI_begin_call(true);
720  if (res < 0)
721  return res;
722 
725  true);
726 
727  _SPI_end_call(true);
728  return res;
729 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, InvalidSnapshot, plan, res, and SPI_ERROR_ARGUMENT.

Referenced by exec_stmt_call(), and exec_stmt_return_query().

◆ SPI_execute_plan_with_paramlist()

int SPI_execute_plan_with_paramlist ( SPIPlanPtr  plan,
ParamListInfo  params,
bool  read_only,
long  tcount 
)

Definition at line 733 of file spi.c.

735 {
737  int res;
738 
739  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
740  return SPI_ERROR_ARGUMENT;
741 
742  res = _SPI_begin_call(true);
743  if (res < 0)
744  return res;
745 
746  memset(&options, 0, sizeof(options));
747  options.params = params;
748  options.read_only = read_only;
749  options.tcount = tcount;
750 
753  true);
754 
755  _SPI_end_call(true);
756  return res;
757 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, InvalidSnapshot, options, plan, res, and SPI_ERROR_ARGUMENT.

Referenced by exec_run_select(), and exec_stmt_execsql().

◆ SPI_execute_snapshot()

int SPI_execute_snapshot ( SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
Snapshot  snapshot,
Snapshot  crosscheck_snapshot,
bool  read_only,
bool  fire_triggers,
long  tcount 
)

Definition at line 773 of file spi.c.

777 {
779  int res;
780 
781  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
782  return SPI_ERROR_ARGUMENT;
783 
784  if (plan->nargs > 0 && Values == NULL)
785  return SPI_ERROR_PARAM;
786 
787  res = _SPI_begin_call(true);
788  if (res < 0)
789  return res;
790 
791  memset(&options, 0, sizeof(options));
792  options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
793  Values, Nulls);
794  options.read_only = read_only;
795  options.tcount = tcount;
796 
798  snapshot, crosscheck_snapshot,
799  fire_triggers);
800 
801  _SPI_end_call(true);
802  return res;
803 }

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, Nulls, options, plan, res, SPI_ERROR_ARGUMENT, and SPI_ERROR_PARAM.

Referenced by RI_Initial_Check(), RI_PartitionRemove_Check(), and ri_PerformCheck().

◆ SPI_execute_with_args()

int SPI_execute_with_args ( const char *  src,
int  nargs,
Oid argtypes,
Datum Values,
const char *  Nulls,
bool  read_only,
long  tcount 
)

Definition at line 812 of file spi.c.

816 {
817  int res;
818  _SPI_plan plan;
819  ParamListInfo paramLI;
821 
822  if (src == NULL || nargs < 0 || tcount < 0)
823  return SPI_ERROR_ARGUMENT;
824 
825  if (nargs > 0 && (argtypes == NULL || Values == NULL))
826  return SPI_ERROR_PARAM;
827 
828  res = _SPI_begin_call(true);
829  if (res < 0)
830  return res;
831 
832  memset(&plan, 0, sizeof(_SPI_plan));
833  plan.magic = _SPI_PLAN_MAGIC;
834  plan.parse_mode = RAW_PARSE_DEFAULT;
835  plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
836  plan.nargs = nargs;
837  plan.argtypes = argtypes;
838  plan.parserSetup = NULL;
839  plan.parserSetupArg = NULL;
840 
841  paramLI = _SPI_convert_params(nargs, argtypes,
842  Values, Nulls);
843 
845 
846  memset(&options, 0, sizeof(options));
847  options.params = paramLI;
848  options.read_only = read_only;
849  options.tcount = tcount;
850 
853  true);
854 
855  _SPI_end_call(true);
856  return res;
857 }

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_prepare_oneshot_plan(), CURSOR_OPT_PARALLEL_OK, InvalidSnapshot, Nulls, options, plan, RAW_PARSE_DEFAULT, res, SPI_ERROR_ARGUMENT, and SPI_ERROR_PARAM.

◆ SPI_finish()

int SPI_finish ( void  )

Definition at line 182 of file spi.c.

183 {
184  int res;
185 
186  res = _SPI_begin_call(false); /* just check we're connected */
187  if (res < 0)
188  return res;
189 
190  /* Restore memory context as it was before procedure call */
192 
193  /* Release memory used in procedure call (including tuptables) */
195  _SPI_current->execCxt = NULL;
197  _SPI_current->procCxt = NULL;
198 
199  /*
200  * Restore outer API variables, especially SPI_tuptable which is probably
201  * pointing at a just-deleted tuptable
202  */
206 
207  /* Exit stack level */
208  _SPI_connected--;
209  if (_SPI_connected < 0)
210  _SPI_current = NULL;
211  else
213 
214  return SPI_OK_FINISH;
215 }
#define SPI_OK_FINISH
Definition: spi.h:83

References _SPI_begin_call(), _SPI_connected, _SPI_current, _SPI_stack, _SPI_connection::execCxt, MemoryContextDelete(), MemoryContextSwitchTo(), _SPI_connection::outer_processed, _SPI_connection::outer_result, _SPI_connection::outer_tuptable, _SPI_connection::procCxt, res, _SPI_connection::savedcxt, SPI_OK_FINISH, SPI_processed, SPI_result, and SPI_tuptable.

Referenced by check_foreign_key(), check_primary_key(), connectby(), crosstab(), cursor_to_xml(), cursor_to_xmlschema(), database_to_xml_internal(), database_to_xmlschema_internal(), get_crosstab_tuplestore(), get_tuple_of_interest(), initialize_worker_spi(), load_categories_hash(), pg_get_ruledef_worker(), pg_get_viewdef_worker(), plperl_event_trigger_handler(), plperl_func_handler(), plperl_inline_handler(), plperl_trigger_handler(), plpgsql_call_handler(), plpgsql_inline_handler(), plpgsql_validator(), plsample_trigger_handler(), pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_trigger_handler(), PLy_exec_function(), PLy_exec_trigger(), query_to_xml_and_xmlschema(), query_to_xml_internal(), query_to_xmlschema(), refresh_by_match_merge(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), ri_set(), schema_to_xml_internal(), schema_to_xmlschema_internal(), test_predtest(), ts_stat1(), ts_stat2(), tsquery_rewrite_query(), ttdummy(), worker_spi_main(), and xpath_table().

◆ SPI_fname()

char* SPI_fname ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 1198 of file spi.c.

1199 {
1200  const FormData_pg_attribute *att;
1201 
1202  SPI_result = 0;
1203 
1204  if (fnumber > tupdesc->natts || fnumber == 0 ||
1206  {
1208  return NULL;
1209  }
1210 
1211  if (fnumber > 0)
1212  att = TupleDescAttr(tupdesc, fnumber - 1);
1213  else
1214  att = SystemAttributeDefinition(fnumber);
1215 
1216  return pstrdup(NameStr(att->attname));
1217 }
#define NameStr(name)
Definition: c.h:751
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:240
char * pstrdup(const char *in)
Definition: mcxt.c:1696
FormData_pg_attribute
Definition: pg_attribute.h:193
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:76
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References FirstLowInvalidHeapAttributeNumber, FormData_pg_attribute, NameStr, TupleDescData::natts, pstrdup(), SPI_ERROR_NOATTRIBUTE, SPI_result, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by get_pkey_attnames(), and SPI_sql_row_to_xmlelement().

◆ SPI_fnumber()

int SPI_fnumber ( TupleDesc  tupdesc,
const char *  fname 
)

Definition at line 1175 of file spi.c.

1176 {
1177  int res;
1178  const FormData_pg_attribute *sysatt;
1179 
1180  for (res = 0; res < tupdesc->natts; res++)
1181  {
1182  Form_pg_attribute attr = TupleDescAttr(tupdesc, res);
1183 
1184  if (namestrcmp(&attr->attname, fname) == 0 &&
1185  !attr->attisdropped)
1186  return res + 1;
1187  }
1188 
1189  sysatt = SystemAttributeByName(fname);
1190  if (sysatt != NULL)
1191  return sysatt->attnum;
1192 
1193  /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
1194  return SPI_ERROR_NOATTRIBUTE;
1195 }
const FormData_pg_attribute * SystemAttributeByName(const char *attname)
Definition: heap.c:252
int namestrcmp(Name name, const char *str)
Definition: name.c:247
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209

References FormData_pg_attribute, namestrcmp(), TupleDescData::natts, res, SPI_ERROR_NOATTRIBUTE, SystemAttributeByName(), and TupleDescAttr.

Referenced by autoinc(), check_foreign_key(), check_primary_key(), insert_username(), lo_manage(), make_ruledef(), make_viewdef(), moddatetime(), plperl_build_tuple_result(), plperl_modify_tuple(), pltcl_build_tuple_result(), PLy_modify_tuple(), tsvector_update_trigger(), and ttdummy().

◆ SPI_freeplan()

int SPI_freeplan ( SPIPlanPtr  plan)

Definition at line 1025 of file spi.c.

1026 {
1027  ListCell *lc;
1028 
1029  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1030  return SPI_ERROR_ARGUMENT;
1031 
1032  /* Release the plancache entries */
1033  foreach(lc, plan->plancache_list)
1034  {
1035  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1036 
1037  DropCachedPlan(plansource);
1038  }
1039 
1040  /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
1041  MemoryContextDelete(plan->plancxt);
1042 
1043  return 0;
1044 }
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:526

References _SPI_PLAN_MAGIC, DropCachedPlan(), lfirst, MemoryContextDelete(), plan, and SPI_ERROR_ARGUMENT.

Referenced by free_expr(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query(), PLy_cursor_query(), PLy_plan_dealloc(), ri_FetchPreparedPlan(), ts_stat_sql(), and tsquery_rewrite_query().

◆ SPI_freetuple()

void SPI_freetuple ( HeapTuple  tuple)

Definition at line 1379 of file spi.c.

1380 {
1381  /* No longer need to worry which context tuple was in... */
1382  heap_freetuple(tuple);
1383 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434

References heap_freetuple().

◆ SPI_freetuptable()

void SPI_freetuptable ( SPITupleTable tuptable)

Definition at line 1386 of file spi.c.

1387 {
1388  bool found = false;
1389 
1390  /* ignore call if NULL pointer */
1391  if (tuptable == NULL)
1392  return;
1393 
1394  /*
1395  * Search only the topmost SPI context for a matching tuple table.
1396  */
1397  if (_SPI_current != NULL)
1398  {
1399  slist_mutable_iter siter;
1400 
1401  /* find tuptable in active list, then remove it */
1403  {
1404  SPITupleTable *tt;
1405 
1406  tt = slist_container(SPITupleTable, next, siter.cur);
1407  if (tt == tuptable)
1408  {
1409  slist_delete_current(&siter);
1410  found = true;
1411  break;
1412  }
1413  }
1414  }
1415 
1416  /*
1417  * Refuse the deletion if we didn't find it in the topmost SPI context.
1418  * This is primarily a guard against double deletion, but might prevent
1419  * other errors as well. Since the worst consequence of not deleting a
1420  * tuptable would be a transient memory leak, this is just a WARNING.
1421  */
1422  if (!found)
1423  {
1424  elog(WARNING, "attempt to delete invalid SPITupleTable %p", tuptable);
1425  return;
1426  }
1427 
1428  /* for safety, reset global variables that might point at tuptable */
1429  if (tuptable == _SPI_current->tuptable)
1430  _SPI_current->tuptable = NULL;
1431  if (tuptable == SPI_tuptable)
1432  SPI_tuptable = NULL;
1433 
1434  /* release all memory belonging to tuptable */
1435  MemoryContextDelete(tuptable->tuptabcxt);
1436 }

References _SPI_current, slist_mutable_iter::cur, elog, MemoryContextDelete(), next, slist_container, slist_delete_current(), slist_foreach_modify, SPI_tuptable, SPITupleTable::tuptabcxt, _SPI_connection::tuptable, _SPI_connection::tuptables, and WARNING.

Referenced by _SPI_execute_plan(), exec_eval_cleanup(), exec_for_query(), exec_stmt_call(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_fetch(), plperl_spi_execute_fetch_result(), plperl_spi_fetchrow(), pltcl_process_SPI_result(), PLy_cursor_fetch(), PLy_cursor_iternext(), PLy_spi_execute_fetch_result(), ts_stat_sql(), and tsquery_rewrite_query().

◆ SPI_getargcount()

int SPI_getargcount ( SPIPlanPtr  plan)

Definition at line 1890 of file spi.c.

1891 {
1892  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1893  {
1895  return -1;
1896  }
1897  return plan->nargs;
1898 }

References _SPI_PLAN_MAGIC, plan, SPI_ERROR_ARGUMENT, and SPI_result.

◆ SPI_getargtypeid()

Oid SPI_getargtypeid ( SPIPlanPtr  plan,
int  argIndex 
)

Definition at line 1875 of file spi.c.

1876 {
1877  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
1878  argIndex < 0 || argIndex >= plan->nargs)
1879  {
1881  return InvalidOid;
1882  }
1883  return plan->argtypes[argIndex];
1884 }
#define InvalidOid
Definition: postgres_ext.h:36

References _SPI_PLAN_MAGIC, InvalidOid, plan, SPI_ERROR_ARGUMENT, and SPI_result.

◆ SPI_getbinval()

Datum SPI_getbinval ( HeapTuple  tuple,
TupleDesc  tupdesc,
int  fnumber,
bool isnull 
)

Definition at line 1252 of file spi.c.

1253 {
1254  SPI_result = 0;
1255 
1256  if (fnumber > tupdesc->natts || fnumber == 0 ||
1258  {
1260  *isnull = true;
1261  return (Datum) NULL;
1262  }
1263 
1264  return heap_getattr(tuple, fnumber, tupdesc, isnull);
1265 }
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792

References FirstLowInvalidHeapAttributeNumber, heap_getattr(), TupleDescData::natts, SPI_ERROR_NOATTRIBUTE, and SPI_result.

Referenced by autoinc(), check_foreign_key(), check_primary_key(), exec_eval_expr(), initialize_worker_spi(), make_ruledef(), make_viewdef(), query_to_oid_list(), SPI_sql_row_to_xmlelement(), test_predtest(), ts_stat_sql(), tsquery_rewrite_query(), tsvector_update_trigger(), ttdummy(), and worker_spi_main().

◆ SPI_getnspname()

char* SPI_getnspname ( Relation  rel)

Definition at line 1332 of file spi.c.

1333 {
1335 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
#define RelationGetNamespace(relation)
Definition: rel.h:546

References get_namespace_name(), and RelationGetNamespace.

Referenced by plperl_trigger_build_args(), plsample_trigger_handler(), pltcl_trigger_handler(), and PLy_trigger_build_args().

◆ SPI_getrelname()

char* SPI_getrelname ( Relation  rel)

◆ SPI_gettype()

char* SPI_gettype ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 1268 of file spi.c.

1269 {
1270  Oid typoid;
1271  HeapTuple typeTuple;
1272  char *result;
1273 
1274  SPI_result = 0;
1275 
1276  if (fnumber > tupdesc->natts || fnumber == 0 ||
1278  {
1280  return NULL;
1281  }
1282 
1283  if (fnumber > 0)
1284  typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1285  else
1286  typoid = (SystemAttributeDefinition(fnumber))->atttypid;
1287 
1288  typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
1289 
1290  if (!HeapTupleIsValid(typeTuple))
1291  {
1293  return NULL;
1294  }
1295 
1296  result = pstrdup(NameStr(((Form_pg_type) GETSTRUCT(typeTuple))->typname));
1297  ReleaseSysCache(typeTuple);
1298  return result;
1299 }
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
NameData typname
Definition: pg_type.h:41
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define SPI_ERROR_TYPUNKNOWN
Definition: spi.h:78
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

References FirstLowInvalidHeapAttributeNumber, GETSTRUCT, HeapTupleIsValid, NameStr, TupleDescData::natts, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), SearchSysCache1(), SPI_ERROR_NOATTRIBUTE, SPI_ERROR_TYPUNKNOWN, SPI_result, SystemAttributeDefinition(), TupleDescAttr, and typname.

Referenced by check_foreign_key().

◆ SPI_gettypeid()

Oid SPI_gettypeid ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 1308 of file spi.c.

1309 {
1310  SPI_result = 0;
1311 
1312  if (fnumber > tupdesc->natts || fnumber == 0 ||
1314  {
1316  return InvalidOid;
1317  }
1318 
1319  if (fnumber > 0)
1320  return TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1321  else
1322  return (SystemAttributeDefinition(fnumber))->atttypid;
1323 }

References FirstLowInvalidHeapAttributeNumber, InvalidOid, TupleDescData::natts, SPI_ERROR_NOATTRIBUTE, SPI_result, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by autoinc(), check_foreign_key(), check_primary_key(), insert_username(), moddatetime(), SPI_sql_row_to_xmlelement(), ts_stat_sql(), tsquery_rewrite_query(), tsvector_update_trigger(), and ttdummy().

◆ SPI_getvalue()

char* SPI_getvalue ( HeapTuple  tuple,
TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 1220 of file spi.c.

1221 {
1222  Datum val;
1223  bool isnull;
1224  Oid typoid,
1225  foutoid;
1226  bool typisvarlena;
1227 
1228  SPI_result = 0;
1229 
1230  if (fnumber > tupdesc->natts || fnumber == 0 ||
1232  {
1234  return NULL;
1235  }
1236 
1237  val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
1238  if (isnull)
1239  return NULL;
1240 
1241  if (fnumber > 0)
1242  typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1243  else
1244  typoid = (SystemAttributeDefinition(fnumber))->atttypid;
1245 
1246  getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
1247 
1248  return OidOutputFunctionCall(foutoid, val);
1249 }
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
long val
Definition: informix.c:689
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907

References FirstLowInvalidHeapAttributeNumber, getTypeOutputInfo(), heap_getattr(), TupleDescData::natts, OidOutputFunctionCall(), SPI_ERROR_NOATTRIBUTE, SPI_result, SystemAttributeDefinition(), TupleDescAttr, and val.

Referenced by build_tuplestore_recursively(), check_foreign_key(), crosstab(), get_crosstab_tuplestore(), get_sql_insert(), get_sql_update(), lo_manage(), load_categories_hash(), make_ruledef(), make_viewdef(), refresh_by_match_merge(), triggered_change_notification(), and xpath_table().

◆ SPI_inside_nonatomic_context()

bool SPI_inside_nonatomic_context ( void  )

Definition at line 581 of file spi.c.

582 {
583  if (_SPI_current == NULL)
584  return false; /* not in any SPI context at all */
585  /* these tests must match _SPI_commit's opinion of what's atomic: */
586  if (_SPI_current->atomic)
587  return false; /* it's atomic (ie function not procedure) */
588  if (IsSubTransaction())
589  return false; /* if within subtransaction, it's atomic */
590  return true;
591 }

References _SPI_current, _SPI_connection::atomic, and IsSubTransaction().

Referenced by StartTransaction().

◆ SPI_is_cursor_plan()

bool SPI_is_cursor_plan ( SPIPlanPtr  plan)

Definition at line 1910 of file spi.c.

1911 {
1912  CachedPlanSource *plansource;
1913 
1914  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1915  {
1917  return false;
1918  }
1919 
1920  if (list_length(plan->plancache_list) != 1)
1921  {
1922  SPI_result = 0;
1923  return false; /* not exactly 1 pre-rewrite command */
1924  }
1925  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1926 
1927  /*
1928  * We used to force revalidation of the cached plan here, but that seems
1929  * unnecessary: invalidation could mean a change in the rowtype of the
1930  * tuples returned by a plan, but not whether it returns tuples at all.
1931  */
1932  SPI_result = 0;
1933 
1934  /* Does it return tuples? */
1935  if (plansource->resultDesc)
1936  return true;
1937 
1938  return false;
1939 }

References _SPI_PLAN_MAGIC, linitial, list_length(), plan, CachedPlanSource::resultDesc, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by SPI_cursor_open_internal().

◆ SPI_keepplan()

int SPI_keepplan ( SPIPlanPtr  plan)

Definition at line 976 of file spi.c.

977 {
978  ListCell *lc;
979 
980  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
981  plan->saved || plan->oneshot)
982  return SPI_ERROR_ARGUMENT;
983 
984  /*
985  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
986  * component CachedPlanSources as saved. This sequence cannot fail
987  * partway through, so there's no risk of long-term memory leakage.
988  */
989  plan->saved = true;
991 
992  foreach(lc, plan->plancache_list)
993  {
994  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
995 
996  SaveCachedPlan(plansource);
997  }
998 
999  return 0;
1000 }

References _SPI_PLAN_MAGIC, CacheMemoryContext, lfirst, MemoryContextSetParent(), plan, SaveCachedPlan(), and SPI_ERROR_ARGUMENT.

Referenced by check_foreign_key(), check_primary_key(), exec_prepare_plan(), pg_get_ruledef_worker(), pg_get_viewdef_worker(), plperl_spi_prepare(), pltcl_SPI_prepare(), PLy_spi_prepare(), ri_PlanCheck(), and ttdummy().

◆ SPI_modifytuple()

HeapTuple SPI_modifytuple ( Relation  rel,
HeapTuple  tuple,
int  natts,
int *  attnum,
Datum Values,
const char *  Nulls 
)

Definition at line 1106 of file spi.c.

1108 {
1109  MemoryContext oldcxt;
1110  HeapTuple mtuple;
1111  int numberOfAttributes;
1112  Datum *v;
1113  bool *n;
1114  int i;
1115 
1116  if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
1117  {
1119  return NULL;
1120  }
1121 
1122  if (_SPI_current == NULL)
1123  {
1125  return NULL;
1126  }
1127 
1129 
1130  SPI_result = 0;
1131 
1132  numberOfAttributes = rel->rd_att->natts;
1133  v = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
1134  n = (bool *) palloc(numberOfAttributes * sizeof(bool));
1135 
1136  /* fetch old values and nulls */
1137  heap_deform_tuple(tuple, rel->rd_att, v, n);
1138 
1139  /* replace values and nulls */
1140  for (i = 0; i < natts; i++)
1141  {
1142  if (attnum[i] <= 0 || attnum[i] > numberOfAttributes)
1143  break;
1144  v[attnum[i] - 1] = Values[i];
1145  n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n');
1146  }
1147 
1148  if (i == natts) /* no errors in *attnum */
1149  {
1150  mtuple = heap_form_tuple(rel->rd_att, v, n);
1151 
1152  /*
1153  * copy the identification info of the old tuple: t_ctid, t_self, and
1154  * OID (if any)
1155  */
1156  mtuple->t_data->t_ctid = tuple->t_data->t_ctid;
1157  mtuple->t_self = tuple->t_self;
1158  mtuple->t_tableOid = tuple->t_tableOid;
1159  }
1160  else
1161  {
1162  mtuple = NULL;
1164  }
1165 
1166  pfree(v);
1167  pfree(n);
1168 
1169  MemoryContextSwitchTo(oldcxt);
1170 
1171  return mtuple;
1172 }
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1345
int16 attnum
Definition: pg_attribute.h:74
ItemPointerData t_self
Definition: htup.h:65
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
ItemPointerData t_ctid
Definition: htup_details.h:161
TupleDesc rd_att
Definition: rel.h:112

References _SPI_current, attnum, heap_deform_tuple(), heap_form_tuple(), i, MemoryContextSwitchTo(), TupleDescData::natts, Nulls, palloc(), pfree(), RelationData::rd_att, _SPI_connection::savedcxt, SPI_ERROR_ARGUMENT, SPI_ERROR_NOATTRIBUTE, SPI_ERROR_UNCONNECTED, SPI_result, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by ttdummy().

◆ SPI_palloc()

void* SPI_palloc ( Size  size)

Definition at line 1338 of file spi.c.

1339 {
1340  if (_SPI_current == NULL)
1341  elog(ERROR, "SPI_palloc called while not connected to SPI");
1342 
1344 }
static pg_noinline void Size size
Definition: slab.c:607

References _SPI_current, elog, ERROR, MemoryContextAlloc(), _SPI_connection::savedcxt, and size.

Referenced by _SPI_strdup(), and coerce_function_result_tuple().

◆ SPI_pfree()

void SPI_pfree ( void *  pointer)

Definition at line 1354 of file spi.c.

1355 {
1356  /* No longer need to worry which context chunk was in... */
1357  pfree(pointer);
1358 }

References pfree().

◆ SPI_plan_get_cached_plan()

CachedPlan* SPI_plan_get_cached_plan ( SPIPlanPtr  plan)

Definition at line 2076 of file spi.c.

2077 {
2078  CachedPlanSource *plansource;
2079  CachedPlan *cplan;
2080  SPICallbackArg spicallbackarg;
2081  ErrorContextCallback spierrcontext;
2082 
2083  Assert(plan->magic == _SPI_PLAN_MAGIC);
2084 
2085  /* Can't support one-shot plans here */
2086  if (plan->oneshot)
2087  return NULL;
2088 
2089  /* Must have exactly one CachedPlanSource */
2090  if (list_length(plan->plancache_list) != 1)
2091  return NULL;
2092  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
2093 
2094  /* Setup error traceback support for ereport() */
2095  spicallbackarg.query = plansource->query_string;
2096  spicallbackarg.mode = plan->parse_mode;
2097  spierrcontext.callback = _SPI_error_callback;
2098  spierrcontext.arg = &spicallbackarg;
2099  spierrcontext.previous = error_context_stack;
2100  error_context_stack = &spierrcontext;
2101 
2102  /* Get the generic plan for the query */
2103  cplan = GetCachedPlan(plansource, NULL,
2104  plan->saved ? CurrentResourceOwner : NULL,
2106  Assert(cplan == plansource->gplan);
2107 
2108  /* Pop the error context stack */
2109  error_context_stack = spierrcontext.previous;
2110 
2111  return cplan;
2112 }
struct CachedPlan * gplan
Definition: plancache.h:121

References _SPI_current, _SPI_error_callback(), _SPI_PLAN_MAGIC, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CurrentResourceOwner, error_context_stack, GetCachedPlan(), CachedPlanSource::gplan, linitial, list_length(), SPICallbackArg::mode, plan, ErrorContextCallback::previous, SPICallbackArg::query, CachedPlanSource::query_string, and _SPI_connection::queryEnv.

Referenced by exec_eval_simple_expr(), exec_simple_check_plan(), make_callstmt_target(), and test_predtest().

◆ SPI_plan_get_plan_sources()

List* SPI_plan_get_plan_sources ( SPIPlanPtr  plan)

Definition at line 2057 of file spi.c.

2058 {
2059  Assert(plan->magic == _SPI_PLAN_MAGIC);
2060  return plan->plancache_list;
2061 }

References _SPI_PLAN_MAGIC, Assert, and plan.

Referenced by exec_is_simple_query(), exec_simple_check_plan(), and exec_stmt_execsql().

◆ SPI_plan_is_valid()

bool SPI_plan_is_valid ( SPIPlanPtr  plan)

Definition at line 1948 of file spi.c.

1949 {
1950  ListCell *lc;
1951 
1952  Assert(plan->magic == _SPI_PLAN_MAGIC);
1953 
1954  foreach(lc, plan->plancache_list)
1955  {
1956  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1957 
1958  if (!CachedPlanIsValid(plansource))
1959  return false;
1960  }
1961  return true;
1962 }
bool CachedPlanIsValid(CachedPlanSource *plansource)
Definition: plancache.c:1627

References _SPI_PLAN_MAGIC, Assert, CachedPlanIsValid(), lfirst, and plan.

Referenced by ri_FetchPreparedPlan().

◆ SPI_prepare()

SPIPlanPtr SPI_prepare ( const char *  src,
int  nargs,
Oid argtypes 
)

◆ SPI_prepare_cursor()

SPIPlanPtr SPI_prepare_cursor ( const char *  src,
int  nargs,
Oid argtypes,
int  cursorOptions 
)

Definition at line 866 of file spi.c.

868 {
869  _SPI_plan plan;
870  SPIPlanPtr result;
871 
872  if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
873  {
875  return NULL;
876  }
877 
878  SPI_result = _SPI_begin_call(true);
879  if (SPI_result < 0)
880  return NULL;
881 
882  memset(&plan, 0, sizeof(_SPI_plan));
883  plan.magic = _SPI_PLAN_MAGIC;
884  plan.parse_mode = RAW_PARSE_DEFAULT;
885  plan.cursor_options = cursorOptions;
886  plan.nargs = nargs;
887  plan.argtypes = argtypes;
888  plan.parserSetup = NULL;
889  plan.parserSetupArg = NULL;
890 
891  _SPI_prepare_plan(src, &plan);
892 
893  /* copy plan to procedure context */
894  result = _SPI_make_plan_non_temp(&plan);
895 
896  _SPI_end_call(true);
897 
898  return result;
899 }
static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan)
Definition: spi.c:3141

References _SPI_begin_call(), _SPI_end_call(), _SPI_make_plan_non_temp(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), plan, RAW_PARSE_DEFAULT, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by SPI_prepare().

◆ SPI_prepare_extended()

SPIPlanPtr SPI_prepare_extended ( const char *  src,
const SPIPrepareOptions options 
)

Definition at line 902 of file spi.c.

904 {
905  _SPI_plan plan;
906  SPIPlanPtr result;
907 
908  if (src == NULL || options == NULL)
909  {
911  return NULL;
912  }
913 
914  SPI_result = _SPI_begin_call(true);
915  if (SPI_result < 0)
916  return NULL;
917 
918  memset(&plan, 0, sizeof(_SPI_plan));
919  plan.magic = _SPI_PLAN_MAGIC;
920  plan.parse_mode = options->parseMode;
921  plan.cursor_options = options->cursorOptions;
922  plan.nargs = 0;
923  plan.argtypes = NULL;
924  plan.parserSetup = options->parserSetup;
925  plan.parserSetupArg = options->parserSetupArg;
926 
927  _SPI_prepare_plan(src, &plan);
928 
929  /* copy plan to procedure context */
930  result = _SPI_make_plan_non_temp(&plan);
931 
932  _SPI_end_call(true);
933 
934  return result;
935 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_make_plan_non_temp(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), plan, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by exec_prepare_plan().

◆ SPI_prepare_params()

SPIPlanPtr SPI_prepare_params ( const char *  src,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
int  cursorOptions 
)

Definition at line 938 of file spi.c.

942 {
943  _SPI_plan plan;
944  SPIPlanPtr result;
945 
946  if (src == NULL)
947  {
949  return NULL;
950  }
951 
952  SPI_result = _SPI_begin_call(true);
953  if (SPI_result < 0)
954  return NULL;
955 
956  memset(&plan, 0, sizeof(_SPI_plan));
957  plan.magic = _SPI_PLAN_MAGIC;
958  plan.parse_mode = RAW_PARSE_DEFAULT;
959  plan.cursor_options = cursorOptions;
960  plan.nargs = 0;
961  plan.argtypes = NULL;
962  plan.parserSetup = parserSetup;
963  plan.parserSetupArg = parserSetupArg;
964 
965  _SPI_prepare_plan(src, &plan);
966 
967  /* copy plan to procedure context */
968  result = _SPI_make_plan_non_temp(&plan);
969 
970  _SPI_end_call(true);
971 
972  return result;
973 }

References _SPI_begin_call(), _SPI_end_call(), _SPI_make_plan_non_temp(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), plan, RAW_PARSE_DEFAULT, SPI_ERROR_ARGUMENT, and SPI_result.

◆ spi_printtup()

bool spi_printtup ( TupleTableSlot slot,
DestReceiver self 
)

Definition at line 2171 of file spi.c.

2172 {
2173  SPITupleTable *tuptable;
2174  MemoryContext oldcxt;
2175 
2176  if (_SPI_current == NULL)
2177  elog(ERROR, "spi_printtup called while not connected to SPI");
2178 
2179  tuptable = _SPI_current->tuptable;
2180  if (tuptable == NULL)
2181  elog(ERROR, "improper call to spi_printtup");
2182 
2183  oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
2184 
2185  if (tuptable->numvals >= tuptable->alloced)
2186  {
2187  /* Double the size of the pointer array */
2188  uint64 newalloced = tuptable->alloced * 2;
2189 
2190  tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
2191  newalloced * sizeof(HeapTuple));
2192  tuptable->alloced = newalloced;
2193  }
2194 
2195  tuptable->vals[tuptable->numvals] = ExecCopySlotHeapTuple(slot);
2196  (tuptable->numvals)++;
2197 
2198  MemoryContextSwitchTo(oldcxt);
2199 
2200  return true;
2201 }
void * repalloc_huge(void *pointer, Size size)
Definition: mcxt.c:1672
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:481

References _SPI_current, SPITupleTable::alloced, elog, ERROR, ExecCopySlotHeapTuple(), MemoryContextSwitchTo(), SPITupleTable::numvals, repalloc_huge(), SPITupleTable::tuptabcxt, _SPI_connection::tuptable, and SPITupleTable::vals.

◆ SPI_register_relation()

int SPI_register_relation ( EphemeralNamedRelation  enr)

Definition at line 3297 of file spi.c.

3298 {
3299  EphemeralNamedRelation match;
3300  int res;
3301 
3302  if (enr == NULL || enr->md.name == NULL)
3303  return SPI_ERROR_ARGUMENT;
3304 
3305  res = _SPI_begin_call(false); /* keep current memory context */
3306  if (res < 0)
3307  return res;
3308 
3309  match = _SPI_find_ENR_by_name(enr->md.name);
3310  if (match)
3312  else
3313  {
3314  if (_SPI_current->queryEnv == NULL)
3316 
3319  }
3320 
3321  _SPI_end_call(false);
3322 
3323  return res;
3324 }
QueryEnvironment * create_queryEnv(void)
void register_ENR(QueryEnvironment *queryEnv, EphemeralNamedRelation enr)
static EphemeralNamedRelation _SPI_find_ENR_by_name(const char *name)
Definition: spi.c:3280
#define SPI_ERROR_REL_DUPLICATE
Definition: spi.h:79
#define SPI_OK_REL_REGISTER
Definition: spi.h:96
EphemeralNamedRelationMetadataData md

References _SPI_begin_call(), _SPI_current, _SPI_end_call(), _SPI_find_ENR_by_name(), create_queryEnv(), EphemeralNamedRelationData::md, EphemeralNamedRelationMetadataData::name, _SPI_connection::queryEnv, register_ENR(), res, SPI_ERROR_ARGUMENT, SPI_ERROR_REL_DUPLICATE, and SPI_OK_REL_REGISTER.

Referenced by SPI_register_trigger_data().

◆ SPI_register_trigger_data()

int SPI_register_trigger_data ( TriggerData tdata)

Definition at line 3364 of file spi.c.

3365 {
3366  if (tdata == NULL)
3367  return SPI_ERROR_ARGUMENT;
3368 
3369  if (tdata->tg_newtable)
3370  {
3373  int rc;
3374 
3375  enr->md.name = tdata->tg_trigger->tgnewtable;
3376  enr->md.reliddesc = tdata->tg_relation->rd_id;
3377  enr->md.tupdesc = NULL;
3380  enr->reldata = tdata->tg_newtable;
3381  rc = SPI_register_relation(enr);
3382  if (rc != SPI_OK_REL_REGISTER)
3383  return rc;
3384  }
3385 
3386  if (tdata->tg_oldtable)
3387  {
3390  int rc;
3391 
3392  enr->md.name = tdata->tg_trigger->tgoldtable;
3393  enr->md.reliddesc = tdata->tg_relation->rd_id;
3394  enr->md.tupdesc = NULL;
3397  enr->reldata = tdata->tg_oldtable;
3398  rc = SPI_register_relation(enr);
3399  if (rc != SPI_OK_REL_REGISTER)
3400  return rc;
3401  }
3402 
3403  return SPI_OK_TD_REGISTER;
3404 }
@ ENR_NAMED_TUPLESTORE
int SPI_register_relation(EphemeralNamedRelation enr)
Definition: spi.c:3297
#define SPI_OK_TD_REGISTER
Definition: spi.h:98
EphemeralNameRelationType enrtype
Oid rd_id
Definition: rel.h:113
Tuplestorestate * tg_oldtable
Definition: trigger.h:41
Relation tg_relation
Definition: trigger.h:35
Tuplestorestate * tg_newtable
Definition: trigger.h:42
Trigger * tg_trigger
Definition: trigger.h:38
char * tgoldtable
Definition: reltrigger.h:43
char * tgnewtable
Definition: reltrigger.h:44
int64 tuplestore_tuple_count(Tuplestorestate *state)
Definition: tuplestore.c:580

References ENR_NAMED_TUPLESTORE, EphemeralNamedRelationMetadataData::enrtuples, EphemeralNamedRelationMetadataData::enrtype, EphemeralNamedRelationData::md, EphemeralNamedRelationMetadataData::name, palloc(), RelationData::rd_id, EphemeralNamedRelationData::reldata, EphemeralNamedRelationMetadataData::reliddesc, SPI_ERROR_ARGUMENT, SPI_OK_REL_REGISTER, SPI_OK_TD_REGISTER, SPI_register_relation(), TriggerData::tg_newtable, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, Trigger::tgnewtable, Trigger::tgoldtable, EphemeralNamedRelationMetadataData::tupdesc, and tuplestore_tuple_count().

Referenced by plperl_trigger_handler(), plpgsql_exec_trigger(), plsample_trigger_handler(), pltcl_trigger_handler(), and PLy_exec_trigger().

◆ SPI_repalloc()

void* SPI_repalloc ( void *  pointer,
Size  size 
)

Definition at line 1347 of file spi.c.

1348 {
1349  /* No longer need to worry which context chunk was in... */
1350  return repalloc(pointer, size);
1351 }

References repalloc(), and size.

◆ SPI_result_code_string()

const char* SPI_result_code_string ( int  code)

Definition at line 1972 of file spi.c.

1973 {
1974  static char buf[64];
1975 
1976  switch (code)
1977  {
1978  case SPI_ERROR_CONNECT:
1979  return "SPI_ERROR_CONNECT";
1980  case SPI_ERROR_COPY:
1981  return "SPI_ERROR_COPY";
1982  case SPI_ERROR_OPUNKNOWN:
1983  return "SPI_ERROR_OPUNKNOWN";
1984  case SPI_ERROR_UNCONNECTED:
1985  return "SPI_ERROR_UNCONNECTED";
1986  case SPI_ERROR_ARGUMENT:
1987  return "SPI_ERROR_ARGUMENT";
1988  case SPI_ERROR_PARAM:
1989  return "SPI_ERROR_PARAM";
1990  case SPI_ERROR_TRANSACTION:
1991  return "SPI_ERROR_TRANSACTION";
1992  case SPI_ERROR_NOATTRIBUTE:
1993  return "SPI_ERROR_NOATTRIBUTE";
1994  case SPI_ERROR_NOOUTFUNC:
1995  return "SPI_ERROR_NOOUTFUNC";
1996  case SPI_ERROR_TYPUNKNOWN:
1997  return "SPI_ERROR_TYPUNKNOWN";
1999  return "SPI_ERROR_REL_DUPLICATE";
2001  return "SPI_ERROR_REL_NOT_FOUND";
2002  case SPI_OK_CONNECT:
2003  return "SPI_OK_CONNECT";
2004  case SPI_OK_FINISH:
2005  return "SPI_OK_FINISH";
2006  case SPI_OK_FETCH:
2007  return "SPI_OK_FETCH";
2008  case SPI_OK_UTILITY:
2009  return "SPI_OK_UTILITY";
2010  case SPI_OK_SELECT:
2011  return "SPI_OK_SELECT";
2012  case SPI_OK_SELINTO:
2013  return "SPI_OK_SELINTO";
2014  case SPI_OK_INSERT:
2015  return "SPI_OK_INSERT";
2016  case SPI_OK_DELETE:
2017  return "SPI_OK_DELETE";
2018  case SPI_OK_UPDATE:
2019  return "SPI_OK_UPDATE";
2020  case SPI_OK_CURSOR:
2021  return "SPI_OK_CURSOR";
2023  return "SPI_OK_INSERT_RETURNING";
2025  return "SPI_OK_DELETE_RETURNING";
2027  return "SPI_OK_UPDATE_RETURNING";
2028  case SPI_OK_REWRITTEN:
2029  return "SPI_OK_REWRITTEN";
2030  case SPI_OK_REL_REGISTER:
2031  return "SPI_OK_REL_REGISTER";
2032  case SPI_OK_REL_UNREGISTER:
2033  return "SPI_OK_REL_UNREGISTER";
2034  case SPI_OK_TD_REGISTER:
2035  return "SPI_OK_TD_REGISTER";
2036  case SPI_OK_MERGE:
2037  return "SPI_OK_MERGE";
2039  return "SPI_OK_MERGE_RETURNING";
2040  }
2041  /* Unrecognized code ... return something useful ... */
2042  sprintf(buf, "Unrecognized SPI code %d", code);
2043  return buf;
2044 }
static char * buf
Definition: pg_test_fsync.c:72
#define sprintf
Definition: port.h:240
#define SPI_ERROR_REL_NOT_FOUND
Definition: spi.h:80
#define SPI_OK_CURSOR
Definition: spi.h:91
#define SPI_OK_FETCH
Definition: spi.h:84
#define SPI_OK_REL_UNREGISTER
Definition: spi.h:97
#define SPI_ERROR_NOOUTFUNC
Definition: spi.h:77
#define SPI_ERROR_CONNECT
Definition: spi.h:68

References buf, SPI_ERROR_ARGUMENT, SPI_ERROR_CONNECT, SPI_ERROR_COPY, SPI_ERROR_NOATTRIBUTE, SPI_ERROR_NOOUTFUNC, SPI_ERROR_OPUNKNOWN, SPI_ERROR_PARAM, SPI_ERROR_REL_DUPLICATE, SPI_ERROR_REL_NOT_FOUND, SPI_ERROR_TRANSACTION, SPI_ERROR_TYPUNKNOWN, SPI_ERROR_UNCONNECTED, SPI_OK_CONNECT, SPI_OK_CURSOR, SPI_OK_DELETE, SPI_OK_DELETE_RETURNING, SPI_OK_FETCH, SPI_OK_FINISH, SPI_OK_INSERT, SPI_OK_INSERT_RETURNING, SPI_OK_MERGE, SPI_OK_MERGE_RETURNING, SPI_OK_REL_REGISTER, SPI_OK_REL_UNREGISTER, SPI_OK_REWRITTEN, SPI_OK_SELECT, SPI_OK_SELINTO, SPI_OK_TD_REGISTER, SPI_OK_UPDATE, SPI_OK_UPDATE_RETURNING, SPI_OK_UTILITY, and sprintf.

Referenced by check_foreign_key(), check_primary_key(), exec_dynquery_with_params(), exec_prepare_plan(), exec_run_select(), exec_stmt_call(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_forc(), exec_stmt_open(), exec_stmt_return_query(), plperl_spi_execute_fetch_result(), plperl_spi_prepare(), plperl_spi_query(), plperl_spi_query_prepared(), plpgsql_call_handler(), plpgsql_inline_handler(), plpgsql_validator(), pltcl_process_SPI_result(), PLy_cursor_plan(), PLy_cursor_query(), PLy_spi_execute_plan(), PLy_spi_execute_query(), PLy_spi_prepare(), query_to_oid_list(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_PerformCheck(), ri_PlanCheck(), and ttdummy().

◆ SPI_returntuple()

HeapTupleHeader SPI_returntuple ( HeapTuple  tuple,
TupleDesc  tupdesc 
)

Definition at line 1074 of file spi.c.

1075 {
1076  MemoryContext oldcxt;
1077  HeapTupleHeader dtup;
1078 
1079  if (tuple == NULL || tupdesc == NULL)
1080  {
1082  return NULL;
1083  }
1084 
1085  if (_SPI_current == NULL)
1086  {
1088  return NULL;
1089  }
1090 
1091  /* For RECORD results, make sure a typmod has been assigned */
1092  if (tupdesc->tdtypeid == RECORDOID &&
1093  tupdesc->tdtypmod < 0)
1094  assign_record_type_typmod(tupdesc);
1095 
1097 
1098  dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
1099 
1100  MemoryContextSwitchTo(oldcxt);
1101 
1102  return dtup;
1103 }
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:1080
int32 tdtypmod
Definition: tupdesc.h:83
Oid tdtypeid
Definition: tupdesc.h:82
void assign_record_type_typmod(TupleDesc tupDesc)
Definition: typcache.c:2040

References _SPI_current, assign_record_type_typmod(), DatumGetHeapTupleHeader, heap_copy_tuple_as_datum(), MemoryContextSwitchTo(), _SPI_connection::savedcxt, SPI_ERROR_ARGUMENT, SPI_ERROR_UNCONNECTED, SPI_result, TupleDescData::tdtypeid, and TupleDescData::tdtypmod.

Referenced by coerce_function_result_tuple().

◆ SPI_rollback()

void SPI_rollback ( void  )

Definition at line 413 of file spi.c.

414 {
415  _SPI_rollback(false);
416 }
static void _SPI_rollback(bool chain)
Definition: spi.c:332

References _SPI_rollback().

Referenced by exec_stmt_rollback(), plperl_spi_rollback(), pltcl_rollback(), and PLy_rollback().

◆ SPI_rollback_and_chain()

void SPI_rollback_and_chain ( void  )

Definition at line 419 of file spi.c.

420 {
421  _SPI_rollback(true);
422 }

References _SPI_rollback().

Referenced by exec_stmt_rollback().

◆ SPI_saveplan()

SPIPlanPtr SPI_saveplan ( SPIPlanPtr  plan)

Definition at line 1003 of file spi.c.

1004 {
1005  SPIPlanPtr newplan;
1006 
1007  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1008  {
1010  return NULL;
1011  }
1012 
1013  SPI_result = _SPI_begin_call(false); /* don't change context */
1014  if (SPI_result < 0)
1015  return NULL;
1016 
1017  newplan = _SPI_save_plan(plan);
1018 
1019  SPI_result = _SPI_end_call(false);
1020 
1021  return newplan;
1022 }
static SPIPlanPtr _SPI_save_plan(SPIPlanPtr plan)
Definition: spi.c:3209

References _SPI_begin_call(), _SPI_end_call(), _SPI_PLAN_MAGIC, _SPI_save_plan(), plan, SPI_ERROR_ARGUMENT, and SPI_result.

◆ SPI_scroll_cursor_fetch()

void SPI_scroll_cursor_fetch ( Portal  portal,
FetchDirection  direction,
long  count 
)

Definition at line 1835 of file spi.c.

1836 {
1837  _SPI_cursor_operation(portal,
1838  direction, count,
1840  /* we know that the DestSPI receiver doesn't need a destroy call */
1841 }

References _SPI_cursor_operation(), CreateDestReceiver(), and DestSPI.

Referenced by exec_stmt_fetch().

◆ SPI_scroll_cursor_move()

void SPI_scroll_cursor_move ( Portal  portal,
FetchDirection  direction,
long  count 
)

Definition at line 1850 of file spi.c.

1851 {
1852  _SPI_cursor_operation(portal, direction, count, None_Receiver);
1853 }

References _SPI_cursor_operation(), and None_Receiver.

Referenced by exec_stmt_fetch().

◆ SPI_start_transaction()

void SPI_start_transaction ( void  )

Definition at line 222 of file spi.c.

223 {
224 }

◆ SPI_unregister_relation()

int SPI_unregister_relation ( const char *  name)

Definition at line 3331 of file spi.c.

3332 {
3333  EphemeralNamedRelation match;
3334  int res;
3335 
3336  if (name == NULL)
3337  return SPI_ERROR_ARGUMENT;
3338 
3339  res = _SPI_begin_call(false); /* keep current memory context */
3340  if (res < 0)
3341  return res;
3342 
3343  match = _SPI_find_ENR_by_name(name);
3344  if (match)
3345  {
3348  }
3349  else
3351 
3352  _SPI_end_call(false);
3353 
3354  return res;
3355 }
void unregister_ENR(QueryEnvironment *queryEnv, const char *name)

References _SPI_begin_call(), _SPI_current, _SPI_end_call(), _SPI_find_ENR_by_name(), EphemeralNamedRelationData::md, name, EphemeralNamedRelationMetadataData::name, _SPI_connection::queryEnv, res, SPI_ERROR_ARGUMENT, SPI_ERROR_REL_NOT_FOUND, SPI_OK_REL_UNREGISTER, and unregister_ENR().

Variable Documentation

◆ _SPI_connected

int _SPI_connected = -1
static

Definition at line 51 of file spi.c.

Referenced by AtEOSubXact_SPI(), AtEOXact_SPI(), SPI_connect_ext(), and SPI_finish().

◆ _SPI_current

◆ _SPI_stack

_SPI_connection* _SPI_stack = NULL
static

Definition at line 48 of file spi.c.

Referenced by AtEOSubXact_SPI(), AtEOXact_SPI(), SPI_connect_ext(), and SPI_finish().

◆ _SPI_stack_depth

int _SPI_stack_depth = 0
static

Definition at line 50 of file spi.c.

Referenced by SPI_connect_ext().

◆ SPI_processed

◆ SPI_result

◆ SPI_tuptable