PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 "miscadmin.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.

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, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
 
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 execmem)
 
static int _SPI_end_call (bool procmem)
 
static MemoryContext _SPI_execmem (void)
 
static MemoryContext _SPI_procmem (void)
 
static bool _SPI_checktuples (void)
 
int SPI_connect (void)
 
int SPI_finish (void)
 
void AtEOXact_SPI (bool isCommit)
 
void AtEOSubXact_SPI (bool isCommit, SubTransactionId mySubid)
 
int SPI_execute (const char *src, bool read_only, long tcount)
 
int SPI_exec (const char *src, long tcount)
 
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_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_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_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
 
Oid SPI_lastoid = InvalidOid
 
SPITupleTableSPI_tuptable = NULL
 
int SPI_result
 
static _SPI_connection_SPI_stack = NULL
 
static _SPI_connection_SPI_current = NULL
 
static int _SPI_stack_depth = 0
 
static int _SPI_connected = -1
 

Function Documentation

static int _SPI_begin_call ( bool  execmem)
static

Definition at line 2449 of file spi.c.

References _SPI_execmem(), NULL, and SPI_ERROR_UNCONNECTED.

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

2450 {
2451  if (_SPI_current == NULL)
2452  return SPI_ERROR_UNCONNECTED;
2453 
2454  if (execmem) /* switch to the Executor memory context */
2455  _SPI_execmem();
2456 
2457  return 0;
2458 }
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
static _SPI_connection * _SPI_current
Definition: spi.c:45
static MemoryContext _SPI_execmem(void)
Definition: spi.c:2434
#define NULL
Definition: c.h:229
static bool _SPI_checktuples ( void  )
static

Definition at line 2479 of file spi.c.

References SPITupleTable::alloced, SPITupleTable::free, NULL, _SPI_connection::processed, and _SPI_connection::tuptable.

Referenced by _SPI_cursor_operation(), and _SPI_pquery().

2480 {
2481  uint64 processed = _SPI_current->processed;
2482  SPITupleTable *tuptable = _SPI_current->tuptable;
2483  bool failed = false;
2484 
2485  if (tuptable == NULL) /* spi_dest_startup was not called */
2486  failed = true;
2487  else if (processed != (tuptable->alloced - tuptable->free))
2488  failed = true;
2489 
2490  return failed;
2491 }
static _SPI_connection * _SPI_current
Definition: spi.c:45
SPITupleTable * tuptable
Definition: spi_priv.h:27
#define NULL
Definition: c.h:229
uint64 processed
Definition: spi_priv.h:25
uint64 free
Definition: spi.h:26
uint64 alloced
Definition: spi.h:25
static ParamListInfo _SPI_convert_params ( int  nargs,
Oid argtypes,
Datum Values,
const char *  Nulls 
)
static

Definition at line 2240 of file spi.c.

References i, ParamExternData::isnull, NULL, ParamListInfoData::numParams, offsetof, palloc(), PARAM_FLAG_CONST, ParamListInfoData::paramFetch, ParamListInfoData::paramFetchArg, ParamListInfoData::paramMask, ParamListInfoData::params, ParamListInfoData::parserSetup, ParamListInfoData::parserSetupArg, 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().

2242 {
2243  ParamListInfo paramLI;
2244 
2245  if (nargs > 0)
2246  {
2247  int i;
2248 
2249  paramLI = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
2250  nargs * sizeof(ParamExternData));
2251  /* we have static list of params, so no hooks needed */
2252  paramLI->paramFetch = NULL;
2253  paramLI->paramFetchArg = NULL;
2254  paramLI->parserSetup = NULL;
2255  paramLI->parserSetupArg = NULL;
2256  paramLI->numParams = nargs;
2257  paramLI->paramMask = NULL;
2258 
2259  for (i = 0; i < nargs; i++)
2260  {
2261  ParamExternData *prm = &paramLI->params[i];
2262 
2263  prm->value = Values[i];
2264  prm->isnull = (Nulls && Nulls[i] == 'n');
2265  prm->pflags = PARAM_FLAG_CONST;
2266  prm->ptype = argtypes[i];
2267  }
2268  }
2269  else
2270  paramLI = NULL;
2271  return paramLI;
2272 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Datum value
Definition: params.h:56
void * parserSetupArg
Definition: params.h:73
ParserSetupHook parserSetup
Definition: params.h:72
struct ParamListInfoData * ParamListInfo
Definition: params.h:62
void * paramFetchArg
Definition: params.h:71
ParamFetchHook paramFetch
Definition: params.h:70
struct Bitmapset * paramMask
Definition: params.h:75
struct ParamExternData ParamExternData
#define NULL
Definition: c.h:229
uint16 pflags
Definition: params.h:58
void * palloc(Size size)
Definition: mcxt.c:849
int i
bool isnull
Definition: params.h:57
#define offsetof(type, field)
Definition: c.h:555
#define PARAM_FLAG_CONST
Definition: params.h:52
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
static void _SPI_cursor_operation ( Portal  portal,
FetchDirection  direction,
long  count,
DestReceiver dest 
)
static

Definition at line 2383 of file spi.c.

References _SPI_begin_call(), _SPI_checktuples(), _SPI_end_call(), DestSPI, elog, ERROR, _DestReceiver::mydest, NULL, PortalIsValid, PortalRunFetch(), _SPI_connection::processed, SPI_processed, and _SPI_connection::tuptable.

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

2385 {
2386  uint64 nfetched;
2387 
2388  /* Check that the portal is valid */
2389  if (!PortalIsValid(portal))
2390  elog(ERROR, "invalid portal in SPI cursor operation");
2391 
2392  /* Push the SPI stack */
2393  if (_SPI_begin_call(true) < 0)
2394  elog(ERROR, "SPI cursor operation called while not connected");
2395 
2396  /* Reset the SPI result (note we deliberately don't touch lastoid) */
2397  SPI_processed = 0;
2398  SPI_tuptable = NULL;
2399  _SPI_current->processed = 0;
2401 
2402  /* Run the cursor */
2403  nfetched = PortalRunFetch(portal,
2404  direction,
2405  count,
2406  dest);
2407 
2408  /*
2409  * Think not to combine this store with the preceding function call. If
2410  * the portal contains calls to functions that use SPI, then SPI_stack is
2411  * likely to move around while the portal runs. When control returns,
2412  * _SPI_current will point to the correct stack entry... but the pointer
2413  * may be different than it was beforehand. So we must be sure to re-fetch
2414  * the pointer after the function call completes.
2415  */
2416  _SPI_current->processed = nfetched;
2417 
2418  if (dest->mydest == DestSPI && _SPI_checktuples())
2419  elog(ERROR, "consistency check on SPI tuple count failed");
2420 
2421  /* Put the result into place for access by caller */
2424 
2425  /* tuptable now is caller's responsibility, not SPI's */
2427 
2428  /* Pop the SPI stack */
2429  _SPI_end_call(true);
2430 }
Definition: dest.h:93
CommandDest mydest
Definition: dest.h:128
uint64 PortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1395
SPITupleTable * SPI_tuptable
Definition: spi.c:41
static _SPI_connection * _SPI_current
Definition: spi.c:45
uint64 SPI_processed
Definition: spi.c:39
static bool _SPI_checktuples(void)
Definition: spi.c:2479
#define ERROR
Definition: elog.h:43
SPITupleTable * tuptable
Definition: spi_priv.h:27
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define PortalIsValid(p)
Definition: portal.h:199
#define NULL
Definition: c.h:229
uint64 processed
Definition: spi_priv.h:25
#define elog
Definition: elog.h:219
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
static int _SPI_end_call ( bool  procmem)
static

Definition at line 2466 of file spi.c.

References _SPI_procmem(), _SPI_connection::execCxt, and MemoryContextResetAndDeleteChildren.

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

2467 {
2468  if (procmem) /* switch to the procedure memory context */
2469  {
2470  _SPI_procmem();
2471  /* and free Executor memory */
2473  }
2474 
2475  return 0;
2476 }
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
MemoryContext execCxt
Definition: spi_priv.h:32
static MemoryContext _SPI_procmem(void)
Definition: spi.c:2440
static void _SPI_error_callback ( void *  arg)
static

Definition at line 2357 of file spi.c.

References errcontext, errposition(), geterrposition(), internalerrposition(), and internalerrquery().

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

2358 {
2359  const char *query = (const char *) arg;
2360  int syntaxerrposition;
2361 
2362  /*
2363  * If there is a syntax error position, convert to internal syntax error;
2364  * otherwise treat the query as an item of context stack
2365  */
2366  syntaxerrposition = geterrposition();
2367  if (syntaxerrposition > 0)
2368  {
2369  errposition(0);
2370  internalerrposition(syntaxerrposition);
2371  internalerrquery(query);
2372  }
2373  else
2374  errcontext("SQL statement \"%s\"", query);
2375 }
int geterrposition(void)
Definition: elog.c:1257
int internalerrquery(const char *query)
Definition: elog.c:1161
#define errcontext
Definition: elog.h:164
void * arg
int errposition(int cursorpos)
Definition: elog.c:1125
int internalerrposition(int cursorpos)
Definition: elog.c:1141
static MemoryContext _SPI_execmem ( void  )
static

Definition at line 2434 of file spi.c.

References _SPI_connection::execCxt, and MemoryContextSwitchTo().

Referenced by _SPI_begin_call().

