SPI_execor similar function
PostgreSQL allocates memory
within memory contexts, which provide a
convenient method of managing allocations made in many different
places that need to live for differing amounts of time.
Destroying a context releases all the memory that was allocated
in it. Thus, it is not necessary to keep track of individual
objects to avoid memory leaks --- only a relatively small number
of contexts have to be managed.
palloc and related functions allocate memory
from the "current" context.
SPI_connect creates a new memory
context and makes it current.
SPI_finish restores the previous current memory
context and destroys the context created by
SPI_connect. These actions ensure that
transient memory allocations made inside your procedure are
reclaimed at procedure exit, avoiding memory leakage.
However, if your procedure needs to return an allocated memory
object (such as a value of a pass-by-reference data type), you
can't allocate the return object using
palloc, at least not while you are connected to
SPI. If you try, the object will be deallocated during
SPI_finish, and your procedure will
not work reliably!
To solve this problem, use
SPI_palloc to allocate your return object.
SPI_palloc allocates space from
"upper Executor" memory --- that is,
the memory context that was current when
SPI_connect was called, which is precisely the
right context for return values of your procedure.
If called while not connected to SPI,
SPI_palloc acts the same as plain
Before a procedure connects to the SPI manager, the current
memory context is the upper Executor context, so all allocations
made by the procedure via
by SPI utility functions are made in this context.
SPI_connect is called, the
current context is the procedure's private context made by
SPI_connect. All allocations made
repalloc or by SPI utility functions (except
SPI_palloc) are made in this context.
When a procedure disconnects from the SPI manager (via
SPI_finish) the current context is
restored to the upper Executor context, and all allocations made
in the procedure memory context are freed and can't be used any
All functions described in this section may be used by both
connected and unconnected procedures. In an unconnected
procedure, they act the same as the underlying ordinary backend
Use SPI_palloc to allocate memory objects, which are returned by your procedure!!
I had a lot of problems because I allocated memory objects, which are returned by my procedure, using palloc BEFORE calling SPI_connect. This did not work.
When I used SPI_palloc to allocate these memory objects everything was working perfect.
If called while not connected to SPI, SPI_palloc DOES NOT act the same as plain palloc, at least in this context.