SPI_cursor_parse_open
SPI_cursor_parse_open — открывает курсор для строки запроса и набора параметров
Синтаксис
Portal SPI_cursor_parse_open(const char *name, const char *command, const SPIParseOpenOptions *options)
Описание
SPI_cursor_parse_open открывает курсор (внутри называемый порталом) для выполнения заданного запроса. Эта функция действует подобно функции SPI_prepare_cursor с последующей SPI_cursor_open_with_paramlist, за исключением того, что ей для обработки всех ссылок на параметры в строке запроса передаётся объект ParamListInfo.
Для разового выполнения запроса эту функцию следует предпочесть SPI_prepare_cursor с последующей SPI_cursor_open_with_paramlist. Если же одна и та же команда должна выполняться с самыми разными параметрами, какой вариант окажется быстрее, будет зависеть от стоимости повторного планирования и выигрыша от выбора специализированных планов.
Как правило, в объекте options->params все параметры должны иметь пометку PARAM_FLAG_CONST, поскольку для запроса всегда используется одноразовый план.
Переданные значения параметров копируются в портал курсора, так что их можно освободить и во время существования курсора.
Аргументы
const char *nameимя портала, либо
NULL, чтобы имя выбрала системаconst char *commandстрока команды
const SPIParseOpenOptions *optionsструктура, содержащая необязательные аргументы
Структуру options всегда следует сначала полностью заполнять нулями, а затем уже задавать необходимые значения. Это гарантирует совместимость с будущими изменениями в коде: при добавлении в эту структуру любых новых полей нулевое значение будет определять старое поведение. Сейчас в options есть такие поля:
ParamListInfoparamsструктура данных, содержащая типы и значения параметров запроса; NULL, если их нет
intcursorOptionsбитовая маска параметров курсора; 0 выбирает поведение по умолчанию
boolread_onlytrueдля режима выполнения «только чтение»
Возвращаемое значение
Указатель на портал, содержащий курсор. Заметьте, что соглашение о возврате ошибок отсутствует; все ошибки выдаются через elog.
SPI_cursor_parse_open
SPI_cursor_parse_open — set up a cursor using a query string and parameters
Synopsis
Portal SPI_cursor_parse_open(const char *name, const char *command, const SPIParseOpenOptions *options)
Description
SPI_cursor_parse_open sets up a cursor (internally, a portal) that will execute the specified query string. This is comparable to SPI_prepare_cursor followed by SPI_cursor_open_with_paramlist, except that parameter references within the query string are handled entirely by supplying a ParamListInfo object.
For one-time query execution, this function should be preferred over SPI_prepare_cursor followed by SPI_cursor_open_with_paramlist. If the same command is to be executed with many different parameters, either method might be faster, depending on the cost of re-planning versus the benefit of custom plans.
The options->params object should normally mark each parameter with the PARAM_FLAG_CONST flag, since a one-shot plan is always used for the query.
The passed-in parameter data will be copied into the cursor's portal, so it can be freed while the cursor still exists.
Arguments
const char *namename for portal, or
NULLto let the system select a nameconst char *commandcommand string
const SPIParseOpenOptions *optionsstruct containing optional arguments
Callers should always zero out the entire options struct, then fill whichever fields they want to set. This ensures forward compatibility of code, since any fields that are added to the struct in future will be defined to behave backwards-compatibly if they are zero. The currently available options fields are:
ParamListInfoparamsdata structure containing query parameter types and values; NULL if none
intcursorOptionsinteger bit mask of cursor options; zero produces default behavior
boolread_onlytruefor read-only execution
Return Value
Pointer to portal containing the cursor. Note there is no error return convention; any error will be reported via elog.