2435 {
2437 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
MemoryContext execCxt
Definition: spi_priv.h:32
static int _SPI_execute_plan ( SPIPlanPtr  plan,
ParamListInfo  paramLI,
Snapshot  snapshot,
Snapshot  crosscheck_snapshot,
bool  read_only,
bool  fire_triggers,
uint64  tcount 
)
static

Definition at line 1908 of file spi.c.

References _SPI_error_callback(), _SPI_pquery(), ActiveSnapshotSet(), SPITupleTable::alloced, ErrorContextCallback::arg, _SPI_plan::argtypes, Assert, ErrorContextCallback::callback, PlannedStmt::canSetTag, CommandCounterIncrement(), CommandIsReadOnly(), CompleteCachedPlan(), COMPLETION_TAG_BUFSIZE, CreateCommandTag(), CreateDestReceiver(), CreateQueryDesc(), _SPI_plan::cursor_options, DestNone, DestSPI, ereport, errcode(), errmsg(), ERROR, error_context_stack, CopyStmt::filename, SPITupleTable::free, FreeQueryDesc(), GetActiveSnapshot(), GetCachedPlan(), GetTransactionSnapshot(), CreateTableAsStmt::if_not_exists, CreateTableAsStmt::into, InvalidOid, InvalidSnapshot, CreateTableAsStmt::is_select_into, IsA, IsInParallelMode(), _SPI_connection::lastoid, lfirst, lfirst_node, _SPI_plan::nargs, NIL, NULL, _SPI_plan::oneshot, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_strtouint64(), _SPI_plan::plancache_list, PopActiveSnapshot(), PreventCommandIfParallelMode(), ErrorContextCallback::previous, PROCESS_UTILITY_QUERY, _SPI_connection::processed, ProcessUtility(), PushActiveSnapshot(), PushCopiedSnapshot(), CachedPlanSource::query_string, _SPI_connection::queryEnv, CachedPlanSource::raw_parse_tree, ReleaseCachedPlan(), _SPI_plan::saved, IntoClause::skipData, SPI_ERROR_COPY, SPI_ERROR_TRANSACTION, SPI_freetuptable(), SPI_lastoid, SPI_OK_REWRITTEN, SPI_OK_SELINTO, SPI_OK_UTILITY, SPI_processed, CachedPlan::stmt_list, _SPI_connection::tuptable, UpdateActiveSnapshotCommandId(), and PlannedStmt::utilityStmt.

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

1911 {
1912  int my_res = 0;
1913  uint64 my_processed = 0;
1914  Oid my_lastoid = InvalidOid;
1915  SPITupleTable *my_tuptable = NULL;
1916  int res = 0;
1917  bool pushed_active_snap = false;
1918  ErrorContextCallback spierrcontext;
1919  CachedPlan *cplan = NULL;
1920  ListCell *lc1;
1921 
1922  /*
1923  * Setup error traceback support for ereport()
1924  */
1925  spierrcontext.callback = _SPI_error_callback;
1926  spierrcontext.arg = NULL; /* we'll fill this below */
1927  spierrcontext.previous = error_context_stack;
1928  error_context_stack = &spierrcontext;
1929 
1930  /*
1931  * We support four distinct snapshot management behaviors:
1932  *
1933  * snapshot != InvalidSnapshot, read_only = true: use exactly the given
1934  * snapshot.
1935  *
1936  * snapshot != InvalidSnapshot, read_only = false: use the given snapshot,
1937  * modified by advancing its command ID before each querytree.
1938  *
1939  * snapshot == InvalidSnapshot, read_only = true: use the entry-time
1940  * ActiveSnapshot, if any (if there isn't one, we run with no snapshot).
1941  *
1942  * snapshot == InvalidSnapshot, read_only = false: take a full new
1943  * snapshot for each user command, and advance its command ID before each
1944  * querytree within the command.
1945  *
1946  * In the first two cases, we can just push the snap onto the stack once
1947  * for the whole plan list.
1948  */
1949  if (snapshot != InvalidSnapshot)
1950  {
1951  if (read_only)
1952  {
1953  PushActiveSnapshot(snapshot);
1954  pushed_active_snap = true;
1955  }
1956  else
1957  {
1958  /* Make sure we have a private copy of the snapshot to modify */
1959  PushCopiedSnapshot(snapshot);
1960  pushed_active_snap = true;
1961  }
1962  }
1963 
1964  foreach(lc1, plan->plancache_list)
1965  {
1966  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
1967  List *stmt_list;
1968  ListCell *lc2;
1969 
1970  spierrcontext.arg = (void *) plansource->query_string;
1971 
1972  /*
1973  * If this is a one-shot plan, we still need to do parse analysis.
1974  */
1975  if (plan->oneshot)
1976  {
1977  RawStmt *parsetree = plansource->raw_parse_tree;
1978  const char *src = plansource->query_string;
1979  List *stmt_list;
1980 
1981  /*
1982  * Parameter datatypes are driven by parserSetup hook if provided,
1983  * otherwise we use the fixed parameter list.
1984  */
1985  if (parsetree == NULL)
1986  stmt_list = NIL;
1987  else if (plan->parserSetup != NULL)
1988  {
1989  Assert(plan->nargs == 0);
1990  stmt_list = pg_analyze_and_rewrite_params(parsetree,
1991  src,
1992  plan->parserSetup,
1993  plan->parserSetupArg,
1995  }
1996  else
1997  {
1998  stmt_list = pg_analyze_and_rewrite(parsetree,
1999  src,
2000  plan->argtypes,
2001  plan->nargs,
2003  }
2004 
2005  /* Finish filling in the CachedPlanSource */
2006  CompleteCachedPlan(plansource,
2007  stmt_list,
2008  NULL,
2009  plan->argtypes,
2010  plan->nargs,
2011  plan->parserSetup,
2012  plan->parserSetupArg,
2013  plan->cursor_options,
2014  false); /* not fixed result */
2015  }
2016 
2017  /*
2018  * Replan if needed, and increment plan refcount. If it's a saved
2019  * plan, the refcount must be backed by the CurrentResourceOwner.
2020  */
2021  cplan = GetCachedPlan(plansource, paramLI, plan->saved, _SPI_current->queryEnv);
2022  stmt_list = cplan->stmt_list;
2023 
2024  /*
2025  * In the default non-read-only case, get a new snapshot, replacing
2026  * any that we pushed in a previous cycle.
2027  */
2028  if (snapshot == InvalidSnapshot && !read_only)
2029  {
2030  if (pushed_active_snap)
2033  pushed_active_snap = true;
2034  }
2035 
2036  foreach(lc2, stmt_list)
2037  {
2038  PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
2039  bool canSetTag = stmt->canSetTag;
2040  DestReceiver *dest;
2041 
2042  _SPI_current->processed = 0;
2045 
2046  if (stmt->utilityStmt)
2047  {
2048  if (IsA(stmt->utilityStmt, CopyStmt))
2049  {
2050  CopyStmt *cstmt = (CopyStmt *) stmt->utilityStmt;
2051 
2052  if (cstmt->filename == NULL)
2053  {
2054  my_res = SPI_ERROR_COPY;
2055  goto fail;
2056  }
2057  }
2058  else if (IsA(stmt->utilityStmt, TransactionStmt))
2059  {
2060  my_res = SPI_ERROR_TRANSACTION;
2061  goto fail;
2062  }
2063  }
2064 
2065  if (read_only && !CommandIsReadOnly(stmt))
2066  ereport(ERROR,
2067  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2068  /* translator: %s is a SQL statement name */
2069  errmsg("%s is not allowed in a non-volatile function",
2070  CreateCommandTag((Node *) stmt))));
2071 
2072  if (IsInParallelMode() && !CommandIsReadOnly(stmt))
2074 
2075  /*
2076  * If not read-only mode, advance the command counter before each
2077  * command and update the snapshot.
2078  */
2079  if (!read_only)
2080  {
2083  }
2084 
2085  dest = CreateDestReceiver(canSetTag ? DestSPI : DestNone);
2086 
2087  if (stmt->utilityStmt == NULL)
2088  {
2089  QueryDesc *qdesc;
2090  Snapshot snap;
2091 
2092  if (ActiveSnapshotSet())
2093  snap = GetActiveSnapshot();
2094  else
2095  snap = InvalidSnapshot;
2096 
2097  qdesc = CreateQueryDesc(stmt,
2098  plansource->query_string,
2099  snap, crosscheck_snapshot,
2100  dest,
2101  paramLI, _SPI_current->queryEnv,
2102  0);
2103  res = _SPI_pquery(qdesc, fire_triggers,
2104  canSetTag ? tcount : 0);
2105  FreeQueryDesc(qdesc);
2106  }
2107  else
2108  {
2109  char completionTag[COMPLETION_TAG_BUFSIZE];
2110 
2111  ProcessUtility(stmt,
2112  plansource->query_string,
2114  paramLI,
2116  dest,
2117  completionTag);
2118 
2119  /* Update "processed" if stmt returned tuples */
2120  if (_SPI_current->tuptable)
2123 
2124  res = SPI_OK_UTILITY;
2125 
2126  /*
2127  * Some utility statements return a row count, even though the
2128  * tuples are not returned to the caller.
2129  */
2130  if (IsA(stmt->utilityStmt, CreateTableAsStmt))
2131  {
2132  CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
2133 
2134  if (strncmp(completionTag, "SELECT ", 7) == 0)
2136  pg_strtouint64(completionTag + 7, NULL, 10);
2137  else
2138  {
2139  /*
2140  * Must be an IF NOT EXISTS that did nothing, or a
2141  * CREATE ... WITH NO DATA.
2142  */
2143  Assert(ctastmt->if_not_exists ||
2144  ctastmt->into->skipData);
2145  _SPI_current->processed = 0;
2146  }
2147 
2148  /*
2149  * For historical reasons, if CREATE TABLE AS was spelled
2150  * as SELECT INTO, return a special return code.
2151  */
2152  if (ctastmt->is_select_into)
2153  res = SPI_OK_SELINTO;
2154  }
2155  else if (IsA(stmt->utilityStmt, CopyStmt))
2156  {
2157  Assert(strncmp(completionTag, "COPY ", 5) == 0);
2158  _SPI_current->processed = pg_strtouint64(completionTag + 5,
2159  NULL, 10);
2160  }
2161  }
2162 
2163  /*
2164  * The last canSetTag query sets the status values returned to the
2165  * caller. Be careful to free any tuptables not returned, to
2166  * avoid intratransaction memory leak.
2167  */
2168  if (canSetTag)
2169  {
2170  my_processed = _SPI_current->processed;
2171  my_lastoid = _SPI_current->lastoid;
2172  SPI_freetuptable(my_tuptable);
2173  my_tuptable = _SPI_current->tuptable;
2174  my_res = res;
2175  }
2176  else
2177  {
2180  }
2181  /* we know that the receiver doesn't need a destroy call */
2182  if (res < 0)
2183  {
2184  my_res = res;
2185  goto fail;
2186  }
2187  }
2188 
2189  /* Done with this plan, so release refcount */
2190  ReleaseCachedPlan(cplan, plan->saved);
2191  cplan = NULL;
2192 
2193  /*
2194  * If not read-only mode, advance the command counter after the last
2195  * command. This ensures that its effects are visible, in case it was
2196  * DDL that would affect the next CachedPlanSource.
2197  */
2198  if (!read_only)
2200  }
2201 
2202 fail:
2203 
2204  /* Pop the snapshot off the stack if we pushed one */
2205  if (pushed_active_snap)
2207 
2208  /* We no longer need the cached plan refcount, if any */
2209  if (cplan)
2210  ReleaseCachedPlan(cplan, plan->saved);
2211 
2212  /*
2213  * Pop the error context stack
2214  */
2215  error_context_stack = spierrcontext.previous;
2216 
2217  /* Save results for caller */
2218  SPI_processed = my_processed;
2219  SPI_lastoid = my_lastoid;
2220  SPI_tuptable = my_tuptable;
2221 
2222  /* tuptable now is caller's responsibility, not SPI's */
2224 
2225  /*
2226  * If none of the queries had canSetTag, return SPI_OK_REWRITTEN. Prior to
2227  * 8.4, we used return the last query's result code, but not its auxiliary
2228  * results, but that's confusing.
2229  */
2230  if (my_res == 0)
2231  my_res = SPI_OK_REWRITTEN;
2232 
2233  return my_res;
2234 }
#define NIL
Definition: pg_list.h:69
Oid * argtypes
Definition: spi_priv.h:86
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:97
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:781
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * plancache_list
Definition: spi_priv.h:82
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1135
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
Definition: dest.h:93
#define SPI_ERROR_COPY
Definition: spi.h:37
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
SPITupleTable * SPI_tuptable
Definition: spi.c:41
Definition: nodes.h:509
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag)
Definition: utility.c:335
int errcode(int sqlerrcode)
Definition: elog.c:575
static _SPI_connection * _SPI_current
Definition: spi.c:45
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
bool skipData
Definition: primnodes.h:115
unsigned int Oid
Definition: postgres_ext.h:31
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:638
struct ErrorContextCallback * previous
Definition: elog.h:238
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
uint64 SPI_processed
Definition: spi.c:39
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void _SPI_error_callback(void *arg)
Definition: spi.c:2357
bool IsInParallelMode(void)
Definition: xact.c:913
#define ERROR
Definition: elog.h:43
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
SPITupleTable * tuptable
Definition: spi_priv.h:27
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:769
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
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
Definition: spi.c:2275
Definition: dest.h:88
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
#define SPI_OK_UTILITY
Definition: spi.h:53
Node * utilityStmt
Definition: plannodes.h:94
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1256
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
#define SPI_OK_REWRITTEN
Definition: spi.h:63
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2036
#define SPI_ERROR_TRANSACTION
Definition: spi.h:43
#define SPI_OK_SELINTO
Definition: spi.h:55
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:970
#define InvalidSnapshot
Definition: snapshot.h:25
uint64 pg_strtouint64(const char *str, char **endptr, int base)
Definition: numutils.c:405
bool canSetTag
Definition: plannodes.h:53
Oid SPI_lastoid
Definition: spi.c:40
void CommandCounterIncrement(void)
Definition: xact.c:922
bool saved
Definition: spi_priv.h:80
int nargs
Definition: spi_priv.h:85
#define InvalidOid
Definition: postgres_ext.h:36
IntoClause * into
Definition: parsenodes.h:3125
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define NULL
Definition: c.h:229
uint64 processed
Definition: spi_priv.h:25
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
ParserSetupHook parserSetup
Definition: spi_priv.h:87
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:325
bool oneshot
Definition: spi_priv.h:81
const char * query_string
Definition: plancache.h:84
void * parserSetupArg
Definition: spi_priv.h:88
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:675
struct RawStmt * raw_parse_tree
Definition: plancache.h:83
uint64 free
Definition: spi.h:26
void(* callback)(void *arg)
Definition: elog.h:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
uint64 alloced
Definition: spi.h:25
char * filename
Definition: parsenodes.h:1933
List * stmt_list
Definition: plancache.h:133
int cursor_options
Definition: spi_priv.h:84
Definition: pg_list.h:45
static EphemeralNamedRelation _SPI_find_ENR_by_name ( const char *  name)
static

Definition at line 2646 of file spi.c.

References Assert, get_ENR(), NULL, and _SPI_connection::queryEnv.

Referenced by SPI_register_relation(), and SPI_unregister_relation().

2647 {
2648  /* internal static function; any error is bug in SPI itself */
2649  Assert(name != NULL);
2650 
2651  /* fast exit if no tuplestores have been added */
2652  if (_SPI_current->queryEnv == NULL)
2653  return NULL;
2654 
2655  return get_ENR(_SPI_current->queryEnv, name);
2656 }
static _SPI_connection * _SPI_current
Definition: spi.c:45
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
const char * name
Definition: encode.c:521
EphemeralNamedRelation get_ENR(QueryEnvironment *queryEnv, const char *name)
static SPIPlanPtr _SPI_make_plan_non_temp ( SPIPlanPtr  plan)
static

Definition at line 2503 of file spi.c.

References _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, NULL, _SPI_plan::oneshot, palloc(), _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, _SPI_plan::plancache_list, _SPI_plan::plancxt, _SPI_connection::procCxt, and _SPI_plan::saved.

Referenced by SPI_prepare_cursor(), and SPI_prepare_params().

2504 {
2505  SPIPlanPtr newplan;
2506  MemoryContext parentcxt = _SPI_current->procCxt;
2507  MemoryContext plancxt;
2508  MemoryContext oldcxt;
2509  ListCell *lc;
2510 
2511  /* Assert the input is a temporary SPIPlan */
2512  Assert(plan->magic == _SPI_PLAN_MAGIC);
2513  Assert(plan->plancxt == NULL);
2514  /* One-shot plans can't be saved */
2515  Assert(!plan->oneshot);
2516 
2517  /*
2518  * Create a memory context for the plan, underneath the procedure context.
2519  * We don't expect the plan to be very large.
2520  */
2521  plancxt = AllocSetContextCreate(parentcxt,
2522  "SPI Plan",
2524  oldcxt = MemoryContextSwitchTo(plancxt);
2525 
2526  /* Copy the SPI_plan struct and subsidiary data into the new context */
2527  newplan = (SPIPlanPtr) palloc(sizeof(_SPI_plan));
2528  newplan->magic = _SPI_PLAN_MAGIC;
2529  newplan->saved = false;
2530  newplan->oneshot = false;
2531  newplan->plancache_list = NIL;
2532  newplan->plancxt = plancxt;
2533  newplan->cursor_options = plan->cursor_options;
2534  newplan->nargs = plan->nargs;
2535  if (plan->nargs > 0)
2536  {
2537  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
2538  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
2539  }
2540  else
2541  newplan->argtypes = NULL;
2542  newplan->parserSetup = plan->parserSetup;
2543  newplan->parserSetupArg = plan->parserSetupArg;
2544 
2545  /*
2546  * Reparent all the CachedPlanSources into the procedure context. In
2547  * theory this could fail partway through due to the pallocs, but we don't
2548  * care too much since both the procedure context and the executor context
2549  * would go away on error.
2550  */
2551  foreach(lc, plan->plancache_list)
2552  {
2553  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2554 
2555  CachedPlanSetParentContext(plansource, parentcxt);
2556 
2557  /* Build new list, with list cells in plancxt */
2558  newplan->plancache_list = lappend(newplan->plancache_list, plansource);
2559  }
2560 
2561  MemoryContextSwitchTo(oldcxt);
2562 
2563  /* For safety, unlink the CachedPlanSources from the temporary plan */
2564  plan->plancache_list = NIL;
2565 
2566  return newplan;
2567 }
#define NIL
Definition: pg_list.h:69
Oid * argtypes
Definition: spi_priv.h:86
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
unsigned int Oid
Definition: postgres_ext.h:31
void CachedPlanSetParentContext(CachedPlanSource *plansource, MemoryContext newcontext)
Definition: plancache.c:1284
MemoryContext plancxt
Definition: spi_priv.h:83
List * lappend(List *list, void *datum)
Definition: list.c:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
MemoryContext procCxt
Definition: spi_priv.h:31
bool saved
Definition: spi_priv.h:80
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
ParserSetupHook parserSetup
Definition: spi_priv.h:87
bool oneshot
Definition: spi_priv.h:81
void * parserSetupArg
Definition: spi_priv.h:88
void * palloc(Size size)
Definition: mcxt.c:849
struct _SPI_plan * SPIPlanPtr
Definition: spi.h:34
int cursor_options
Definition: spi_priv.h:84
static int _SPI_pquery ( QueryDesc queryDesc,
bool  fire_triggers,
uint64  tcount 
)
static

Definition at line 2275 of file spi.c.

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

Referenced by _SPI_execute_plan().

2276 {
2277  int operation = queryDesc->operation;
2278  int eflags;
2279  int res;
2280 
2281  switch (operation)
2282  {
2283  case CMD_SELECT:
2284  if (queryDesc->dest->mydest != DestSPI)
2285  {
2286  /* Don't return SPI_OK_SELECT if we're discarding result */
2287  res = SPI_OK_UTILITY;
2288  }
2289  else
2290  res = SPI_OK_SELECT;
2291  break;
2292  case CMD_INSERT:
2293  if (queryDesc->plannedstmt->hasReturning)
2295  else
2296  res = SPI_OK_INSERT;
2297  break;
2298  case CMD_DELETE:
2299  if (queryDesc->plannedstmt->hasReturning)
2301  else
2302  res = SPI_OK_DELETE;
2303  break;
2304  case CMD_UPDATE:
2305  if (queryDesc->plannedstmt->hasReturning)
2307  else
2308  res = SPI_OK_UPDATE;
2309  break;
2310  default:
2311  return SPI_ERROR_OPUNKNOWN;
2312  }
2313 
2314 #ifdef SPI_EXECUTOR_STATS
2315  if (ShowExecutorStats)
2316  ResetUsage();
2317 #endif
2318 
2319  /* Select execution options */
2320  if (fire_triggers)
2321  eflags = 0; /* default run-to-completion flags */
2322  else
2323  eflags = EXEC_FLAG_SKIP_TRIGGERS;
2324 
2325  ExecutorStart(queryDesc, eflags);
2326 
2327  ExecutorRun(queryDesc, ForwardScanDirection, tcount, true);
2328 
2329  _SPI_current->processed = queryDesc->estate->es_processed;
2330  _SPI_current->lastoid = queryDesc->estate->es_lastoid;
2331 
2332  if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
2333  queryDesc->dest->mydest == DestSPI)
2334  {
2335  if (_SPI_checktuples())
2336  elog(ERROR, "consistency check on SPI tuple count failed");
2337  }
2338 
2339  ExecutorFinish(queryDesc);
2340  ExecutorEnd(queryDesc);
2341  /* FreeQueryDesc is done by the caller */
2342 
2343 #ifdef SPI_EXECUTOR_STATS
2344  if (ShowExecutorStats)
2345  ShowUsage("SPI EXECUTOR STATS");
2346 #endif
2347 
2348  return res;
2349 }
EState * estate
Definition: execdesc.h:48
Oid es_lastoid
Definition: execnodes.h:475
#define SPI_OK_DELETE_RETURNING
Definition: spi.h:61
Definition: dest.h:93
void ShowUsage(const char *title)
Definition: postgres.c:4395
#define SPI_OK_DELETE
Definition: spi.h:57
CommandDest mydest
Definition: dest.h:128
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:146
#define SPI_ERROR_OPUNKNOWN
Definition: spi.h:38
static _SPI_connection * _SPI_current
Definition: spi.c:45
static bool _SPI_checktuples(void)
Definition: spi.c:2479
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:460
void ResetUsage(void)
Definition: postgres.c:4388
#define ERROR
Definition: elog.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:298
#define SPI_OK_INSERT_RETURNING
Definition: spi.h:60
bool hasReturning
Definition: plannodes.h:49
#define SPI_OK_UTILITY
Definition: spi.h:53
#define SPI_OK_UPDATE_RETURNING
Definition: spi.h:62
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:400
CmdType operation
Definition: execdesc.h:36
#define SPI_OK_SELECT
Definition: spi.h:54
uint64 processed
Definition: spi_priv.h:25
uint64 es_processed
Definition: execnodes.h:474
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:62
DestReceiver * dest
Definition: execdesc.h:41
#define SPI_OK_UPDATE
Definition: spi.h:58
#define SPI_OK_INSERT
Definition: spi.h:56
#define elog
Definition: elog.h:219
PlannedStmt * plannedstmt
Definition: execdesc.h:37
static void _SPI_prepare_oneshot_plan ( const char *  src,
SPIPlanPtr  plan 
)
static

Definition at line 1850 of file spi.c.

References _SPI_error_callback(), ErrorContextCallback::arg, ErrorContextCallback::callback, CreateCommandTag(), CreateOneShotCachedPlan(), error_context_stack, lappend(), lfirst_node, NIL, _SPI_plan::oneshot, pg_parse_query(), _SPI_plan::plancache_list, ErrorContextCallback::previous, and RawStmt::stmt.

Referenced by SPI_execute(), and SPI_execute_with_args().

1851 {
1852  List *raw_parsetree_list;
1853  List *plancache_list;
1854  ListCell *list_item;
1855  ErrorContextCallback spierrcontext;
1856 
1857  /*
1858  * Setup error traceback support for ereport()
1859  */
1860  spierrcontext.callback = _SPI_error_callback;
1861  spierrcontext.arg = (void *) src;
1862  spierrcontext.previous = error_context_stack;
1863  error_context_stack = &spierrcontext;
1864 
1865  /*
1866  * Parse the request string into a list of raw parse trees.
1867  */
1868  raw_parsetree_list = pg_parse_query(src);
1869 
1870  /*
1871  * Construct plancache entries, but don't do parse analysis yet.
1872  */
1873  plancache_list = NIL;
1874 
1875  foreach(list_item, raw_parsetree_list)
1876  {
1877  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
1878  CachedPlanSource *plansource;
1879 
1880  plansource = CreateOneShotCachedPlan(parsetree,
1881  src,
1882  CreateCommandTag(parsetree->stmt));
1883 
1884  plancache_list = lappend(plancache_list, plansource);
1885  }
1886 
1887  plan->plancache_list = plancache_list;
1888  plan->oneshot = true;
1889 
1890  /*
1891  * Pop the error context stack
1892  */
1893  error_context_stack = spierrcontext.previous;
1894 }
#define NIL
Definition: pg_list.h:69
List * plancache_list
Definition: spi_priv.h:82
CachedPlanSource * CreateOneShotCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:235
struct ErrorContextCallback * previous
Definition: elog.h:238
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void _SPI_error_callback(void *arg)
Definition: spi.c:2357
List * pg_parse_query(const char *query_string)
Definition: postgres.c:596
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * stmt
Definition: parsenodes.h:1411
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2036
List * lappend(List *list, void *datum)
Definition: list.c:128
bool oneshot
Definition: spi_priv.h:81
void(* callback)(void *arg)
Definition: elog.h:239
Definition: pg_list.h:45
static void _SPI_prepare_plan ( const char *  src,
SPIPlanPtr  plan 
)
static

Definition at line 1745 of file spi.c.

References _SPI_error_callback(), ErrorContextCallback::arg, _SPI_plan::argtypes, Assert, ErrorContextCallback::callback, CompleteCachedPlan(), CreateCachedPlan(), CreateCommandTag(), _SPI_plan::cursor_options, error_context_stack, lappend(), lfirst_node, _SPI_plan::nargs, NIL, NULL, _SPI_plan::oneshot, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), _SPI_plan::plancache_list, ErrorContextCallback::previous, _SPI_connection::queryEnv, and RawStmt::stmt.

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

