32.11. Функции разного назначения
Как всегда, находятся функции, которые не попадают ни в одну из категорий.
-
PQfreemem
Освобождает память, которую выделила libpq.
void PQfreemem(void *ptr);
Освобождает память, выделенную библиотекой libpq, а именно функциями
PQescapeByteaConn
,PQescapeBytea
,PQunescapeBytea
иPQnotifies
. Особенно важно использовать именно эту функцию, а неfree()
, в Microsoft Windows. Это связано с тем, что выделение памяти в DLL и освобождение её в приложении будет работать, только если флаги многопоточной/однопоточной, выпускаемой/отладочной или статической/динамической сборки для DLL и приложения полностью совпадают. На других платформах эта функция действует так же, как стандартная библиотечная функцияfree()
.-
PQconninfoFree
Освобождает структуры данных, выделенные функциями
PQconndefaults
иPQconninfoParse
.void PQconninfoFree(PQconninfoOption *connOptions);
Простая функция
PQfreemem
не подойдёт для этого, так как эти структуры содержат ссылки на подчинённые строки.-
PQencryptPassword
Подготавливает зашифрованную форму пароля Postgres Pro.
char * PQencryptPassword(const char *passwd, const char *user);
Эта функция предназначена для клиентских приложений, желающих передавать команды вида
ALTER USER joe PASSWORD 'pwd'
. В такой команде лучше не передавать исходный пароль открытым текстом, так как он может появиться в рабочих журналах, мониторе активности и т. д. Вместо этого, воспользуйтесь данной функцией и переведите пароль в зашифрованную форму, прежде чем передавать его. В аргументах ей передаётся пароль в открытом виде и имя пользователя SQL, для которого он предназначен. Возвращает она строку, выделенную функциейmalloc
, илиNULL
в случае нехватки памяти. Вызывающий код может рассчитывать на то, что в этой строке не будет специальных символов, требующих экранирования. Завершив работу с этой строкой, вызовитеPQfreemem
, чтобы освободить её.-
PQmakeEmptyPGresult
Конструирует пустой объект
PGresult
с указанным состоянием.PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
Это внутренняя функция libpq, выделяющая память и инициализирующая пустой объект
PGresult
. Эта функция возвращаетNULL
, если не может выделить память. Она сделана экспортируемой, так как некоторые приложения находят полезным создавать объекты результатов (в частности, объекты с состоянием ошибки) самостоятельно. Если вconn
передаётся не null иstatus
указывает на ошибку, вPGresult
копируется текущее сообщение об ошибке для заданного соединения. Также, если вconn
передаётся не null, вPGresult
копируются все процедуры событий, зарегистрированные для этого соединения. (При этом вызовыPGEVT_RESULTCREATE
не выполняются; см. описаниеPQfireResultCreateEvents
.) Заметьте, что в конце для этого объекта следует вызватьPQclear
, как и для объектаPGresult
, возвращённого самой библиотекой libpq.-
PQfireResultCreateEvents
Вызывает событие
PGEVT_RESULTCREATE
(см. Раздел 32.13) для каждой процедуры событий, зарегистрированной в объектеPGresult
. Возвращает ненулевое значение в случае успеха или ноль в случае ошибки в одной из процедур.int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
Аргумент
conn
передаётся процедурам событий, но непосредственно не используется. Он может быть равенNULL
, если он не нужен процедурам событий.Процедуры событий, уже получившие событие
PGEVT_RESULTCREATE
илиPGEVT_RESULTCOPY
для этого объекта, больше не вызываются.Основная причина отделения этой функции от
PQmakeEmptyPGresult
в том, что часто требуется создать объектPGresult
и наполнить его данными, прежде чем вызывать процедуры событий.-
PQcopyResult
Создаёт копию объекта
PGresult
. Эта копия никак не связана с исходным результатом и поэтому, когда она становится не нужна, необходимо вызватьPQclear
. Если функция завершается ошибкой, она возвращаетNULL
.PGresult *PQcopyResult(const PGresult *src, int flags);
Создаваемая копия не будет точной. В возвращаемый результат всегда помещается состояние
PGRES_TUPLES_OK
и в него не копируются никакие сообщения об ошибках из исходного объекта. (Однако в него копируется строка состояния команды.) Что ещё в него будет копироваться, определяет аргументflags
, в котором складываются несколько флагов. ФлагPG_COPYRES_ATTRS
включает копирование атрибутов исходного объекта (определений столбцов), а флагPG_COPYRES_TUPLES
включает копирование кортежей из исходного объекта (при этом также копируются и атрибуты.) ФлагPG_COPYRES_NOTICEHOOKS
включает копирование обработчиков замечаний, а флагPG_COPYRES_EVENTS
— событий из исходного объекта результата. (Но любые данные, связанные с экземпляром исходного объекта, не копируются.)-
PQsetResultAttrs
Устанавливает атрибуты объекта
PGresult
.int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
Предоставленная структура
attDescs
копируется в результат. Если указательattDescs
равенNULL
илиnumAttributes
меньше одного, запрос игнорируется и функция выполняется без ошибки. Еслиres
уже содержит атрибуты, функция завершается ошибкой. В случае ошибки функция возвращает ноль, а в обратном случае — ненулевое значение.-
PQsetvalue
Устанавливает значение поля кортежа в объекте
PGresult
.int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
Эта функция автоматически увеличивает внутренний массив кортежей при необходимости. Однако значение
tup_num
должно быть меньше или равноPQntuples
, что означает, что эта функция может увеличивать массив кортежей только на один кортеж. Но в существующем кортеже любые поля могут изменяться в любом порядке. Если значение в поле с номеромfield_num
уже существует, оно будет перезаписано. Еслиlen
равно -1 илиvalue
равноNULL
, в поле будет записано значение SQL NULL. Устанавливаемое значение (value
) копируется в закрытую область объекта результата, так что от него можно избавиться после завершения функции. Если функция завершается ошибкой, она возвращает ноль, а в обратном случае — ненулевое значение.-
PQresultAlloc
Выделяет подчинённую область памяти для объекта
PGresult
.void *PQresultAlloc(PGresult *res, size_t nBytes);
Любая память, выделенная этой функцией, будет освобождена при очистке объекта
res
. В случае ошибки эта функция возвращаетNULL
. Результат гарантированно выравнивается должным образом для любого типа данных, как и приmalloc
.-
PQlibVersion
Возвращает версию используемой библиотеки libpq.
int PQlibVersion(void);
По результату этой функции можно во время выполнения определить, предоставляется ли определённая функциональность загруженной в данный момент версией libpq. Эта функция может использоваться, например, чтобы понять, какие параметры соединения может принять
PQconnectdb
или поддерживается ли выводbytea
в форматеhex
, появившийся в PostgreSQL 9.0.Это число формируется в результате преобразования номеров старшей, дополнительной и корректирующей версии в числа из двух цифр и соединения их вместе. Например, для версии 9.1 будет возвращено 90100, а для версии 9.1.2 — 90102 (ведущие нули не показываются).
Примечание
Эта функция появилась в PostgreSQL версии 9.1, поэтому с её помощью нельзя проверить функциональность предыдущих версий, так как при компоновке с ней будет создана зависимость от версии 9.1.
CREATE EXTENSION
CREATE EXTENSION — install an extension
Synopsis
CREATE EXTENSION [ IF NOT EXISTS ]extension_name
[ WITH ] [ SCHEMAschema_name
] [ VERSIONversion
] [ CASCADE ]
Description
CREATE EXTENSION
loads a new extension into the current database. There must not be an extension of the same name already loaded.
Loading an extension essentially amounts to running the extension's script file. The script will typically create new SQL objects such as functions, data types, operators and index support methods. CREATE EXTENSION
additionally records the identities of all the created objects, so that they can be dropped again if DROP EXTENSION
is issued.
The user who runs CREATE EXTENSION
becomes the owner of the extension for purposes of later privilege checks, and normally also becomes the owner of any objects created by the extension's script.
Loading an extension ordinarily requires the same privileges that would be required to create its component objects. For many extensions this means superuser privileges are needed. However, if the extension is marked trusted in its control file, then it can be installed by any user who has CREATE
privilege on the current database. In this case the extension object itself will be owned by the calling user, but the contained objects will be owned by the bootstrap superuser (unless the extension's script explicitly assigns them to the calling user). This configuration gives the calling user the right to drop the extension, but not to modify individual objects within it.
Parameters
IF NOT EXISTS
Do not throw an error if an extension with the same name already exists. A notice is issued in this case. Note that there is no guarantee that the existing extension is anything like the one that would have been created from the currently-available script file.
extension_name
The name of the extension to be installed. Postgres Pro will create the extension using details from the file
SHAREDIR/extension/
extension_name
.control
.schema_name
The name of the schema in which to install the extension's objects, given that the extension allows its contents to be relocated. The named schema must already exist. If not specified, and the extension's control file does not specify a schema either, the current default object creation schema is used.
If the extension specifies a
schema
parameter in its control file, then that schema cannot be overridden with aSCHEMA
clause. Normally, an error will be raised if aSCHEMA
clause is given and it conflicts with the extension'sschema
parameter. However, if theCASCADE
clause is also given, thenschema_name
is ignored when it conflicts. The givenschema_name
will be used for installation of any needed extensions that do not specifyschema
in their control files.Remember that the extension itself is not considered to be within any schema: extensions have unqualified names that must be unique database-wide. But objects belonging to the extension can be within schemas.
version
The version of the extension to install. This can be written as either an identifier or a string literal. The default version is whatever is specified in the extension's control file.
CASCADE
Automatically install any extensions that this extension depends on that are not already installed. Their dependencies are likewise automatically installed, recursively. The
SCHEMA
clause, if given, applies to all extensions that get installed this way. Other options of the statement are not applied to automatically-installed extensions; in particular, their default versions are always selected.
Notes
Before you can use CREATE EXTENSION
to load an extension into a database, the extension's supporting files must be installed. Information about installing the extensions supplied with Postgres Pro can be found in Additional Supplied Modules.
The extensions currently available for loading can be identified from the pg_available_extensions
or pg_available_extension_versions
system views.
Caution
Installing an extension as superuser requires trusting that the extension's author wrote the extension installation script in a secure fashion. It is not terribly difficult for a malicious user to create trojan-horse objects that will compromise later execution of a carelessly-written extension script, allowing that user to acquire superuser privileges. However, trojan-horse objects are only hazardous if they are in the search_path
during script execution, meaning that they are in the extension's installation target schema or in the schema of some extension it depends on. Therefore, a good rule of thumb when dealing with extensions whose scripts have not been carefully vetted is to install them only into schemas for which CREATE privilege has not been and will not be granted to any untrusted users. Likewise for any extensions they depend on.
The extensions supplied with Postgres Pro are believed to be secure against installation-time attacks of this sort, except for a few that depend on other extensions. As stated in the documentation for those extensions, they should be installed into secure schemas, or installed into the same schemas as the extensions they depend on, or both.
For information about writing new extensions, see Section 37.17.
Examples
Install the hstore extension into the current database, placing its objects in schema addons
:
CREATE EXTENSION hstore SCHEMA addons;
Another way to accomplish the same thing:
SET search_path = addons; CREATE EXTENSION hstore;
Compatibility
CREATE EXTENSION
is a Postgres Pro extension.