33.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не подойдёт для этого, так как эти структуры содержат ссылки на подчинённые строки.-
PQencryptPasswordConn Подготавливает зашифрованную форму пароля Postgres Pro.
char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
Эта функция предназначена для клиентских приложений, желающих передавать команды вида
ALTER USER joe PASSWORD 'pwd'. В такой команде лучше не передавать исходный пароль открытым текстом, так как он может появиться в журналах команд, мониторе активности и т. д. Вместо этого воспользуйтесь данной функцией и переведите пароль в зашифрованную форму.В аргументах
passwdиuserзадаётся пароль в открытом виде и SQL-имя пользователя, для которого он задаётся. В аргументеalgorithmзадаётся алгоритм для шифрования пароля. В настоящее время поддерживаются алгоритмыmd5иscram-sha-256(в качестве альтернативных обозначенийmd5для совместимости со старыми версиями сервера поддерживаются значенияonиoff). Заметьте, что поддержкаscram-sha-256появилась в Postgres Pro версии 10 и со старыми версиями серверов этот вариант работать не будет. ЕслиalgorithmравенNULL, эта функция запросит у сервера текущее значение параметра password_encryption. При этом возможна блокировка и отказ при выполнении функции, если текущая транзакция прерывается или если в текущем соединении выполняется другой запрос. Если вы хотите использовать алгоритм по умолчанию для данного сервера, но при этом избежать блокировки, получите значениеpassword_encryptionсамостоятельно до вызоваPQencryptPasswordConnи передайте его в параметреalgorithm.Эта функция возвращает строку, выделенную функцией
malloc. Вызывающий код может рассчитывать на то, что эта строка не содержит никаких спецсимволов, требующих экранирования. Закончив работу с ней, освободите память, вызвавPQfreemem. В случае ошибки эта функция возвращаетNULL, а соответствующее сообщение помещается в объект соединения.-
PQencryptPassword Подготавливает зашифрованную md5 форму пароля Postgres Pro.
char *PQencryptPassword(const char *passwd, const char *user);
PQencryptPassword— старая, подлежащая ликвидации версияPQencryptPasswordConn. Отличие состоит в том, что дляPQencryptPasswordне требуется объект соединения, а в качестве алгоритма шифрования всегда используетсяmd5.-
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(см. Раздел 33.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.Это число формируется в результате умножения номера основной версии библиотеки на 10000 и добавления номера дополнительной версии. Например, для версии 10.1 будет выдано 100001, а для версии 11.0 — 110000.
До версии 10, в Postgres Pro номера версий образовывались из трёх чисел, первые два из которых представляли основную версию. Для таких версий
PQlibVersionотводит на каждое число по две цифры; например, для версии 9.1.5 будет выдано 90105, а для версии 9.2.0 — 90200.Таким образом, чтобы получить логический номер версии для определения доступности функционала, приложения должны разделить результат
PQlibVersionна 100, а не на 10000. Во всех сериях номера дополнительных (корректирующих) выпусков различаются только в двух последних цифрах.Примечание
Эта функция появилась в PostgreSQL версии 9.1, поэтому с её помощью нельзя проверить функциональность предыдущих версий, так как при вызове её будет создана зависимость от версии 9.1 или новее.
33.11. Miscellaneous Functions
As always, there are some functions that just don't fit anywhere.
-
PQfreemem Frees memory allocated by libpq.
void PQfreemem(void *ptr);
Frees memory allocated by libpq, particularly
PQescapeByteaConn,PQescapeBytea,PQunescapeBytea, andPQnotifies. It is particularly important that this function, rather thanfree(), be used on Microsoft Windows. This is because allocating memory in a DLL and releasing it in the application works only if multithreaded/single-threaded, release/debug, and static/dynamic flags are the same for the DLL and the application. On non-Microsoft Windows platforms, this function is the same as the standard library functionfree().-
PQconninfoFree Frees the data structures allocated by
PQconndefaultsorPQconninfoParse.void PQconninfoFree(PQconninfoOption *connOptions);
A simple
PQfreememwill not do for this, since the array contains references to subsidiary strings.-
PQencryptPasswordConn Prepares the encrypted form of a Postgres Pro password.
char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
This function is intended to be used by client applications that wish to send commands like
ALTER USER joe PASSWORD 'pwd'. It is good practice not to send the original cleartext password in such a command, because it might be exposed in command logs, activity displays, and so on. Instead, use this function to convert the password to encrypted form before it is sent.The
passwdanduserarguments are the cleartext password, and the SQL name of the user it is for.algorithmspecifies the encryption algorithm to use to encrypt the password. Currently supported algorithms aremd5andscram-sha-256(onandoffare also accepted as aliases formd5, for compatibility with older server versions). Note that support forscram-sha-256was introduced in Postgres Pro version 10, and will not work correctly with older server versions. IfalgorithmisNULL, this function will query the server for the current value of the password_encryption setting. That can block, and will fail if the current transaction is aborted, or if the connection is busy executing another query. If you wish to use the default algorithm for the server but want to avoid blocking, querypassword_encryptionyourself before callingPQencryptPasswordConn, and pass that value as thealgorithm.The return value is a string allocated by
malloc. The caller can assume the string doesn't contain any special characters that would require escaping. UsePQfreememto free the result when done with it. On error, returnsNULL, and a suitable message is stored in the connection object.-
PQencryptPassword Prepares the md5-encrypted form of a Postgres Pro password.
char *PQencryptPassword(const char *passwd, const char *user);
PQencryptPasswordis an older, deprecated version ofPQencryptPasswordConn. The difference is thatPQencryptPassworddoes not require a connection object, andmd5is always used as the encryption algorithm.-
PQmakeEmptyPGresult Constructs an empty
PGresultobject with the given status.PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
This is libpq's internal function to allocate and initialize an empty
PGresultobject. This function returnsNULLif memory could not be allocated. It is exported because some applications find it useful to generate result objects (particularly objects with error status) themselves. Ifconnis not null andstatusindicates an error, the current error message of the specified connection is copied into thePGresult. Also, ifconnis not null, any event procedures registered in the connection are copied into thePGresult. (They do not getPGEVT_RESULTCREATEcalls, but seePQfireResultCreateEvents.) Note thatPQclearshould eventually be called on the object, just as with aPGresultreturned by libpq itself.-
PQfireResultCreateEvents Fires a
PGEVT_RESULTCREATEevent (see Section 33.13) for each event procedure registered in thePGresultobject. Returns non-zero for success, zero if any event procedure fails.int PQfireResultCreateEvents(PGconn *conn, PGresult *res);
The
connargument is passed through to event procedures but not used directly. It can beNULLif the event procedures won't use it.Event procedures that have already received a
PGEVT_RESULTCREATEorPGEVT_RESULTCOPYevent for this object are not fired again.The main reason that this function is separate from
PQmakeEmptyPGresultis that it is often appropriate to create aPGresultand fill it with data before invoking the event procedures.-
PQcopyResult Makes a copy of a
PGresultobject. The copy is not linked to the source result in any way andPQclearmust be called when the copy is no longer needed. If the function fails,NULLis returned.PGresult *PQcopyResult(const PGresult *src, int flags);
This is not intended to make an exact copy. The returned result is always put into
PGRES_TUPLES_OKstatus, and does not copy any error message in the source. (It does copy the command status string, however.) Theflagsargument determines what else is copied. It is a bitwise OR of several flags.PG_COPYRES_ATTRSspecifies copying the source result's attributes (column definitions).PG_COPYRES_TUPLESspecifies copying the source result's tuples. (This implies copying the attributes, too.)PG_COPYRES_NOTICEHOOKSspecifies copying the source result's notify hooks.PG_COPYRES_EVENTSspecifies copying the source result's events. (But any instance data associated with the source is not copied.)-
PQsetResultAttrs Sets the attributes of a
PGresultobject.int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs);
The provided
attDescsare copied into the result. If theattDescspointer isNULLornumAttributesis less than one, the request is ignored and the function succeeds. Ifresalready contains attributes, the function will fail. If the function fails, the return value is zero. If the function succeeds, the return value is non-zero.-
PQsetvalue Sets a tuple field value of a
PGresultobject.int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len);
The function will automatically grow the result's internal tuples array as needed. However, the
tup_numargument must be less than or equal toPQntuples, meaning this function can only grow the tuples array one tuple at a time. But any field of any existing tuple can be modified in any order. If a value atfield_numalready exists, it will be overwritten. Iflenis -1 orvalueisNULL, the field value will be set to an SQL null value. Thevalueis copied into the result's private storage, thus is no longer needed after the function returns. If the function fails, the return value is zero. If the function succeeds, the return value is non-zero.-
PQresultAlloc Allocate subsidiary storage for a
PGresultobject.void *PQresultAlloc(PGresult *res, size_t nBytes);
Any memory allocated with this function will be freed when
resis cleared. If the function fails, the return value isNULL. The result is guaranteed to be adequately aligned for any type of data, just as formalloc.-
PQlibVersion Return the version of libpq that is being used.
int PQlibVersion(void);
The result of this function can be used to determine, at run time, whether specific functionality is available in the currently loaded version of libpq. The function can be used, for example, to determine which connection options are available in
PQconnectdb.The result is formed by multiplying the library's major version number by 10000 and adding the minor version number. For example, version 10.1 will be returned as 100001, and version 11.0 will be returned as 110000.
Prior to major version 10, Postgres Pro used three-part version numbers in which the first two parts together represented the major version. For those versions,
PQlibVersionuses two digits for each part; for example version 9.1.5 will be returned as 90105, and version 9.2.0 will be returned as 90200.Therefore, for purposes of determining feature compatibility, applications should divide the result of
PQlibVersionby 100 not 10000 to determine a logical major version number. In all release series, only the last two digits differ between minor releases (bug-fix releases).Note
This function appeared in PostgreSQL version 9.1, so it cannot be used to detect required functionality in earlier versions, since calling it will create a link dependency on version 9.1 or later.