1746 {
1747  List *raw_parsetree_list;
1748  List *plancache_list;
1749  ListCell *list_item;
1750  ErrorContextCallback spierrcontext;
1751 
1752  /*
1753  * Setup error traceback support for ereport()
1754  */
1755  spierrcontext.callback = _SPI_error_callback;
1756  spierrcontext.arg = (void *) src;
1757  spierrcontext.previous = error_context_stack;
1758  error_context_stack = &spierrcontext;
1759 
1760  /*
1761  * Parse the request string into a list of raw parse trees.
1762  */
1763  raw_parsetree_list = pg_parse_query(src);
1764 
1765  /*
1766  * Do parse analysis and rule rewrite for each raw parsetree, storing the
1767  * results into unsaved plancache entries.
1768  */
1769  plancache_list = NIL;
1770 
1771  foreach(list_item, raw_parsetree_list)
1772  {
1773  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
1774  List *stmt_list;
1775  CachedPlanSource *plansource;
1776 
1777  /*
1778  * Create the CachedPlanSource before we do parse analysis, since it
1779  * needs to see the unmodified raw parse tree.
1780  */
1781  plansource = CreateCachedPlan(parsetree,
1782  src,
1783  CreateCommandTag(parsetree->stmt));
1784 
1785  /*
1786  * Parameter datatypes are driven by parserSetup hook if provided,
1787  * otherwise we use the fixed parameter list.
1788  */
1789  if (plan->parserSetup != NULL)
1790  {
1791  Assert(plan->nargs == 0);
1792  stmt_list = pg_analyze_and_rewrite_params(parsetree,
1793  src,
1794  plan->parserSetup,
1795  plan->parserSetupArg,
1797  }
1798  else
1799  {
1800  stmt_list = pg_analyze_and_rewrite(parsetree,
1801  src,
1802  plan->argtypes,
1803  plan->nargs,
1805  }
1806 
1807  /* Finish filling in the CachedPlanSource */
1808  CompleteCachedPlan(plansource,
1809  stmt_list,
1810  NULL,
1811  plan->argtypes,
1812  plan->nargs,
1813  plan->parserSetup,
1814  plan->parserSetupArg,
1815  plan->cursor_options,
1816  false); /* not fixed result */
1817 
1818  plancache_list = lappend(plancache_list, plansource);
1819  }
1820 
1821  plan->plancache_list = plancache_list;
1822  plan->oneshot = false;
1823 
1824  /*
1825  * Pop the error context stack
1826  */
1827  error_context_stack = spierrcontext.previous;
1828 }
#define NIL
Definition: pg_list.h:69
Oid * argtypes
Definition: spi_priv.h:86
List * plancache_list
Definition: spi_priv.h:82
static _SPI_connection * _SPI_current
Definition: spi.c:45
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:638
struct ErrorContextCallback * previous
Definition: elog.h:238
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void _SPI_error_callback(void *arg)
Definition: spi.c:2357
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
List * pg_parse_query(const char *query_string)
Definition: postgres.c:596
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * stmt
Definition: parsenodes.h:1411
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:152
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2036
List * lappend(List *list, void *datum)
Definition: list.c:128
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
ParserSetupHook parserSetup
Definition: spi_priv.h:87
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:325
bool oneshot
Definition: spi_priv.h:81
void * parserSetupArg
Definition: spi_priv.h:88
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:675
void(* callback)(void *arg)
Definition: elog.h:239
int cursor_options
Definition: spi_priv.h:84
Definition: pg_list.h:45
static MemoryContext _SPI_procmem ( void  )
static

Definition at line 2440 of file spi.c.

References MemoryContextSwitchTo(), and _SPI_connection::procCxt.

Referenced by _SPI_end_call(), and spi_dest_startup().

2441 {
2443 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
MemoryContext procCxt
Definition: spi_priv.h:31
static SPIPlanPtr _SPI_save_plan ( SPIPlanPtr  plan)
static

Definition at line 2573 of file spi.c.

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, NIL, NULL, _SPI_plan::oneshot, palloc(), _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, _SPI_plan::plancache_list, _SPI_plan::plancxt, SaveCachedPlan(), and _SPI_plan::saved.

Referenced by SPI_saveplan().

2574 {
2575  SPIPlanPtr newplan;
2576  MemoryContext plancxt;
2577  MemoryContext oldcxt;
2578  ListCell *lc;
2579 
2580  /* One-shot plans can't be saved */
2581  Assert(!plan->oneshot);
2582 
2583  /*
2584  * Create a memory context for the plan. We don't expect the plan to be
2585  * very large, so use smaller-than-default alloc parameters. It's a
2586  * transient context until we finish copying everything.
2587  */
2589  "SPI Plan",
2591  oldcxt = MemoryContextSwitchTo(plancxt);
2592 
2593  /* Copy the SPI plan into its own context */
2594  newplan = (SPIPlanPtr) palloc(sizeof(_SPI_plan));
2595  newplan->magic = _SPI_PLAN_MAGIC;
2596  newplan->saved = false;
2597  newplan->oneshot = false;
2598  newplan->plancache_list = NIL;
2599  newplan->plancxt = plancxt;
2600  newplan->cursor_options = plan->cursor_options;
2601  newplan->nargs = plan->nargs;
2602  if (plan->nargs > 0)
2603  {
2604  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
2605  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
2606  }
2607  else
2608  newplan->argtypes = NULL;
2609  newplan->parserSetup = plan->parserSetup;
2610  newplan->parserSetupArg = plan->parserSetupArg;
2611 
2612  /* Copy all the plancache entries */
2613  foreach(lc, plan->plancache_list)
2614  {
2615  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2616  CachedPlanSource *newsource;
2617 
2618  newsource = CopyCachedPlan(plansource);
2619  newplan->plancache_list = lappend(newplan->plancache_list, newsource);
2620  }
2621 
2622  MemoryContextSwitchTo(oldcxt);
2623 
2624  /*
2625  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
2626  * component CachedPlanSources as saved. This sequence cannot fail
2627  * partway through, so there's no risk of long-term memory leakage.
2628  */
2629  newplan->saved = true;
2631 
2632  foreach(lc, newplan->plancache_list)
2633  {
2634  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2635 
2636  SaveCachedPlan(plansource);
2637  }
2638 
2639  return newplan;
2640 }
#define NIL
Definition: pg_list.h:69
Oid * argtypes
Definition: spi_priv.h:86
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:317
int magic
Definition: spi_priv.h:79
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned int Oid
Definition: postgres_ext.h:31
CachedPlanSource * CopyCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:1322
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
MemoryContext plancxt
Definition: spi_priv.h:83
List * lappend(List *list, void *datum)
Definition: list.c:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
bool saved
Definition: spi_priv.h:80
int nargs
Definition: spi_priv.h:85
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:441
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
ParserSetupHook parserSetup
Definition: spi_priv.h:87
bool oneshot
Definition: spi_priv.h:81
void * parserSetupArg
Definition: spi_priv.h:88
void * palloc(Size size)
Definition: mcxt.c:849
struct _SPI_plan * SPIPlanPtr
Definition: spi.h:34
int cursor_options
Definition: spi_priv.h:84
MemoryContext CacheMemoryContext
Definition: mcxt.c:46
void AtEOSubXact_SPI ( bool  isCommit,
SubTransactionId  mySubid 
)

Definition at line 215 of file spi.c.

References _SPI_connected, Assert, _SPI_connection::connectSubid, slist_mutable_iter::cur, ereport, errcode(), errhint(), errmsg(), _SPI_connection::execCxt, InvalidOid, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, next, NULL, _SPI_connection::procCxt, slist_container, slist_delete_current(), slist_foreach_modify, SPI_lastoid, SPI_processed, SPITupleTable::subid, SPITupleTable::tuptabcxt, _SPI_connection::tuptable, _SPI_connection::tuptables, and WARNING.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

216 {
217  bool found = false;
218 
219  while (_SPI_connected >= 0)
220  {
222 
223  if (connection->connectSubid != mySubid)
224  break; /* couldn't be any underneath it either */
225 
226  found = true;
227 
228  /*
229  * Release procedure memory explicitly (see note in SPI_connect)
230  */
231  if (connection->execCxt)
232  {
233  MemoryContextDelete(connection->execCxt);
234  connection->execCxt = NULL;
235  }
236  if (connection->procCxt)
237  {
238  MemoryContextDelete(connection->procCxt);
239  connection->procCxt = NULL;
240  }
241 
242  /*
243  * Pop the stack entry and reset global variables. Unlike
244  * SPI_finish(), we don't risk switching to memory contexts that might
245  * be already gone.
246  */
247  _SPI_connected--;
248  if (_SPI_connected < 0)
249  _SPI_current = NULL;
250  else
252  SPI_processed = 0;
254  SPI_tuptable = NULL;
255  }
256 
257  if (found && isCommit)
259  (errcode(ERRCODE_WARNING),
260  errmsg("subtransaction left non-empty SPI stack"),
261  errhint("Check for missing \"SPI_finish\" calls.")));
262 
263  /*
264  * If we are aborting a subtransaction and there is an open SPI context
265  * surrounding the subxact, clean up to prevent memory leakage.
266  */
267  if (_SPI_current && !isCommit)
268  {
269  slist_mutable_iter siter;
270 
271  /* free Executor memory the same as _SPI_end_call would do */
273 
274  /* throw away any tuple tables created within current subxact */
276  {
277  SPITupleTable *tuptable;
278 
279  tuptable = slist_container(SPITupleTable, next, siter.cur);
280  if (tuptable->subid >= mySubid)
281  {
282  /*
283  * If we used SPI_freetuptable() here, its internal search of
284  * the tuptables list would make this operation O(N^2).
285  * Instead, just free the tuptable manually. This should
286  * match what SPI_freetuptable() does.
287  */
288  slist_delete_current(&siter);
289  if (tuptable == _SPI_current->tuptable)
291  if (tuptable == SPI_tuptable)
292  SPI_tuptable = NULL;
293  MemoryContextDelete(tuptable->tuptabcxt);
294  }
295  }
296  /* in particular we should have gotten rid of any in-progress table */
298  }
299 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
int errhint(const char *fmt,...)
Definition: elog.c:987
static int32 next
Definition: blutils.c:210
slist_node * cur
Definition: ilist.h:241
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
static int _SPI_connected
Definition: spi.c:47
static _SPI_connection * _SPI_current
Definition: spi.c:45
uint64 SPI_processed
Definition: spi.c:39
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
SubTransactionId connectSubid
Definition: spi_priv.h:34
SPITupleTable * tuptable
Definition: spi_priv.h:27
static _SPI_connection * _SPI_stack
Definition: spi.c:44
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
MemoryContext procCxt
Definition: spi_priv.h:31
Oid SPI_lastoid
Definition: spi.c:40
MemoryContext execCxt
Definition: spi_priv.h:32
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:652
SubTransactionId subid
Definition: spi.h:30
slist_head tuptables
Definition: spi_priv.h:30
MemoryContext tuptabcxt
Definition: spi.h:24
void AtEOXact_SPI ( bool  isCommit)

Definition at line 187 of file spi.c.

References _SPI_connected, _SPI_stack_depth, ereport, errcode(), errhint(), errmsg(), InvalidOid, NULL, SPI_lastoid, SPI_processed, and WARNING.

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

188 {
189  /*
190  * Note that memory contexts belonging to SPI stack entries will be freed
191  * automatically, so we can ignore them here. We just need to restore our
192  * static variables to initial state.
193  */
194  if (isCommit && _SPI_connected != -1)
196  (errcode(ERRCODE_WARNING),
197  errmsg("transaction left non-empty SPI stack"),
198  errhint("Check for missing \"SPI_finish\" calls.")));
199 
201  _SPI_stack_depth = 0;
202  _SPI_connected = -1;
203  SPI_processed = 0;
205  SPI_tuptable = NULL;
206 }
int errhint(const char *fmt,...)
Definition: elog.c:987
static int _SPI_stack_depth
Definition: spi.c:46
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
static int _SPI_connected
Definition: spi.c:47
static _SPI_connection * _SPI_current
Definition: spi.c:45
uint64 SPI_processed
Definition: spi.c:39
static _SPI_connection * _SPI_stack
Definition: spi.c:44
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
Oid SPI_lastoid
Definition: spi.c:40
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
int SPI_connect ( void  )

Definition at line 84 of file spi.c.

References _SPI_connected, _SPI_stack_depth, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Assert, _SPI_connection::connectSubid, elog, ERROR, _SPI_connection::execCxt, GetCurrentSubTransactionId(), InvalidOid, _SPI_connection::lastoid, MemoryContextAlloc(), MemoryContextSwitchTo(), NULL, _SPI_connection::procCxt, _SPI_connection::processed, _SPI_connection::queryEnv, repalloc(), _SPI_connection::savedcxt, slist_init(), SPI_OK_CONNECT, TopTransactionContext, _SPI_connection::tuptable, and _SPI_connection::tuptables.

Referenced by check_foreign_key(), check_primary_key(), connectby(), crosstab(), cursor_to_xml(), cursor_to_xmlschema(), database_to_xml_internal(), database_to_xmlschema_internal(), funny_dup17(), 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(), plpython_call_handler(), plpython_inline_handler(), pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_trigger_handler(), 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_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), ri_restrict_upd(), schema_to_xml_internal(), schema_to_xmlschema_internal(), timetravel(), ts_stat1(), ts_stat2(), tsquery_rewrite_query(), ttdummy(), and xpath_table().

85 {
86  int newdepth;
87 
88  /* Enlarge stack if necessary */
89  if (_SPI_stack == NULL)
90  {
91  if (_SPI_connected != -1 || _SPI_stack_depth != 0)
92  elog(ERROR, "SPI stack corrupted");
93  newdepth = 16;
96  newdepth * sizeof(_SPI_connection));
97  _SPI_stack_depth = newdepth;
98  }
99  else
100  {
102  elog(ERROR, "SPI stack corrupted");
103  if (_SPI_stack_depth == _SPI_connected + 1)
104  {
105  newdepth = _SPI_stack_depth * 2;
108  newdepth * sizeof(_SPI_connection));
109  _SPI_stack_depth = newdepth;
110  }
111  }
112 
113  /* Enter new stack level */
114  _SPI_connected++;
116 
118  _SPI_current->processed = 0;
122  _SPI_current->procCxt = NULL; /* in case we fail to create 'em */
126 
127  /*
128  * Create memory contexts for this procedure
129  *
130  * XXX it would be better to use PortalContext as the parent context, but
131  * we may not be inside a portal (consider deferred-trigger execution).
132  * Perhaps CurTransactionContext would do? For now it doesn't matter
133  * because we clean up explicitly in AtEOSubXact_SPI().
134  */
136  "SPI Proc",
139  "SPI Exec",
141  /* ... and switch to procedure's context */
143 
144  return SPI_OK_CONNECT;
145 }
#define SPI_OK_CONNECT
Definition: spi.h:50
MemoryContext TopTransactionContext
Definition: mcxt.c:48
static int _SPI_stack_depth
Definition: spi.c:46
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static int _SPI_connected
Definition: spi.c:47
static _SPI_connection * _SPI_current
Definition: spi.c:45
SubTransactionId connectSubid
Definition: spi_priv.h:34
static void slist_init(slist_head *head)
Definition: ilist.h:554
#define ERROR
Definition: elog.h:43
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
SPITupleTable * tuptable
Definition: spi_priv.h:27
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
static _SPI_connection * _SPI_stack
Definition: spi.c:44
MemoryContext savedcxt
Definition: spi_priv.h:33
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
MemoryContext procCxt
Definition: spi_priv.h:31
MemoryContext execCxt
Definition: spi_priv.h:32
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
uint64 processed
Definition: spi_priv.h:25
#define Assert(condition)
Definition: c.h:675
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:649
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
#define elog
Definition: elog.h:219
slist_head tuptables
Definition: spi_priv.h:30
HeapTuple SPI_copytuple ( HeapTuple  tuple)

