SPI_prepare
SPI_prepare — подготовить оператор, но пока не выполнять его
Синтаксис
SPIPlanPtr SPI_prepare(const char *command
, intnargs
, Oid *argtypes
)
Описание
SPI_prepare
создаёт и возвращает подготовленный оператор для заданной команды. Подготовленный оператор может быть затем неоднократно выполнен функцией SPI_execute_plan
.
Когда одна и та же или похожие команды выполняются неоднократно, обычно выгоднее произвести анализ запроса только раз, а ещё выгоднее может быть повторно использовать план выполнения команды. SPI_prepare
преобразует строку команды в подготовленный оператор, включающий в себя результаты анализа запроса. Подготовленный оператор также оставляет место для кеширования плана выполнения, если выбор специализированного плана для каждого выполнения не принесёт пользы.
Подготавливаемую команду можно сделать более общей, записав параметры ($1
, $2
, etc.) вместо значений, задаваемыми константами в обычной команде. Фактические значения параметров в этом случае будут задаваться при вызове SPI_execute_plan
. Это позволяет применять подготовленную команду в более широком круге ситуаций, чем это возможно без параметров.
Оператор, возвращаемый функцией SPI_prepare
, может использоваться только в текущем вызове процедуры, так как SPI_finish
освобождает память, выделенную для такого оператора. Но этот оператор может быть сохранён на будущее с помощью функций SPI_keepplan
или SPI_saveplan
.
Аргументы
const char *
command
строка команды
int
nargs
число входных параметров (
$1
,$2
и т. д.)Oid *
argtypes
указатель на массив, содержащий OID типов параметров
Возвращаемое значение
SPI_prepare
возвращает ненулевой указатель на SPIPlan
, скрытую структуру, представляющую подготовленный оператор. В случае ошибки возвращается NULL
, а в SPI_result
устанавливается один из кодов ошибок, определённых для SPI_execute
, за исключением того, что код SPI_ERROR_ARGUMENT
устанавливается, когда command
— NULL
, когда nargs
меньше 0 или когда nargs
больше 0, а argtypes
— NULL
.
Замечания
Если параметры не определены, при первом использовании SPI_execute_plan
создаётся общий план, который затем будет применяться при последующих вызовах. Если же присутствуют параметры, SPI_execute_plan
будет создавать специализированные планы для конкретных значений параметров. После достаточного количества использований полученного подготовленного оператора, функция SPI_execute_plan
построит общий план, и если он не будет значительно дороже специализированных, она начнёт использовать его, а не будет строить план заново. Если это поведение по умолчанию не устраивает, его можно изменить, передав флаг CURSOR_OPT_GENERIC_PLAN
или CURSOR_OPT_CUSTOM_PLAN
в SPI_prepare_cursor
, чтобы ограничиться использованием только общего или специализированных планов, соответственно.
Хотя основной смысл подготовленного оператора в том, чтобы избежать повторного разбора и планирования запроса, Postgres Pro всё же будет принудительно повторять разбор и планирование запроса перед его выполнением, если со времени предыдущего использования подготовленного оператора произойдут изменения определений (DDL) объектов базы, задействованных в этом запросе. Также, если перед очередным использованием было изменено значение search_path, запрос будет разобран заново с новым значением search_path
. (Последняя особенность появилась в PostgreSQL 9.3.) Чтобы узнать о поведении подготовленных операторов больше, обратитесь к PREPARE.
Эту функцию следует вызывать только из подключённой процедуры.
SPIPlanPtr
объявлен в spi.h
как указатель на скрытую структуру. Пытаться обращаться к её содержимому напрямую не стоит, так как ваш код скорее всего сломается при выходе новых версий Postgres Pro.
Имя SPIPlanPtr
объясняется отчасти историческими причинами, так как теперь эта структура может не содержать собственно план выполнения.
SPI_prepare
SPI_prepare — prepare a statement, without executing it yet
Synopsis
SPIPlanPtr SPI_prepare(const char *command
, intnargs
, Oid *argtypes
)
Description
SPI_prepare
creates and returns a prepared statement for the specified command, but doesn't execute the command. The prepared statement can later be executed repeatedly using SPI_execute_plan
.
When the same or a similar command is to be executed repeatedly, it is generally advantageous to perform parse analysis only once, and might furthermore be advantageous to re-use an execution plan for the command. SPI_prepare
converts a command string into a prepared statement that encapsulates the results of parse analysis. The prepared statement also provides a place for caching an execution plan if it is found that generating a custom plan for each execution is not helpful.
A prepared command can be generalized by writing parameters ($1
, $2
, etc.) in place of what would be constants in a normal command. The actual values of the parameters are then specified when SPI_execute_plan
is called. This allows the prepared command to be used over a wider range of situations than would be possible without parameters.
The statement returned by SPI_prepare
can be used only in the current invocation of the procedure, since SPI_finish
frees memory allocated for such a statement. But the statement can be saved for longer using the functions SPI_keepplan
or SPI_saveplan
.
Arguments
const char *
command
command string
int
nargs
number of input parameters (
$1
,$2
, etc.)Oid *
argtypes
pointer to an array containing the OIDs of the data types of the parameters
Return Value
SPI_prepare
returns a non-null pointer to an SPIPlan
, which is an opaque struct representing a prepared statement. On error, NULL
will be returned, and SPI_result
will be set to one of the same error codes used by SPI_execute
, except that it is set to SPI_ERROR_ARGUMENT
if command
is NULL
, or if nargs
is less than 0, or if nargs
is greater than 0 and argtypes
is NULL
.
Notes
If no parameters are defined, a generic plan will be created at the first use of SPI_execute_plan
, and used for all subsequent executions as well. If there are parameters, the first few uses of SPI_execute_plan
will generate custom plans that are specific to the supplied parameter values. After enough uses of the same prepared statement, SPI_execute_plan
will build a generic plan, and if that is not too much more expensive than the custom plans, it will start using the generic plan instead of re-planning each time. If this default behavior is unsuitable, you can alter it by passing the CURSOR_OPT_GENERIC_PLAN
or CURSOR_OPT_CUSTOM_PLAN
flag to SPI_prepare_cursor
, to force use of generic or custom plans respectively.
Although the main point of a prepared statement is to avoid repeated parse analysis and planning of the statement, Postgres Pro will force re-analysis and re-planning of the statement before using it whenever database objects used in the statement have undergone definitional (DDL) changes since the previous use of the prepared statement. Also, if the value of search_path changes from one use to the next, the statement will be re-parsed using the new search_path
. (This latter behavior is new as of PostgreSQL 9.3.) See PREPARE for more information about the behavior of prepared statements.
This function should only be called from a connected procedure.
SPIPlanPtr
is declared as a pointer to an opaque struct type in spi.h
. It is unwise to try to access its contents directly, as that makes your code much more likely to break in future revisions of Postgres Pro.
The name SPIPlanPtr
is somewhat historical, since the data structure no longer necessarily contains an execution plan.