SPI_prepare(query, nargs, argtypes)
Number of input parameters ($1 ... $nargs - as in SQL-functions)
Pointer to array of type OIDs for input parameter types
SPI_prepare creates and returns
an execution plan (parser+planner+optimizer) but doesn't execute
the query. Should only be called from a connected procedure.
When the same or similar query is to be executed repeatedly,
it may be advantageous to perform query planning only once.
SPI_prepare converts a query string
into an execution plan that can be passed repeatedly to
A prepared query can be generalized by writing parameters ($1,
$2, etc) in place of what would be constants in a normal query.
The values of the parameters are then specified when
SPI_execp is called. This allows the prepared
query to be used over a wider range of situations than would be
possible without parameters.
Note: However, there is a disadvantage: since the planner does not know the values that will be supplied for the parameters, it may make worse query planning choices than it would make for a simple query with all constants visible.
If the query uses parameters, their number and datatypes must
be specified in the call to
The plan returned by
may be used only in current invocation of the procedure since
SPI_finish frees memory allocated
for a plan. But see
save a plan for longer.
If successful, a non-null pointer will be returned. Otherwise, you'll get a NULL plan. In both cases SPI_result will be set like the value returned by SPI_exec, except that it is set to SPI_ERROR_ARGUMENT if query is NULL or nargs < 0 or nargs > 0 && argtypes is NULL.