Definition at line 631 of file spi.c.

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

Referenced by get_tuple_of_interest(), and plpgsql_exec_trigger().

632 {
633  MemoryContext oldcxt;
634  HeapTuple ctuple;
635 
636  if (tuple == NULL)
637  {
639  return NULL;
640  }
641 
642  if (_SPI_current == NULL)
643  {
645  return NULL;
646  }
647 
649 
650  ctuple = heap_copytuple(tuple);
651 
652  MemoryContextSwitchTo(oldcxt);
653 
654  return ctuple;
655 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
MemoryContext savedcxt
Definition: spi_priv.h:33
#define NULL
Definition: c.h:229
void SPI_cursor_close ( Portal  portal)

Definition at line 1403 of file spi.c.

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

Referenced by exec_stmt_close(), exec_stmt_dynfors(), exec_stmt_forc(), exec_stmt_fors(), exec_stmt_return_query(), 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().

1404 {
1405  if (!PortalIsValid(portal))
1406  elog(ERROR, "invalid portal in SPI cursor operation");
1407 
1408  PortalDrop(portal, false);
1409 }
#define ERROR
Definition: elog.h:43
#define PortalIsValid(p)
Definition: portal.h:199
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:461
#define elog
Definition: elog.h:219
void SPI_cursor_fetch ( Portal  portal,
bool  forward,
long  count 
)

Definition at line 1347 of file spi.c.

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

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

1348 {
1349  _SPI_cursor_operation(portal,
1350  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1352  /* we know that the DestSPI receiver doesn't need a destroy call */
1353 }
Definition: dest.h:93
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:2383
Portal SPI_cursor_find ( const char *  name)

Definition at line 1335 of file spi.c.

References GetPortalByName().

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().

1336 {
1337  return GetPortalByName(name);
1338 }
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
const char * name
Definition: encode.c:521
void SPI_cursor_move ( Portal  portal,
bool  forward,
long  count 
)

Definition at line 1362 of file spi.c.

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

1363 {
1364  _SPI_cursor_operation(portal,
1365  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1366  None_Receiver);
1367 }
DestReceiver * None_Receiver
Definition: dest.c:91
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:2383
Portal SPI_cursor_open ( const char *  name,
SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
bool  read_only 
)

Definition at line 1029 of file spi.c.

References _SPI_convert_params(), _SPI_plan::argtypes, _SPI_plan::nargs, pfree(), 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().

1032 {
1033  Portal portal;
1034  ParamListInfo paramLI;
1035 
1036  /* build transient ParamListInfo in caller's context */
1037  paramLI = _SPI_convert_params(plan->nargs, plan->argtypes,
1038  Values, Nulls);
1039 
1040  portal = SPI_cursor_open_internal(name, plan, paramLI, read_only);
1041 
1042  /* done with the transient ParamListInfo */
1043  if (paramLI)
1044  pfree(paramLI);
1045 
1046  return portal;
1047 }
Oid * argtypes
Definition: spi_priv.h:86
void pfree(void *pointer)
Definition: mcxt.c:950
int nargs
Definition: spi_priv.h:85
const char * name
Definition: encode.c:521
static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
Definition: spi.c:1121
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2240
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
static Portal SPI_cursor_open_internal ( const char *  name,
SPIPlanPtr  plan,
ParamListInfo  paramLI,
bool  read_only 
)
static

Definition at line 1121 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_error_callback(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CMD_UTILITY, CommandCounterIncrement(), CommandIsReadOnly(), CachedPlanSource::commandTag, copyObject, copyParamList(), CreateCommandTag(), CreateNewPortal(), CreatePortal(), CURSOR_OPT_NO_SCROLL, CURSOR_OPT_SCROLL, _SPI_plan::cursor_options, PortalData::cursorOptions, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, error_context_stack, ExecSupportsBackwardScan(), GetActiveSnapshot(), GetCachedPlan(), GetTransactionSnapshot(), IsInParallelMode(), lfirst_node, linitial, linitial_node, list_length(), MemoryContextStrdup(), MemoryContextSwitchTo(), NIL, NULL, _SPI_plan::plancache_list, PORTAL_MULTI_QUERY, PortalDefineQuery(), PortalGetHeapMemory, PortalStart(), PreventCommandIfParallelMode(), ErrorContextCallback::previous, _SPI_connection::processed, CachedPlanSource::query_string, _SPI_connection::queryEnv, PortalData::queryEnv, ReleaseCachedPlan(), _SPI_plan::saved, SPI_is_cursor_plan(), SPI_processed, CachedPlan::stmt_list, PortalData::strategy, and _SPI_connection::tuptable.

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

1123 {
1124  CachedPlanSource *plansource;
1125  CachedPlan *cplan;
1126  List *stmt_list;
1127  char *query_string;
1128  Snapshot snapshot;
1129  MemoryContext oldcontext;
1130  Portal portal;
1131  ErrorContextCallback spierrcontext;
1132 
1133  /*
1134  * Check that the plan is something the Portal code will special-case as
1135  * returning one tupleset.
1136  */
1137  if (!SPI_is_cursor_plan(plan))
1138  {
1139  /* try to give a good error message */
1140  if (list_length(plan->plancache_list) != 1)
1141  ereport(ERROR,
1142  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1143  errmsg("cannot open multi-query plan as cursor")));
1144  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1145  ereport(ERROR,
1146  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1147  /* translator: %s is name of a SQL command, eg INSERT */
1148  errmsg("cannot open %s query as cursor",
1149  plansource->commandTag)));
1150  }
1151 
1152  Assert(list_length(plan->plancache_list) == 1);
1153  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1154 
1155  /* Push the SPI stack */
1156  if (_SPI_begin_call(true) < 0)
1157  elog(ERROR, "SPI_cursor_open called while not connected");
1158 
1159  /* Reset SPI result (note we deliberately don't touch lastoid) */
1160  SPI_processed = 0;
1161  SPI_tuptable = NULL;
1162  _SPI_current->processed = 0;
1164 
1165  /* Create the portal */
1166  if (name == NULL || name[0] == '\0')
1167  {
1168  /* Use a random nonconflicting name */
1169  portal = CreateNewPortal();
1170  }
1171  else
1172  {
1173  /* In this path, error if portal of same name already exists */
1174  portal = CreatePortal(name, false, false);
1175  }
1176 
1177  /* Copy the plan's query string into the portal */
1178  query_string = MemoryContextStrdup(PortalGetHeapMemory(portal),
1179  plansource->query_string);
1180 
1181  /*
1182  * Setup error traceback support for ereport(), in case GetCachedPlan
1183  * throws an error.
1184  */
1185  spierrcontext.callback = _SPI_error_callback;
1186  spierrcontext.arg = (void *) plansource->query_string;
1187  spierrcontext.previous = error_context_stack;
1188  error_context_stack = &spierrcontext;
1189 
1190  /*
1191  * Note: for a saved plan, we mustn't have any failure occur between
1192  * GetCachedPlan and PortalDefineQuery; that would result in leaking our
1193  * plancache refcount.
1194  */
1195 
1196  /* Replan if needed, and increment plan refcount for portal */
1197  cplan = GetCachedPlan(plansource, paramLI, false, _SPI_current->queryEnv);
1198  stmt_list = cplan->stmt_list;
1199 
1200  if (!plan->saved)
1201  {
1202  /*
1203  * We don't want the portal to depend on an unsaved CachedPlanSource,
1204  * so must copy the plan into the portal's context. An error here
1205  * will result in leaking our refcount on the plan, but it doesn't
1206  * matter because the plan is unsaved and hence transient anyway.
1207  */
1208  oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1209  stmt_list = copyObject(stmt_list);
1210  MemoryContextSwitchTo(oldcontext);
1211  ReleaseCachedPlan(cplan, false);
1212  cplan = NULL; /* portal shouldn't depend on cplan */
1213  }
1214 
1215  /*
1216  * Set up the portal.
1217  */
1218  PortalDefineQuery(portal,
1219  NULL, /* no statement name */
1220  query_string,
1221  plansource->commandTag,
1222  stmt_list,
1223  cplan);
1224 
1225  /*
1226  * Set up options for portal. Default SCROLL type is chosen the same way
1227  * as PerformCursorOpen does it.
1228  */
1229  portal->cursorOptions = plan->cursor_options;
1231  {
1232  if (list_length(stmt_list) == 1 &&
1233  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1234  linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
1235  ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
1236  portal->cursorOptions |= CURSOR_OPT_SCROLL;
1237  else
1239  }
1240 
1241  /*
1242  * Disallow SCROLL with SELECT FOR UPDATE. This is not redundant with the
1243  * check in transformDeclareCursorStmt because the cursor options might
1244  * not have come through there.
1245  */
1246  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
1247  {
1248  if (list_length(stmt_list) == 1 &&
1249  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1250  linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
1251  ereport(ERROR,
1252  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1253  errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1254  errdetail("Scrollable cursors must be READ ONLY.")));
1255  }
1256 
1257  /* Make current query environment available to portal at execution time. */
1258  portal->queryEnv = _SPI_current->queryEnv;
1259 
1260  /*
1261  * If told to be read-only, or in parallel mode, verify that this query is
1262  * in fact read-only. This can't be done earlier because we need to look
1263  * at the finished, planned queries. (In particular, we don't want to do
1264  * it between GetCachedPlan and PortalDefineQuery, because throwing an
1265  * error between those steps would result in leaking our plancache
1266  * refcount.)
1267  */
1268  if (read_only || IsInParallelMode())
1269  {
1270  ListCell *lc;
1271 
1272  foreach(lc, stmt_list)
1273  {
1274  PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
1275 
1276  if (!CommandIsReadOnly(pstmt))
1277  {
1278  if (read_only)
1279  ereport(ERROR,
1280  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1281  /* translator: %s is a SQL statement name */
1282  errmsg("%s is not allowed in a non-volatile function",
1283  CreateCommandTag((Node *) pstmt))));
1284  else
1286  }
1287  }
1288  }
1289 
1290  /* Set up the snapshot to use. */
1291  if (read_only)
1292  snapshot = GetActiveSnapshot();
1293  else
1294  {
1296  snapshot = GetTransactionSnapshot();
1297  }
1298 
1299  /*
1300  * If the plan has parameters, copy them into the portal. Note that this
1301  * must be done after revalidating the plan, because in dynamic parameter
1302  * cases the set of parameters could have changed during re-parsing.
1303  */
1304  if (paramLI)
1305  {
1306  oldcontext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1307  paramLI = copyParamList(paramLI);
1308  MemoryContextSwitchTo(oldcontext);
1309  }
1310 
1311  /*
1312  * Start portal execution.
1313  */
1314  PortalStart(portal, paramLI, 0, snapshot);
1315 
1316  Assert(portal->strategy != PORTAL_MULTI_QUERY);
1317 
1318  /* Pop the error context stack */
1319  error_context_stack = spierrcontext.previous;
1320 
1321  /* Pop the SPI stack */
1322  _SPI_end_call(true);
1323 
1324  /* Return the created portal */
1325  return portal;
1326 }
ParamListInfo copyParamList(ParamListInfo from)
Definition: params.c:36
#define NIL
Definition: pg_list.h:69
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:97
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:174
List * plancache_list
Definition: spi_priv.h:82
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1135
Portal CreateNewPortal(void)
Definition: portalmem.c:230
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:445
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:277
bool SPI_is_cursor_plan(SPIPlanPtr plan)
Definition: spi.c:1451
const char * commandTag
Definition: plancache.h:85
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
SPITupleTable * SPI_tuptable
Definition: spi.c:41
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define linitial_node(type, l)
Definition: pg_list.h:114
struct ErrorContextCallback * previous
Definition: elog.h:238
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2616
uint64 SPI_processed
Definition: spi.c:39
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void _SPI_error_callback(void *arg)
Definition: spi.c:2357
bool IsInParallelMode(void)
Definition: xact.c:913
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
SPITupleTable * tuptable
Definition: spi_priv.h:27
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
int errdetail(const char *fmt,...)
Definition: elog.c:873
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1256
PortalStrategy strategy
Definition: portal.h:143
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2036
void CommandCounterIncrement(void)
Definition: xact.c:922
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:457
bool saved
Definition: spi_priv.h:80
#define NULL
Definition: c.h:229
uint64 processed
Definition: spi_priv.h:25
#define Assert(condition)
Definition: c.h:675
const char * query_string
Definition: plancache.h:84
static int list_length(const List *l)
Definition: pg_list.h:89
#define PortalGetHeapMemory(portal)
Definition: portal.h:205
const char * name
Definition: encode.c:521
QueryEnvironment * queryEnv
Definition: portal.h:140
void(* callback)(void *arg)
Definition: elog.h:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1064
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2615
List * stmt_list
Definition: plancache.h:133
int cursor_options
Definition: spi_priv.h:84
#define elog
Definition: elog.h:219
int cursorOptions
Definition: portal.h:144
#define copyObject(obj)
Definition: nodes.h:622
Definition: pg_list.h:45
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
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 1056 of file spi.c.

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), _SPI_plan::argtypes, _SPI_plan::cursor_options, elog, ERROR, _SPI_plan::magic, _SPI_plan::nargs, NULL, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, result, SPI_cursor_open_internal(), and SPI_result.

Referenced by exec_dynquery_with_params().

1061 {
1062  Portal result;
1063  _SPI_plan plan;
1064  ParamListInfo paramLI;
1065 
1066  if (src == NULL || nargs < 0)
1067  elog(ERROR, "SPI_cursor_open_with_args called with invalid arguments");
1068 
1069  if (nargs > 0 && (argtypes == NULL || Values == NULL))
1070  elog(ERROR, "SPI_cursor_open_with_args called with missing parameters");
1071 
1072  SPI_result = _SPI_begin_call(true);
1073  if (SPI_result < 0)
1074  elog(ERROR, "SPI_cursor_open_with_args called while not connected");
1075 
1076  memset(&plan, 0, sizeof(_SPI_plan));
1077  plan.magic = _SPI_PLAN_MAGIC;
1078  plan.cursor_options = cursorOptions;
1079  plan.nargs = nargs;
1080  plan.argtypes = argtypes;
1081  plan.parserSetup = NULL;
1082  plan.parserSetupArg = NULL;
1083 
1084  /* build transient ParamListInfo in executor context */
1085  paramLI = _SPI_convert_params(nargs, argtypes,
1086  Values, Nulls);
1087 
1088  _SPI_prepare_plan(src, &plan);
1089 
1090  /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1091 
1092  result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
1093 
1094  /* And clean up */
1095  _SPI_end_call(true);
1096 
1097  return result;
1098 }
static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1745
Oid * argtypes
Definition: spi_priv.h:86
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
return result
Definition: formatting.c:1632
int SPI_result
Definition: spi.c:42
#define ERROR
Definition: elog.h:43
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
ParserSetupHook parserSetup
Definition: spi_priv.h:87
void * parserSetupArg
Definition: spi_priv.h:88
const char * name
Definition: encode.c:521
static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
Definition: spi.c:1121
int cursor_options
Definition: spi_priv.h:84
#define elog
Definition: elog.h:219
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2240
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
Portal SPI_cursor_open_with_paramlist ( const char *  name,
SPIPlanPtr  plan,
ParamListInfo  params,
bool  read_only 
)

Definition at line 1108 of file spi.c.

References SPI_cursor_open_internal().

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

1110 {
1111  return SPI_cursor_open_internal(name, plan, params, read_only);
1112 }
const char * name
Definition: encode.c:521
static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
Definition: spi.c:1121
Datum SPI_datumTransfer ( Datum  value,
bool  typByVal,
int  typLen 
)

Definition at line 945 of file spi.c.

References datumTransfer(), elog, ERROR, MemoryContextSwitchTo(), NULL, result, and _SPI_connection::savedcxt.

Referenced by plpgsql_exec_function().

946 {
947  MemoryContext oldcxt;
948  Datum result;
949 
950  if (_SPI_current == NULL)
951  elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
952 
954 
955  result = datumTransfer(value, typByVal, typLen);
956 
957  MemoryContextSwitchTo(oldcxt);
958 
959  return result;
960 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
return result
Definition: formatting.c:1632
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define ERROR
Definition: elog.h:43
static struct @121 value
MemoryContext savedcxt
Definition: spi_priv.h:33
uintptr_t Datum
Definition: postgres.h:372
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:190
#define NULL
Definition: c.h:229
#define elog
Definition: elog.h:219
void spi_dest_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)

Definition at line 1649 of file spi.c.

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

1650 {
1651  SPITupleTable *tuptable;
1652  MemoryContext oldcxt;
1653  MemoryContext tuptabcxt;
1654 
1655  if (_SPI_current == NULL)
1656  elog(ERROR, "spi_dest_startup called while not connected to SPI");
1657 
1658  if (_SPI_current->tuptable != NULL)
1659  elog(ERROR, "improper call to spi_dest_startup");
1660 
1661  /* We create the tuple table context as a child of procCxt */
1662 
1663  oldcxt = _SPI_procmem(); /* switch to procedure memory context */
1664 
1666  "SPI TupTable",
1668  MemoryContextSwitchTo(tuptabcxt);
1669 
1670  _SPI_current->tuptable = tuptable = (SPITupleTable *)
1671  palloc0(sizeof(SPITupleTable));
1672  tuptable->tuptabcxt = tuptabcxt;
1673  tuptable->subid = GetCurrentSubTransactionId();
1674 
1675  /*
1676  * The tuptable is now valid enough to be freed by AtEOSubXact_SPI, so put
1677  * it onto the SPI context's tuptables list. This will ensure it's not
1678  * leaked even in the unlikely event the following few lines fail.
1679  */
1680  slist_push_head(&_SPI_current->tuptables, &tuptable->next);
1681 
1682  /* set up initial allocations */
1683  tuptable->alloced = tuptable->free = 128;
1684  tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
1685  tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
1686 
1687  MemoryContextSwitchTo(oldcxt);
1688 }
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:574
slist_node next
Definition: spi.h:29
static _SPI_connection * _SPI_current
Definition: spi.c:45
HeapTuple * vals
Definition: spi.h:28
#define ERROR
Definition: elog.h:43
SPITupleTable * tuptable
Definition: spi_priv.h:27
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:878
TupleDesc tupdesc
Definition: spi.h:27
#define NULL
Definition: c.h:229
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:649
uint64 free
Definition: spi.h:26
void * palloc(Size size)
Definition: mcxt.c:849
uint64 alloced
Definition: spi.h:25
#define elog
Definition: elog.h:219
static MemoryContext _SPI_procmem(void)
Definition: spi.c:2440
SubTransactionId subid
Definition: spi.h:30
slist_head tuptables
Definition: spi_priv.h:30
MemoryContext tuptabcxt
Definition: spi.h:24
int SPI_exec ( const char *  src,
long  tcount 
)

Definition at line 332 of file spi.c.

References SPI_execute().

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

333 {
334  return SPI_execute(src, false, tcount);
335 }
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:304
int SPI_execp ( SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
long  tcount 
)

Definition at line 366 of file spi.c.

References SPI_execute_plan().

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

367 {
368  return SPI_execute_plan(plan, Values, Nulls, false, tcount);
369 }
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:339
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
int SPI_execute ( const char *  src,
bool  read_only,
long  tcount 
)

Definition at line 304 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_prepare_oneshot_plan(), CURSOR_OPT_PARALLEL_OK, _SPI_plan::cursor_options, InvalidSnapshot, _SPI_plan::magic, NULL, and SPI_ERROR_ARGUMENT.

Referenced by build_tuplestore_recursively(), crosstab(), exec_stmt_dynexecute(), 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(), and SPI_exec().

305 {
306  _SPI_plan plan;
307  int res;
308 
309  if (src == NULL || tcount < 0)
310  return SPI_ERROR_ARGUMENT;
311 
312  res = _SPI_begin_call(true);
313  if (res < 0)
314  return res;
315 
316  memset(&plan, 0, sizeof(_SPI_plan));
317  plan.magic = _SPI_PLAN_MAGIC;
319 
320  _SPI_prepare_oneshot_plan(src, &plan);
321 
322  res = _SPI_execute_plan(&plan, NULL,
324  read_only, true, tcount);
325 
326  _SPI_end_call(true);
327  return res;
328 }
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1850
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:1908
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define InvalidSnapshot
Definition: snapshot.h:25
#define NULL
Definition: c.h:229
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2623
int cursor_options
Definition: spi_priv.h:84
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
int SPI_execute_plan ( SPIPlanPtr  plan,
Datum Values,
const char *  Nulls,
bool  read_only,
long  tcount 
)

Definition at line 339 of file spi.c.

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_plan::argtypes, InvalidSnapshot, _SPI_plan::magic, _SPI_plan::nargs, NULL, 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(), and SPI_execp().

341 {
342  int res;
343 
344  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
345  return SPI_ERROR_ARGUMENT;
346 
347  if (plan->nargs > 0 && Values == NULL)
348  return SPI_ERROR_PARAM;
349 
350  res = _SPI_begin_call(true);
351  if (res < 0)
352  return res;
353 
354  res = _SPI_execute_plan(plan,
355  _SPI_convert_params(plan->nargs, plan->argtypes,
356  Values, Nulls),
358  read_only, true, tcount);
359 
360  _SPI_end_call(true);
361  return res;
362 }
Oid * argtypes
Definition: spi_priv.h:86
#define SPI_ERROR_PARAM
Definition: spi.h:42
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:1908
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define InvalidSnapshot
Definition: snapshot.h:25
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2240
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
int SPI_execute_plan_with_paramlist ( SPIPlanPtr  plan,
ParamListInfo  params,
bool  read_only,
long  tcount 
)

Definition at line 373 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, InvalidSnapshot, _SPI_plan::magic, NULL, and SPI_ERROR_ARGUMENT.

Referenced by exec_run_select(), and exec_stmt_execsql().

375 {
376  int res;
377 
378  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
379  return SPI_ERROR_ARGUMENT;
380 
381  res = _SPI_begin_call(true);
382  if (res < 0)
383  return res;
384 
385  res = _SPI_execute_plan(plan, params,
387  read_only, true, tcount);
388 
389  _SPI_end_call(true);
390  return res;
391 }
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:1908
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define InvalidSnapshot
Definition: snapshot.h:25
#define NULL
Definition: c.h:229
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
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 407 of file spi.c.

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_plan::argtypes, _SPI_plan::magic, _SPI_plan::nargs, NULL, SPI_ERROR_ARGUMENT, and SPI_ERROR_PARAM.

Referenced by RI_Initial_Check(), and ri_PerformCheck().

411 {
412  int res;
413 
414  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
415  return SPI_ERROR_ARGUMENT;
416 
417  if (plan->nargs > 0 && Values == NULL)
418  return SPI_ERROR_PARAM;
419 
420  res = _SPI_begin_call(true);
421  if (res < 0)
422  return res;
423 
424  res = _SPI_execute_plan(plan,
425  _SPI_convert_params(plan->nargs, plan->argtypes,
426  Values, Nulls),
427  snapshot, crosscheck_snapshot,
428  read_only, fire_triggers, tcount);
429 
430  _SPI_end_call(true);
431  return res;
432 }
Oid * argtypes
Definition: spi_priv.h:86
#define SPI_ERROR_PARAM
Definition: spi.h:42
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:1908
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2240
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
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 441 of file spi.c.

References _SPI_begin_call(), _SPI_convert_params(), _SPI_end_call(), _SPI_execute_plan(), _SPI_PLAN_MAGIC, _SPI_prepare_oneshot_plan(), _SPI_plan::argtypes, CURSOR_OPT_PARALLEL_OK, _SPI_plan::cursor_options, InvalidSnapshot, _SPI_plan::magic, _SPI_plan::nargs, NULL, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, SPI_ERROR_ARGUMENT, and SPI_ERROR_PARAM.

Referenced by exec_stmt_dynexecute().

445 {
446  int res;
447  _SPI_plan plan;
448  ParamListInfo paramLI;
449 
450  if (src == NULL || nargs < 0 || tcount < 0)
451  return SPI_ERROR_ARGUMENT;
452 
453  if (nargs > 0 && (argtypes == NULL || Values == NULL))
454  return SPI_ERROR_PARAM;
455 
456  res = _SPI_begin_call(true);
457  if (res < 0)
458  return res;
459 
460  memset(&plan, 0, sizeof(_SPI_plan));
461  plan.magic = _SPI_PLAN_MAGIC;
463  plan.nargs = nargs;
464  plan.argtypes = argtypes;
465  plan.parserSetup = NULL;
466  plan.parserSetupArg = NULL;
467 
468  paramLI = _SPI_convert_params(nargs, argtypes,
469  Values, Nulls);
470 
471  _SPI_prepare_oneshot_plan(src, &plan);
472 
473  res = _SPI_execute_plan(&plan, paramLI,
475  read_only, true, tcount);
476 
477  _SPI_end_call(true);
478  return res;
479 }
Oid * argtypes
Definition: spi_priv.h:86
#define SPI_ERROR_PARAM
Definition: spi.h:42
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1850
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:1908
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define InvalidSnapshot
Definition: snapshot.h:25
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
ParserSetupHook parserSetup
Definition: spi_priv.h:87
void * parserSetupArg
Definition: spi_priv.h:88
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2623
int cursor_options
Definition: spi_priv.h:84
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2240
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
int SPI_finish ( void  )

Definition at line 148 of file spi.c.

References _SPI_begin_call(), _SPI_connected, _SPI_connection::execCxt, InvalidOid, MemoryContextDelete(), MemoryContextSwitchTo(), NULL, _SPI_connection::procCxt, _SPI_connection::savedcxt, SPI_lastoid, SPI_OK_FINISH, and SPI_processed.

Referenced by check_foreign_key(), check_primary_key(), connectby(), crosstab(), cursor_to_xml(), cursor_to_xmlschema(), database_to_xml_internal(), database_to_xmlschema_internal(), funny_dup17(), 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(), 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_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), RI_Initial_Check(), ri_restrict_del(), ri_restrict_upd(), schema_to_xml_internal(), schema_to_xmlschema_internal(), timetravel(), ts_stat1(), ts_stat2(), tsquery_rewrite_query(), ttdummy(), and xpath_table().

149 {
150  int res;
151 
152  res = _SPI_begin_call(false); /* live in procedure memory */
153  if (res < 0)
154  return res;
155 
156  /* Restore memory context as it was before procedure call */
158 
159  /* Release memory used in procedure call (including tuptables) */
164 
165  /*
166  * Reset result variables, especially SPI_tuptable which is probably
167  * pointing at a just-deleted tuptable
168  */
169  SPI_processed = 0;
171  SPI_tuptable = NULL;
172 
173  /* Exit stack level */
174  _SPI_connected--;
175  if (_SPI_connected < 0)
176  _SPI_current = NULL;
177  else
179 
180  return SPI_OK_FINISH;
181 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SPITupleTable * SPI_tuptable
Definition: spi.c:41
static int _SPI_connected
Definition: spi.c:47
static _SPI_connection * _SPI_current
Definition: spi.c:45
uint64 SPI_processed
Definition: spi.c:39
static _SPI_connection * _SPI_stack
Definition: spi.c:44
MemoryContext savedcxt
Definition: spi_priv.h:33
MemoryContext procCxt
Definition: spi_priv.h:31
Oid SPI_lastoid
Definition: spi.c:40
MemoryContext execCxt
Definition: spi_priv.h:32
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define SPI_OK_FINISH
Definition: spi.h:51
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
char* SPI_fname ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 782 of file spi.c.

References tupleDesc::attrs, FirstLowInvalidHeapAttributeNumber, NameStr, tupleDesc::natts, NULL, pstrdup(), SPI_ERROR_NOATTRIBUTE, SPI_result, and SystemAttributeDefinition().

Referenced by funny_dup17(), get_pkey_attnames(), ri_ReportViolation(), and SPI_sql_row_to_xmlelement().

783 {
784  Form_pg_attribute att;
785 
786  SPI_result = 0;
787 
788  if (fnumber > tupdesc->natts || fnumber == 0 ||
790  {
792  return NULL;
793  }
794 
795  if (fnumber > 0)
796  att = tupdesc->attrs[fnumber - 1];
797  else
798  att = SystemAttributeDefinition(fnumber, true);
799 
800  return pstrdup(NameStr(att->attname));
801 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
int natts
Definition: tupdesc.h:73
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define NULL
Definition: c.h:229
#define NameStr(name)
Definition: c.h:499
int SPI_fnumber ( TupleDesc  tupdesc,
const char *  fname 
)

Definition at line 761 of file spi.c.

References tupleDesc::attrs, namestrcmp(), tupleDesc::natts, NULL, SPI_ERROR_NOATTRIBUTE, and SystemAttributeByName().

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

762 {
763  int res;
764  Form_pg_attribute sysatt;
765 
766  for (res = 0; res < tupdesc->natts; res++)
767  {
768  if (namestrcmp(&tupdesc->attrs[res]->attname, fname) == 0 &&
769  !tupdesc->attrs[res]->attisdropped)
770  return res + 1;
771  }
772 
773  sysatt = SystemAttributeByName(fname, true /* "oid" will be accepted */ );
774  if (sysatt != NULL)
775  return sysatt->attnum;
776 
777  /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
778  return SPI_ERROR_NOATTRIBUTE;
779 }
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:214
int namestrcmp(Name name, const char *str)
Definition: name.c:247
int natts
Definition: tupdesc.h:73
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define NULL
Definition: c.h:229
int SPI_freeplan ( SPIPlanPtr  plan)

Definition at line 609 of file spi.c.

References _SPI_PLAN_MAGIC, DropCachedPlan(), lfirst, _SPI_plan::magic, MemoryContextDelete(), NULL, _SPI_plan::plancache_list, _SPI_plan::plancxt, 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().

610 {
611  ListCell *lc;
612 
613  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
614  return SPI_ERROR_ARGUMENT;
615 
616  /* Release the plancache entries */
617  foreach(lc, plan->plancache_list)
618  {
619  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
620 
621  DropCachedPlan(plansource);
622  }
623 
624  /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
626 
627  return 0;
628 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
MemoryContext plancxt
Definition: spi_priv.h:83
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:486
void SPI_freetuple ( HeapTuple  tuple)

Definition at line 963 of file spi.c.

References heap_freetuple().

964 {
965  /* No longer need to worry which context tuple was in... */
966  heap_freetuple(tuple);
967 }
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
void SPI_freetuptable ( SPITupleTable tuptable)

Definition at line 970 of file spi.c.

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

Referenced by _SPI_execute_plan(), exec_assign_value(), exec_eval_cleanup(), exec_for_query(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_fetch(), exec_stmt_return_query(), 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().

971 {
972  bool found = false;
973 
974  /* ignore call if NULL pointer */
975  if (tuptable == NULL)
976  return;
977 
978  /*
979  * Search only the topmost SPI context for a matching tuple table.
980  */
981  if (_SPI_current != NULL)
982  {
983  slist_mutable_iter siter;
984 
985  /* find tuptable in active list, then remove it */
987  {
988  SPITupleTable *tt;
989 
990  tt = slist_container(SPITupleTable, next, siter.cur);
991  if (tt == tuptable)
992  {
993  slist_delete_current(&siter);
994  found = true;
995  break;
996  }
997  }
998  }
999 
1000  /*
1001  * Refuse the deletion if we didn't find it in the topmost SPI context.
1002  * This is primarily a guard against double deletion, but might prevent
1003  * other errors as well. Since the worst consequence of not deleting a
1004  * tuptable would be a transient memory leak, this is just a WARNING.
1005  */
1006  if (!found)
1007  {
1008  elog(WARNING, "attempt to delete invalid SPITupleTable %p", tuptable);
1009  return;
1010  }
1011 
1012  /* for safety, reset global variables that might point at tuptable */
1013  if (tuptable == _SPI_current->tuptable)
1015  if (tuptable == SPI_tuptable)
1016  SPI_tuptable = NULL;
1017 
1018  /* release all memory belonging to tuptable */
1019  MemoryContextDelete(tuptable->tuptabcxt);
1020 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
static int32 next
Definition: blutils.c:210
slist_node * cur
Definition: ilist.h:241
SPITupleTable * SPI_tuptable
Definition: spi.c:41
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
SPITupleTable * tuptable
Definition: spi_priv.h:27
#define WARNING
Definition: elog.h:40
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define NULL
Definition: c.h:229
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:652
#define elog
Definition: elog.h:219
slist_head tuptables
Definition: spi_priv.h:30
MemoryContext tuptabcxt
Definition: spi.h:24
int SPI_getargcount ( SPIPlanPtr  plan)

Definition at line 1431 of file spi.c.

References _SPI_PLAN_MAGIC, _SPI_plan::magic, _SPI_plan::nargs, NULL, SPI_ERROR_ARGUMENT, and SPI_result.

1432 {
1433  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1434  {
1436  return -1;
1437  }
1438  return plan->nargs;
1439 }
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
Oid SPI_getargtypeid ( SPIPlanPtr  plan,
int  argIndex 
)

Definition at line 1416 of file spi.c.

References _SPI_PLAN_MAGIC, _SPI_plan::argtypes, InvalidOid, _SPI_plan::magic, _SPI_plan::nargs, NULL, SPI_ERROR_ARGUMENT, and SPI_result.

1417 {
1418  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
1419  argIndex < 0 || argIndex >= plan->nargs)
1420  {
1422  return InvalidOid;
1423  }
1424  return plan->argtypes[argIndex];
1425 }
Oid * argtypes
Definition: spi_priv.h:86
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
int nargs
Definition: spi_priv.h:85
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
Datum SPI_getbinval ( HeapTuple  tuple,
TupleDesc  tupdesc,
int  fnumber,
bool isnull 
)

Definition at line 836 of file spi.c.

References FirstLowInvalidHeapAttributeNumber, heap_getattr, tupleDesc::natts, NULL, SPI_ERROR_NOATTRIBUTE, and SPI_result.

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

837 {
838  SPI_result = 0;
839 
840  if (fnumber > tupdesc->natts || fnumber == 0 ||
842  {
844  *isnull = true;
845  return (Datum) NULL;
846  }
847 
848  return heap_getattr(tuple, fnumber, tupdesc, isnull);
849 }
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
int natts
Definition: tupdesc.h:73
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
char* SPI_getnspname ( Relation  rel)

Definition at line 916 of file spi.c.

References get_namespace_name(), and RelationGetNamespace.

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

917 {
919 }
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
#define RelationGetNamespace(relation)
Definition: rel.h:443
char* SPI_getrelname ( Relation  rel)

Definition at line 910 of file spi.c.

References pstrdup(), and RelationGetRelationName.

Referenced by autoinc(), check_foreign_key(), check_primary_key(), funny_dup17(), insert_username(), moddatetime(), plperl_trigger_build_args(), pltcl_trigger_handler(), PLy_trigger_build_args(), timetravel(), and ttdummy().

911 {
912  return pstrdup(RelationGetRelationName(rel));
913 }
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define RelationGetRelationName(relation)
Definition: rel.h:436
char* SPI_gettype ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 852 of file spi.c.

References tupleDesc::attrs, FirstLowInvalidHeapAttributeNumber, GETSTRUCT, HeapTupleIsValid, NameStr, tupleDesc::natts, NULL, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), result, SearchSysCache1, SPI_ERROR_NOATTRIBUTE, SPI_ERROR_TYPUNKNOWN, SPI_result, SystemAttributeDefinition(), and TYPEOID.

Referenced by check_foreign_key(), and funny_dup17().

853 {
854  Oid typoid;
855  HeapTuple typeTuple;
856  char *result;
857 
858  SPI_result = 0;
859 
860  if (fnumber > tupdesc->natts || fnumber == 0 ||
862  {
864  return NULL;
865  }
866 
867  if (fnumber > 0)
868  typoid = tupdesc->attrs[fnumber - 1]->atttypid;
869  else
870  typoid = (SystemAttributeDefinition(fnumber, true))->atttypid;
871 
872  typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
873 
874  if (!HeapTupleIsValid(typeTuple))
875  {
877  return NULL;
878  }
879 
880  result = pstrdup(NameStr(((Form_pg_type) GETSTRUCT(typeTuple))->typname));
881  ReleaseSysCache(typeTuple);
882  return result;
883 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1077
Form_pg_attribute * attrs
Definition: tupdesc.h:74
return result
Definition: formatting.c:1632
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
int SPI_result
Definition: spi.c:42
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define SPI_ERROR_TYPUNKNOWN
Definition: spi.h:46
#define NameStr(name)
Definition: c.h:499
Oid SPI_gettypeid ( TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 892 of file spi.c.

References tupleDesc::attrs, FirstLowInvalidHeapAttributeNumber, InvalidOid, tupleDesc::natts, SPI_ERROR_NOATTRIBUTE, SPI_result, and SystemAttributeDefinition().

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

893 {
894  SPI_result = 0;
895 
896  if (fnumber > tupdesc->natts || fnumber == 0 ||
898  {
900  return InvalidOid;
901  }
902 
903  if (fnumber > 0)
904  return tupdesc->attrs[fnumber - 1]->atttypid;
905  else
906  return (SystemAttributeDefinition(fnumber, true))->atttypid;
907 }
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
int natts
Definition: tupdesc.h:73
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define InvalidOid
Definition: postgres_ext.h:36
char* SPI_getvalue ( HeapTuple  tuple,
TupleDesc  tupdesc,
int  fnumber 
)

Definition at line 804 of file spi.c.

References tupleDesc::attrs, FirstLowInvalidHeapAttributeNumber, getTypeOutputInfo(), heap_getattr, tupleDesc::natts, NULL, OidOutputFunctionCall(), SPI_ERROR_NOATTRIBUTE, SPI_result, SystemAttributeDefinition(), and val.

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

805 {
806  Datum val;
807  bool isnull;
808  Oid typoid,
809  foutoid;
810  bool typisvarlena;
811 
812  SPI_result = 0;
813 
814  if (fnumber > tupdesc->natts || fnumber == 0 ||
816  {
818  return NULL;
819  }
820 
821  val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
822  if (isnull)
823  return NULL;
824 
825  if (fnumber > 0)
826  typoid = tupdesc->attrs[fnumber - 1]->atttypid;
827  else
828  typoid = (SystemAttributeDefinition(fnumber, true))->atttypid;
829 
830  getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
831 
832  return OidOutputFunctionCall(foutoid, val);
833 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
uintptr_t Datum
Definition: postgres.h:372
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define NULL
Definition: c.h:229
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
long val
Definition: informix.c:689
bool SPI_is_cursor_plan ( SPIPlanPtr  plan)

Definition at line 1451 of file spi.c.

References _SPI_PLAN_MAGIC, linitial, list_length(), _SPI_plan::magic, NULL, _SPI_plan::plancache_list, CachedPlanSource::resultDesc, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by SPI_cursor_open_internal().

1452 {
1453  CachedPlanSource *plansource;
1454 
1455  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1456  {
1458  return false;
1459  }
1460 
1461  if (list_length(plan->plancache_list) != 1)
1462  {
1463  SPI_result = 0;
1464  return false; /* not exactly 1 pre-rewrite command */
1465  }
1466  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1467 
1468  /*
1469  * We used to force revalidation of the cached plan here, but that seems
1470  * unnecessary: invalidation could mean a change in the rowtype of the
1471  * tuples returned by a plan, but not whether it returns tuples at all.
1472  */
1473  SPI_result = 0;
1474 
1475  /* Does it return tuples? */
1476  if (plansource->resultDesc)
1477  return true;
1478 
1479  return false;
1480 }
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
TupleDesc resultDesc
Definition: plancache.h:92
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
#define linitial(l)
Definition: pg_list.h:111
#define NULL
Definition: c.h:229
static int list_length(const List *l)
Definition: pg_list.h:89
int SPI_keepplan ( SPIPlanPtr  plan)

Definition at line 560 of file spi.c.

References _SPI_PLAN_MAGIC, CacheMemoryContext, lfirst, _SPI_plan::magic, MemoryContextSetParent(), NULL, _SPI_plan::oneshot, _SPI_plan::plancache_list, _SPI_plan::plancxt, SaveCachedPlan(), _SPI_plan::saved, 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(), timetravel(), and ttdummy().

561 {
562  ListCell *lc;
563 
564  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
565  plan->saved || plan->oneshot)
566  return SPI_ERROR_ARGUMENT;
567 
568  /*
569  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
570  * component CachedPlanSources as saved. This sequence cannot fail
571  * partway through, so there's no risk of long-term memory leakage.
572  */
573  plan->saved = true;
575 
576  foreach(lc, plan->plancache_list)
577  {
578  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
579 
580  SaveCachedPlan(plansource);
581  }
582 
583  return 0;
584 }
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:317
int magic
Definition: spi_priv.h:79
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
MemoryContext plancxt
Definition: spi_priv.h:83
bool saved
Definition: spi_priv.h:80
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:441
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
bool oneshot
Definition: spi_priv.h:81
MemoryContext CacheMemoryContext
Definition: mcxt.c:46
HeapTuple SPI_modifytuple ( Relation  rel,
HeapTuple  tuple,
int  natts,
int *  attnum,
Datum Values,
const char *  Nulls 
)

Definition at line 690 of file spi.c.

References heap_deform_tuple(), heap_form_tuple(), HeapTupleGetOid, HeapTupleSetOid, i, MemoryContextSwitchTo(), tupleDesc::natts, NULL, 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, HeapTupleData::t_tableOid, and tupleDesc::tdhasoid.

Referenced by timetravel(), and ttdummy().

692 {
693  MemoryContext oldcxt;
694  HeapTuple mtuple;
695  int numberOfAttributes;
696  Datum *v;
697  bool *n;
698  int i;
699 
700  if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
701  {
703  return NULL;
704  }
705 
706  if (_SPI_current == NULL)
707  {
709  return NULL;
710  }
711 
713 
714  SPI_result = 0;
715 
716  numberOfAttributes = rel->rd_att->natts;
717  v = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
718  n = (bool *) palloc(numberOfAttributes * sizeof(bool));
719 
720  /* fetch old values and nulls */
721  heap_deform_tuple(tuple, rel->rd_att, v, n);
722 
723  /* replace values and nulls */
724  for (i = 0; i < natts; i++)
725  {
726  if (attnum[i] <= 0 || attnum[i] > numberOfAttributes)
727  break;
728  v[attnum[i] - 1] = Values[i];
729  n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n') ? true : false;
730  }
731 
732  if (i == natts) /* no errors in *attnum */
733  {
734  mtuple = heap_form_tuple(rel->rd_att, v, n);
735 
736  /*
737  * copy the identification info of the old tuple: t_ctid, t_self, and
738  * OID (if any)
739  */
740  mtuple->t_data->t_ctid = tuple->t_data->t_ctid;
741  mtuple->t_self = tuple->t_self;
742  mtuple->t_tableOid = tuple->t_tableOid;
743  if (rel->rd_att->tdhasoid)
744  HeapTupleSetOid(mtuple, HeapTupleGetOid(tuple));
745  }
746  else
747  {
748  mtuple = NULL;
750  }
751 
752  pfree(v);
753  pfree(n);
754 
755  MemoryContextSwitchTo(oldcxt);
756 
757  return mtuple;
758 }
bool tdhasoid
Definition: tupdesc.h:79
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
int natts
Definition: tupdesc.h:73
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
void pfree(void *pointer)
Definition: mcxt.c:950
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
Oid t_tableOid
Definition: htup.h:66
MemoryContext savedcxt
Definition: spi_priv.h:33
uintptr_t Datum
Definition: postgres.h:372
TupleDesc rd_att
Definition: rel.h:115
#define NULL
Definition: c.h:229
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:933
void * palloc(Size size)
Definition: mcxt.c:849
int i
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
static bool Nulls[MAXATTR]
Definition: bootstrap.c:164
void* SPI_palloc ( Size  size)

Definition at line 922 of file spi.c.

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

Referenced by _SPI_strdup().

923 {
924  if (_SPI_current == NULL)
925  elog(ERROR, "SPI_palloc called while not connected to SPI");
926 
928 }
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define ERROR
Definition: elog.h:43
MemoryContext savedcxt
Definition: spi_priv.h:33
#define NULL
Definition: c.h:229
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:707
#define elog
Definition: elog.h:219
void SPI_pfree ( void *  pointer)

Definition at line 938 of file spi.c.

References pfree().

939 {
940  /* No longer need to worry which context chunk was in... */
941  pfree(pointer);
942 }
void pfree(void *pointer)
Definition: mcxt.c:950
CachedPlan* SPI_plan_get_cached_plan ( SPIPlanPtr  plan)

Definition at line 1606 of file spi.c.

References _SPI_error_callback(), _SPI_PLAN_MAGIC, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, error_context_stack, GetCachedPlan(), CachedPlanSource::gplan, linitial, list_length(), _SPI_plan::magic, NULL, _SPI_plan::oneshot, _SPI_plan::plancache_list, ErrorContextCallback::previous, CachedPlanSource::query_string, _SPI_connection::queryEnv, and _SPI_plan::saved.

Referenced by exec_eval_simple_expr(), and exec_simple_check_plan().

1607 {
1608  CachedPlanSource *plansource;
1609  CachedPlan *cplan;
1610  ErrorContextCallback spierrcontext;
1611 
1612  Assert(plan->magic == _SPI_PLAN_MAGIC);
1613 
1614  /* Can't support one-shot plans here */
1615  if (plan->oneshot)
1616  return NULL;
1617 
1618  /* Must have exactly one CachedPlanSource */
1619  if (list_length(plan->plancache_list) != 1)
1620  return NULL;
1621  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1622 
1623  /* Setup error traceback support for ereport() */
1624  spierrcontext.callback = _SPI_error_callback;
1625  spierrcontext.arg = (void *) plansource->query_string;
1626  spierrcontext.previous = error_context_stack;
1627  error_context_stack = &spierrcontext;
1628 
1629  /* Get the generic plan for the query */
1630  cplan = GetCachedPlan(plansource, NULL, plan->saved,
1632  Assert(cplan == plansource->gplan);
1633 
1634  /* Pop the error context stack */
1635  error_context_stack = spierrcontext.previous;
1636 
1637  return cplan;
1638 }
List * plancache_list
Definition: spi_priv.h:82
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1135
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
static _SPI_connection * _SPI_current
Definition: spi.c:45
struct ErrorContextCallback * previous
Definition: elog.h:238
struct CachedPlan * gplan
Definition: plancache.h:105
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void _SPI_error_callback(void *arg)
Definition: spi.c:2357
#define linitial(l)
Definition: pg_list.h:111
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
bool saved
Definition: spi_priv.h:80
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool oneshot
Definition: spi_priv.h:81
const char * query_string
Definition: plancache.h:84
static int list_length(const List *l)
Definition: pg_list.h:89
void(* callback)(void *arg)
Definition: elog.h:239
List* SPI_plan_get_plan_sources ( SPIPlanPtr  plan)

Definition at line 1590 of file spi.c.

References _SPI_PLAN_MAGIC, Assert, _SPI_plan::magic, and _SPI_plan::plancache_list.

Referenced by exec_simple_check_plan(), and exec_stmt_execsql().

1591 {
1592  Assert(plan->magic == _SPI_PLAN_MAGIC);
1593  return plan->plancache_list;
1594 }
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
#define Assert(condition)
Definition: c.h:675
bool SPI_plan_is_valid ( SPIPlanPtr  plan)

Definition at line 1489 of file spi.c.

References _SPI_PLAN_MAGIC, Assert, CachedPlanIsValid(), lfirst, _SPI_plan::magic, and _SPI_plan::plancache_list.

Referenced by ri_FetchPreparedPlan().

1490 {
1491  ListCell *lc;
1492 
1493  Assert(plan->magic == _SPI_PLAN_MAGIC);
1494 
1495  foreach(lc, plan->plancache_list)
1496  {
1497  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1498 
1499  if (!CachedPlanIsValid(plansource))
1500  return false;
1501  }
1502  return true;
1503 }
List * plancache_list
Definition: spi_priv.h:82
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
bool CachedPlanIsValid(CachedPlanSource *plansource)
Definition: plancache.c:1412
SPIPlanPtr SPI_prepare ( const char *  src,
int  nargs,
Oid argtypes 
)
SPIPlanPtr SPI_prepare_cursor ( const char *  src,
int  nargs,
Oid argtypes,
int  cursorOptions 
)

Definition at line 488 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_make_plan_non_temp(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), _SPI_plan::argtypes, _SPI_plan::cursor_options, _SPI_plan::magic, _SPI_plan::nargs, NULL, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, result, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by SPI_prepare().

490 {
491  _SPI_plan plan;
493 
494  if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
495  {
497  return NULL;
498  }
499 
500  SPI_result = _SPI_begin_call(true);
501  if (SPI_result < 0)
502  return NULL;
503 
504  memset(&plan, 0, sizeof(_SPI_plan));
505  plan.magic = _SPI_PLAN_MAGIC;
506  plan.cursor_options = cursorOptions;
507  plan.nargs = nargs;
508  plan.argtypes = argtypes;
509  plan.parserSetup = NULL;
510  plan.parserSetupArg = NULL;
511 
512  _SPI_prepare_plan(src, &plan);
513 
514  /* copy plan to procedure context */
515  result = _SPI_make_plan_non_temp(&plan);
516 
517  _SPI_end_call(true);
518 
519  return result;
520 }
static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1745
Oid * argtypes
Definition: spi_priv.h:86
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
return result
Definition: formatting.c:1632
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan)
Definition: spi.c:2503
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
ParserSetupHook parserSetup
Definition: spi_priv.h:87
void * parserSetupArg
Definition: spi_priv.h:88
int cursor_options
Definition: spi_priv.h:84
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
SPIPlanPtr SPI_prepare_params ( const char *  src,
ParserSetupHook  parserSetup,
void *  parserSetupArg,
int  cursorOptions 
)

Definition at line 523 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_make_plan_non_temp(), _SPI_PLAN_MAGIC, _SPI_prepare_plan(), _SPI_plan::argtypes, _SPI_plan::cursor_options, _SPI_plan::magic, _SPI_plan::nargs, NULL, _SPI_plan::parserSetup, _SPI_plan::parserSetupArg, result, SPI_ERROR_ARGUMENT, and SPI_result.

Referenced by exec_prepare_plan().

527 {
528  _SPI_plan plan;
530 
531  if (src == NULL)
532  {
534  return NULL;
535  }
536 
537  SPI_result = _SPI_begin_call(true);
538  if (SPI_result < 0)
539  return NULL;
540 
541  memset(&plan, 0, sizeof(_SPI_plan));
542  plan.magic = _SPI_PLAN_MAGIC;
543  plan.cursor_options = cursorOptions;
544  plan.nargs = 0;
545  plan.argtypes = NULL;
546  plan.parserSetup = parserSetup;
547  plan.parserSetupArg = parserSetupArg;
548 
549  _SPI_prepare_plan(src, &plan);
550 
551  /* copy plan to procedure context */
552  result = _SPI_make_plan_non_temp(&plan);
553 
554  _SPI_end_call(true);
555 
556  return result;
557 }
static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1745
Oid * argtypes
Definition: spi_priv.h:86
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
return result
Definition: formatting.c:1632
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan)
Definition: spi.c:2503
int nargs
Definition: spi_priv.h:85
#define NULL
Definition: c.h:229
ParserSetupHook parserSetup
Definition: spi_priv.h:87
void * parserSetupArg
Definition: spi_priv.h:88
int cursor_options
Definition: spi_priv.h:84
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
bool spi_printtup ( TupleTableSlot slot,
DestReceiver self 
)

Definition at line 1696 of file spi.c.

References SPITupleTable::alloced, elog, ERROR, ExecCopySlotTuple(), SPITupleTable::free, MemoryContextSwitchTo(), NULL, repalloc_huge(), SPITupleTable::tuptabcxt, _SPI_connection::tuptable, and SPITupleTable::vals.

1697 {
1698  SPITupleTable *tuptable;
1699  MemoryContext oldcxt;
1700 
1701  if (_SPI_current == NULL)
1702  elog(ERROR, "spi_printtup called while not connected to SPI");
1703 
1704  tuptable = _SPI_current->tuptable;
1705  if (tuptable == NULL)
1706  elog(ERROR, "improper call to spi_printtup");
1707 
1708  oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
1709 
1710  if (tuptable->free == 0)
1711  {
1712  /* Double the size of the pointer array */
1713  tuptable->free = tuptable->alloced;
1714  tuptable->alloced += tuptable->free;
1715  tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
1716  tuptable->alloced * sizeof(HeapTuple));
1717  }
1718 
1719  tuptable->vals[tuptable->alloced - tuptable->free] =
1720  ExecCopySlotTuple(slot);
1721  (tuptable->free)--;
1722 
1723  MemoryContextSwitchTo(oldcxt);
1724 
1725  return true;
1726 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
HeapTuple * vals
Definition: spi.h:28
#define ERROR
Definition: elog.h:43
SPITupleTable * tuptable
Definition: spi_priv.h:27
HeapTuple ExecCopySlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:545
#define NULL
Definition: c.h:229
uint64 free
Definition: spi.h:26
void * repalloc_huge(void *pointer, Size size)
Definition: mcxt.c:1031
uint64 alloced
Definition: spi.h:25
#define elog
Definition: elog.h:219
MemoryContext tuptabcxt
Definition: spi.h:24
int SPI_register_relation ( EphemeralNamedRelation  enr)

Definition at line 2663 of file spi.c.

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

Referenced by SPI_register_trigger_data().

2664 {
2665  EphemeralNamedRelation match;
2666  int res;
2667 
2668  if (enr == NULL || enr->md.name == NULL)
2669  return SPI_ERROR_ARGUMENT;
2670 
2671  res = _SPI_begin_call(false); /* keep current memory context */
2672  if (res < 0)
2673  return res;
2674 
2675  match = _SPI_find_ENR_by_name(enr->md.name);
2676  if (match)
2678  else
2679  {
2680  if (_SPI_current->queryEnv == NULL)
2682 
2684  res = SPI_OK_REL_REGISTER;
2685  }
2686 
2687  _SPI_end_call(false);
2688 
2689  return res;
2690 }
EphemeralNamedRelationMetadataData md
#define SPI_ERROR_REL_DUPLICATE
Definition: spi.h:47
static EphemeralNamedRelation _SPI_find_ENR_by_name(const char *name)
Definition: spi.c:2646
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define SPI_OK_REL_REGISTER
Definition: spi.h:64
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
void register_ENR(QueryEnvironment *queryEnv, EphemeralNamedRelation enr)
#define NULL
Definition: c.h:229
QueryEnvironment * create_queryEnv()
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
int SPI_register_trigger_data ( TriggerData tdata)

Definition at line 2730 of file spi.c.

References ENR_NAMED_TUPLESTORE, EphemeralNamedRelationMetadataData::enrtuples, EphemeralNamedRelationMetadataData::enrtype, EphemeralNamedRelationData::md, EphemeralNamedRelationMetadataData::name, NULL, 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(), pltcl_trigger_handler(), and PLy_exec_trigger().

2731 {
2732  if (tdata == NULL)
2733  return SPI_ERROR_ARGUMENT;
2734 
2735  if (tdata->tg_newtable)
2736  {
2739  int rc;
2740 
2741  enr->md.name = tdata->tg_trigger->tgnewtable;
2742  enr->md.reliddesc = tdata->tg_relation->rd_id;
2743  enr->md.tupdesc = NULL;
2746  enr->reldata = tdata->tg_newtable;
2747  rc = SPI_register_relation(enr);
2748  if (rc != SPI_OK_REL_REGISTER)
2749  return rc;
2750  }
2751 
2752  if (tdata->tg_oldtable)
2753  {
2756  int rc;
2757 
2758  enr->md.name = tdata->tg_trigger->tgoldtable;
2759  enr->md.reliddesc = tdata->tg_relation->rd_id;
2760  enr->md.tupdesc = NULL;
2763  enr->reldata = tdata->tg_oldtable;
2764  rc = SPI_register_relation(enr);
2765  if (rc != SPI_OK_REL_REGISTER)
2766  return rc;
2767  }
2768 
2769  return SPI_OK_TD_REGISTER;
2770 }
EphemeralNamedRelationMetadataData md
#define SPI_OK_REL_REGISTER
Definition: spi.h:64
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
#define SPI_OK_TD_REGISTER
Definition: spi.h:66
Oid rd_id
Definition: rel.h:116
char * tgnewtable
Definition: reltrigger.h:43
Trigger * tg_trigger
Definition: trigger.h:37
int64 tuplestore_tuple_count(Tuplestorestate *state)
Definition: tuplestore.c:546
#define NULL
Definition: c.h:229
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
int SPI_register_relation(EphemeralNamedRelation enr)
Definition: spi.c:2663
void * palloc(Size size)
Definition: mcxt.c:849
Tuplestorestate * tg_newtable
Definition: trigger.h:41
EphemeralNameRelationType enrtype
char * tgoldtable
Definition: reltrigger.h:42
Relation tg_relation
Definition: trigger.h:34
void* SPI_repalloc ( void *  pointer,
Size  size 
)

Definition at line 931 of file spi.c.

References repalloc().

932 {
933  /* No longer need to worry which context chunk was in... */
934  return repalloc(pointer, size);
935 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
const char* SPI_result_code_string ( int  code)

Definition at line 1513 of file spi.c.

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_REL_REGISTER, SPI_OK_REL_UNREGISTER, SPI_OK_REWRITTEN, SPI_OK_SELECT, SPI_OK_SELINTO, SPI_OK_UPDATE, SPI_OK_UPDATE_RETURNING, and SPI_OK_UTILITY.

Referenced by exec_dynquery_with_params(), exec_prepare_plan(), exec_run_select(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_forc(), exec_stmt_open(), 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(), and PLy_spi_prepare().

1514 {
1515  static char buf[64];
1516 
1517  switch (code)
1518  {
1519  case SPI_ERROR_CONNECT:
1520  return "SPI_ERROR_CONNECT";
1521  case SPI_ERROR_COPY:
1522  return "SPI_ERROR_COPY";
1523  case SPI_ERROR_OPUNKNOWN:
1524  return "SPI_ERROR_OPUNKNOWN";
1525  case SPI_ERROR_UNCONNECTED:
1526  return "SPI_ERROR_UNCONNECTED";
1527  case SPI_ERROR_ARGUMENT:
1528  return "SPI_ERROR_ARGUMENT";
1529  case SPI_ERROR_PARAM:
1530  return "SPI_ERROR_PARAM";
1531  case SPI_ERROR_TRANSACTION:
1532  return "SPI_ERROR_TRANSACTION";
1533  case SPI_ERROR_NOATTRIBUTE:
1534  return "SPI_ERROR_NOATTRIBUTE";
1535  case SPI_ERROR_NOOUTFUNC:
1536  return "SPI_ERROR_NOOUTFUNC";
1537  case SPI_ERROR_TYPUNKNOWN:
1538  return "SPI_ERROR_TYPUNKNOWN";
1540  return "SPI_ERROR_REL_DUPLICATE";
1542  return "SPI_ERROR_REL_NOT_FOUND";
1543  case SPI_OK_CONNECT:
1544  return "SPI_OK_CONNECT";
1545  case SPI_OK_FINISH:
1546  return "SPI_OK_FINISH";
1547  case SPI_OK_FETCH:
1548  return "SPI_OK_FETCH";
1549  case SPI_OK_UTILITY:
1550  return "SPI_OK_UTILITY";
1551  case SPI_OK_SELECT:
1552  return "SPI_OK_SELECT";
1553  case SPI_OK_SELINTO:
1554  return "SPI_OK_SELINTO";
1555  case SPI_OK_INSERT:
1556  return "SPI_OK_INSERT";
1557  case SPI_OK_DELETE:
1558  return "SPI_OK_DELETE";
1559  case SPI_OK_UPDATE:
1560  return "SPI_OK_UPDATE";
1561  case SPI_OK_CURSOR:
1562  return "SPI_OK_CURSOR";
1564  return "SPI_OK_INSERT_RETURNING";
1566  return "SPI_OK_DELETE_RETURNING";
1568  return "SPI_OK_UPDATE_RETURNING";
1569  case SPI_OK_REWRITTEN:
1570  return "SPI_OK_REWRITTEN";
1571  case SPI_OK_REL_REGISTER:
1572  return "SPI_OK_REL_REGISTER";
1573  case SPI_OK_REL_UNREGISTER:
1574  return "SPI_OK_REL_UNREGISTER";
1575  }
1576  /* Unrecognized code ... return something useful ... */
1577  sprintf(buf, "Unrecognized SPI code %d", code);
1578  return buf;
1579 }
#define SPI_OK_CONNECT
Definition: spi.h:50
#define SPI_ERROR_PARAM
Definition: spi.h:42
#define SPI_ERROR_REL_NOT_FOUND
Definition: spi.h:48
#define SPI_ERROR_REL_DUPLICATE
Definition: spi.h:47
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
#define SPI_OK_DELETE_RETURNING
Definition: spi.h:61
#define SPI_OK_DELETE
Definition: spi.h:57
#define SPI_ERROR_COPY
Definition: spi.h:37
#define SPI_ERROR_OPUNKNOWN
Definition: spi.h:38
#define SPI_OK_REL_REGISTER
Definition: spi.h:64
#define SPI_ERROR_CONNECT
Definition: spi.h:36
#define SPI_OK_CURSOR
Definition: spi.h:59
#define SPI_ERROR_NOOUTFUNC
Definition: spi.h:45
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
#define SPI_OK_INSERT_RETURNING
Definition: spi.h:60
static char * buf
Definition: pg_test_fsync.c:66
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
#define SPI_OK_UTILITY
Definition: spi.h:53
#define SPI_OK_UPDATE_RETURNING
Definition: spi.h:62
#define SPI_OK_REWRITTEN
Definition: spi.h:63
#define SPI_ERROR_TRANSACTION
Definition: spi.h:43
#define SPI_OK_SELINTO
Definition: spi.h:55
#define SPI_OK_FETCH
Definition: spi.h:52
#define SPI_OK_SELECT
Definition: spi.h:54
#define SPI_OK_FINISH
Definition: spi.h:51
#define SPI_ERROR_TYPUNKNOWN
Definition: spi.h:46
#define SPI_OK_UPDATE
Definition: spi.h:58
#define SPI_OK_INSERT
Definition: spi.h:56
#define SPI_OK_REL_UNREGISTER
Definition: spi.h:65
HeapTupleHeader SPI_returntuple ( HeapTuple  tuple,
TupleDesc  tupdesc 
)

Definition at line 658 of file spi.c.

References assign_record_type_typmod(), DatumGetHeapTupleHeader, heap_copy_tuple_as_datum(), MemoryContextSwitchTo(), NULL, RECORDOID, _SPI_connection::savedcxt, SPI_ERROR_ARGUMENT, SPI_ERROR_UNCONNECTED, SPI_result, tupleDesc::tdtypeid, and tupleDesc::tdtypmod.

Referenced by plpgsql_exec_function().

659 {
660  MemoryContext oldcxt;
661  HeapTupleHeader dtup;
662 
663  if (tuple == NULL || tupdesc == NULL)
664  {
666  return NULL;
667  }
668 
669  if (_SPI_current == NULL)
670  {
672  return NULL;
673  }
674 
675  /* For RECORD results, make sure a typmod has been assigned */
676  if (tupdesc->tdtypeid == RECORDOID &&
677  tupdesc->tdtypmod < 0)
678  assign_record_type_typmod(tupdesc);
679 
681 
682  dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
683 
684  MemoryContextSwitchTo(oldcxt);
685 
686  return dtup;
687 }
Oid tdtypeid
Definition: tupdesc.h:77
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
int32 tdtypmod
Definition: tupdesc.h:78
void assign_record_type_typmod(TupleDesc tupDesc)
Definition: typcache.c:1308
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
#define RECORDOID
Definition: pg_type.h:680
MemoryContext savedcxt
Definition: spi_priv.h:33
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:656
#define NULL
Definition: c.h:229
SPIPlanPtr SPI_saveplan ( SPIPlanPtr  plan)

Definition at line 587 of file spi.c.

References _SPI_begin_call(), _SPI_end_call(), _SPI_PLAN_MAGIC, _SPI_save_plan(), _SPI_plan::magic, NULL, SPI_ERROR_ARGUMENT, and SPI_result.

588 {
589  SPIPlanPtr newplan;
590 
591  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
592  {
594  return NULL;
595  }
596 
597  SPI_result = _SPI_begin_call(false); /* don't change context */
598  if (SPI_result < 0)
599  return NULL;
600 
601  newplan = _SPI_save_plan(plan);
602 
603  SPI_result = _SPI_end_call(false);
604 
605  return newplan;
606 }
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
int magic
Definition: spi_priv.h:79
int SPI_result
Definition: spi.c:42
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static SPIPlanPtr _SPI_save_plan(SPIPlanPtr plan)
Definition: spi.c:2573
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define NULL
Definition: c.h:229
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
void SPI_scroll_cursor_fetch ( Portal  portal,
FetchDirection  direction,
long  count 
)

Definition at line 1376 of file spi.c.

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

Referenced by exec_stmt_fetch().

1377 {
1378  _SPI_cursor_operation(portal,
1379  direction, count,
1381  /* we know that the DestSPI receiver doesn't need a destroy call */
1382 }
Definition: dest.h:93
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:2383
void SPI_scroll_cursor_move ( Portal  portal,
FetchDirection  direction,
long  count 
)

Definition at line 1391 of file spi.c.

References _SPI_cursor_operation(), and None_Receiver.

Referenced by exec_stmt_fetch().

1392 {
1393  _SPI_cursor_operation(portal, direction, count, None_Receiver);
1394 }
DestReceiver * None_Receiver
Definition: dest.c:91
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:2383
int SPI_unregister_relation ( const char *  name)

Definition at line 2697 of file spi.c.

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

2698 {
2699  EphemeralNamedRelation match;
2700  int res;
2701 
2702  if (name == NULL)
2703  return SPI_ERROR_ARGUMENT;
2704 
2705  res = _SPI_begin_call(false); /* keep current memory context */
2706  if (res < 0)
2707  return res;
2708 
2709  match = _SPI_find_ENR_by_name(name);
2710  if (match)
2711  {
2713  res = SPI_OK_REL_UNREGISTER;
2714  }
2715  else
2717 
2718  _SPI_end_call(false);
2719 
2720  return res;
2721 }
EphemeralNamedRelationMetadataData md
#define SPI_ERROR_REL_NOT_FOUND
Definition: spi.h:48
static EphemeralNamedRelation _SPI_find_ENR_by_name(const char *name)
Definition: spi.c:2646
static _SPI_connection * _SPI_current
Definition: spi.c:45
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
QueryEnvironment * queryEnv
Definition: spi_priv.h:35
void unregister_ENR(QueryEnvironment *queryEnv, const char *name)
static int _SPI_end_call(bool procmem)
Definition: spi.c:2466
#define NULL
Definition: c.h:229
const char * name
Definition: encode.c:521
static int _SPI_begin_call(bool execmem)
Definition: spi.c:2449
#define SPI_OK_REL_UNREGISTER
Definition: spi.h:65

Variable Documentation

int _SPI_connected = -1
static

Definition at line 47 of file spi.c.

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

_SPI_connection* _SPI_current = NULL
static

Definition at line 45 of file spi.c.

_SPI_connection* _SPI_stack = NULL
static

Definition at line 44 of file spi.c.

int _SPI_stack_depth = 0
static

Definition at line 46 of file spi.c.

Referenced by AtEOXact_SPI(), and SPI_connect().