36.2. Функции, описывающие текущее состояние подключения
Эти функции могут использоваться для опроса состояния объекта, описывающего существующее подключение к базе данных.
Подсказка
Разработчики приложений на основе libpq должны тщательно поддерживать абстракцию PGconn. Следует использовать функции доступа, описанные ниже, для получения содержимого PGconn. Обращение напрямую к внутренним полям PGconn, используя сведения из libpq-int.h, не рекомендуется, поскольку они могут измениться в будущем.
Следующие функции возвращают значения параметров, которые были установлены в момент подключения. Эти значения не изменяются во время жизни соединения. Если используется строка соединения с несколькими узлами, значения PQhost, PQport и PQpass могут меняться, если с тем же объектом PGconn устанавливается новое соединение. Другие значения не меняются на протяжении жизни объекта PGconn.
PQdbВозвращает имя базы данных, с которой установлено соединение.
char *PQdb(const PGconn *conn);
PQuserВозвращает имя пользователя, который установил соединение.
char *PQuser(const PGconn *conn);
PQpassВозвращает пароль, использованный для подключения.
char *PQpass(const PGconn *conn);
PQpassвозвратит либо пароль, указанный в параметрах подключения, либо пароль, полученный из файла паролей (в случае отсутствия первого). Во втором случае, если в параметрах подключения было указано несколько узлов, полагаться на результатPQpassнельзя, пока соединение не будет установлено. Состояние подключения позволяет проверить функцияPQstatus.PQhostВозвращает имя сервера для активного соединения. Это может быть имя узла, IP-адрес или путь к каталогу, если подключение установлено через сокет Unix. (Признаком подключения к сокету будет абсолютный путь, который начинается с
/.)char *PQhost(const PGconn *conn);
Если в параметрах подключения был задан и
host, иhostaddr, функцияPQhostвыдаст содержимоеhost. Если был задан толькоhostaddr, возвращается это значение. Если в параметрах подключения было задано несколько узлов,PQhostвозвращает адрес узла, с которым фактически установлено соединение.PQhostвозвращаетNULL, если аргументconnравенNULL. Иначе в случае ошибки при получении информации об узле (это возможно, если соединение не установлено до конца или произошла ошибка) она возвращает пустую строку.Если в параметрах подключения указаны несколько узлов, на результат
PQhostнельзя полагаться, пока соединение не будет установлено. Проверить состояние соединения позволяет функцияPQstatus.PQhostaddrВозвращает IP-адрес сервера для активного соединения. Это может быть адрес, в который разрешилось имя узла, или IP-адрес, переданный в параметре
hostaddr.char *PQhostaddr(const PGconn *conn);
PQhostaddrвозвращаетNULL, если аргументconnравенNULL. Иначе в случае ошибки при получении информации об узле (это возможно, если соединение не установлено до конца или произошла ошибка) она возвращает пустую строку.PQportВозвращает номер порта активного соединения.
char *PQport(const PGconn *conn);
Если в параметрах подключения было задано несколько портов,
PQportвозвращает порт, с которым фактически установлено соединение.PQportвозвращаетNULL, если аргументconnравенNULL. Иначе в случае ошибки при получении информации о порте (это возможно, если соединение не установлено до конца или произошла ошибка) она возвращает пустую строку.Если в параметрах подключения указаны несколько портов, на результат
PQportнельзя полагаться, пока соединение не будет установлено. Проверить состояние соединения позволяет функцияPQstatus.PQttyЭта функция теперь ничего не делает, но необходима для обратной совместимости. Функция всегда возвращает пустую строку или
NULL, если аргументconnимеет значениеNULL.char *PQtty(const PGconn *conn);
PQoptionsВозвращает параметры командной строки, переданные в запросе на подключение.
char *PQoptions(const PGconn *conn);
Следующие функции возвращают данные статуса, который может измениться в процессе выполнения операций на объекте PGconn.
PQstatusВозвращает состояние подключения.
ConnStatusType PQstatus(const PGconn *conn);
Статус может принимать одно из ряда значений. Однако только два из них видны извне процедуры асинхронного подключения:
CONNECTION_OKиCONNECTION_BAD. Успешное подключение к базе данных имеет статусCONNECTION_OK. О неудачной попытке подключения сигнализирует статусCONNECTION_BAD. Обычно статус OK остаётся таковым до вызоваPQfinish, но в случае ошибки соединения статус может смениться наCONNECTION_BADпреждевременно. В таком случае приложение может попытаться восстановить подключение, вызвавPQreset.О других кодах состояния, которые могут выдать эти функции, можно узнать в описании
PQconnectStartParams,PQconnectStartиPQconnectPoll.PQtransactionStatusВозвращает текущий статус сервера, отражающий процесс выполнения транзакций.
PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
Статус может быть одним из
PQTRANS_IDLE(в настоящее время не занят обработкой транзакции),PQTRANS_ACTIVE(команда в процессе обработки),PQTRANS_INTRANS(не выполняет работу, но находится в рамках действительной транзакции) илиPQTRANS_INERROR(не выполняет работу, но находится в рамках транзакции, завершившейся сбоем). Статус принимает значениеPQTRANS_UNKNOWN, если соединение не работает. Статус принимает значениеPQTRANS_ACTIVEтолько тогда, когда запрос был отправлен серверу, но ещё не завершён.PQparameterStatusОтыскивает текущее значение параметра сервера.
const char *PQparameterStatus(const PGconn *conn, const char *paramName);
Значения определённых параметров сервер сообщает автоматически в начале процедуры подключения или тогда, когда их значения изменяются.
PQparameterStatusможно использовать, чтобы запросить эти значения. Функция возвращает текущее значение параметра, если оно известно, илиNULL, если параметр неизвестен.Параметры, значения которых сообщает сервер, в текущей версии включают
server_version,server_encoding,client_encoding,application_name,is_superuser,session_authorization,DateStyle,IntervalStyle,TimeZone,integer_datetimesиstandard_conforming_strings. (Значения параметровserver_encoding,TimeZoneиinteger_datetimesсервер до версии 8.0 не сообщал;standard_conforming_stringsсервер до версии 8.1 не сообщал;IntervalStyleсервер до версии 8.4 не сообщал;application_nameсервер до версии 9.0 не сообщал.) Учтите, чтоserver_version,server_encodingиinteger_datetimesнельзя изменить после запуска.Если для
standard_conforming_stringsне передано никакого значения, то приложения могут принять его равнымoff. Это означает, что символы обратной косой черты в строковых литералах интерпретируются в качестве спецсимволов. Также, наличие этого параметра может рассматриваться как указание на то, что синтаксис escape-строк (E'...') является приемлемым.Хотя возвращаемый указатель объявлен со спецификатором
const, фактически он указывает на изменяемое хранилище, связанное со структуройPGconn. Не стоит рассчитывать на то, что указатель останется действительным при последующих запросах.PQprotocolVersionЗапрашивает протокол, используемый между клиентом и сервером.
int PQprotocolVersion(const PGconn *conn);
Приложения могут использовать эту функцию, чтобы определить, поддерживаются ли опредёленные функциональные возможности. В настоящее время возможными значениями являются 3 (протокол версии 3.0) или ноль (проблемы в подключении). Версия протокола не будет изменяться после завершения процедуры подключения, но теоретически она могла бы измениться в процессе переподключения. Версия протокола 3.0 обычно используется при взаимодействии с серверами PostgreSQL версии 7.4 или более поздними.
PQserverVersionВозвращает целочисленное представление версии сервера.
int PQserverVersion(const PGconn *conn);
Приложения могут использовать эту функцию, чтобы определить версию сервера баз данных, к которому они подключены. Возвращаемое ей число получается в результате умножения номера основной версии на 10000 и добавления номера дополнительной версии. Например, для версии 10.1 будет выдано число 100001, а для версии 11.0 — 110000. Если соединение не работает, то возвращается ноль.
До версии 10 в Postgres Pro номера версий образовывались из трёх чисел, первые два из которых представляли основную версию. Для таких версий
PQserverVersionотводит на каждое число по две цифры; например, для версии 9.1.5 будет выдано 90105, а для версии 9.2.0 — 90200.Таким образом, чтобы получить логический номер основной версии для определения доступности функциональности, приложения должны разделить результат
PQserverVersionна 100, а не на 10000. Во всех сериях номера дополнительных (корректирующих) выпусков различаются только в двух последних цифрах.PQerrorMessageВозвращает сообщение об ошибке, наиболее недавно сгенерированное операцией, выполненной в рамках текущего подключения.
char *PQerrorMessage(const PGconn *conn);
Почти все функции библиотеки libpq в случае сбоя сформируют сообщение для
PQerrorMessage. Обратите внимание, что по соглашениям, принятым в libpq, непустой результат функцииPQerrorMessageможет состоять из нескольких строк и будет включать завершающий символ новой строки. Вызывающая функция не должна освобождать память, на которую указывает возвращаемое значение, напрямую. Она будет освобождена, когда связанный с ней дескрипторPGconnбудет передан функцииPQfinish. Не стоит ожидать, что результирующая строка останется той же самой при выполнении нескольких операций со структуройPGconn.PQsocketПолучает номер файлового дескриптора для сокета соединения с сервером. Действительный дескриптор будет больше или равен 0; значение -1 показывает, что в данный момент не открыто ни одного соединения с сервером. (Значение не изменится во время обычной работы, но может измениться во время установки или переустановки подключения.)
int PQsocket(const PGconn *conn);
PQbackendPIDВозвращает ID (PID) серверного процесса, обрабатывающего это подключение.
int PQbackendPID(const PGconn *conn);
PID серверного процесса полезен для отладочных целей и для сопоставления с сообщениями команды
NOTIFY(которые включают PID уведомляющего серверного процесса). Примите к сведению, что PID принадлежит процессу, выполняющемуся на узле сервера баз данных, а не на локальном узле.PQconnectionNeedsPasswordВозвращает true (1), если метод аутентификации соединения требовал пароля, однако он не был предоставлен. Возвращает false (0), если пароль не требовался.
int PQconnectionNeedsPassword(const PGconn *conn);
Эту функцию можно применить после неудачной попытки подключения, чтобы решить, нужно ли предлагать пользователю ввести пароль.
PQconnectionUsedPasswordВозвращает true (1), если метод аутентификации соединения использовал пароль. Возвращает false (0) в противном случае.
int PQconnectionUsedPassword(const PGconn *conn);
Эту функцию можно применить как после неудачной, так и после успешной попытки подключения, чтобы определить, требовал ли сервер предоставления пароля.
Следующие функции возвращают информацию, относящуюся к SSL. Эта информация обычно не меняется после того, как подключение установлено.
PQsslInUseВозвращает true (1), если для текущего подключения используется SSL, и false (0) в противном случае.
int PQsslInUse(const PGconn *conn);
PQsslAttributeВозвращает связанную с SSL информацию о соединении.
const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
Список доступных атрибутов зависит от используемой библиотеки SSL и типа подключения. Если подключение не использует SSL или указанное имя атрибута неизвестно используемой библиотеке, возвращается NULL.
Обычно доступны следующие атрибуты:
libraryИмя используемой реализации SSL. (В настоящее время поддерживается только
"OpenSSL")protocolПрименяемая версия SSL/TLS. Наиболее распространены варианты
"TLSv1","TLSv1.1"и"TLSv1.2", но реализация может возвращать и другие строки, если применяется какой-то другой протокол.key_bitsЧисло бит в ключе, используемом алгоритмом шифрования.
cipherКраткое имя применяемого комплекта шифров, например:
"DHE-RSA-DES-CBC3-SHA". Эти имена могут быть разными в разных реализациях SSL.compressionВозвращает
on, если используется сжатие SSL, илиoffв противном случае.
В качестве исключения можно запросить атрибут
libraryбез подключения, передав NULL в качестве аргументаconn. В результате будет выдано имя используемой по умолчанию библиотеки SSL, либо NULL, если библиотека libpq была скомпилирована без поддержки SSL. (В версиях Postgres Pro ниже 15, когда вconnпередавался NULL, результатом всегда был NULL. Отличить новую реализацию от старой в клиентских программах можно, проверив макросLIBPQ_HAS_SSL_LIBRARY_DETECTION.)PQsslAttributeNamesВозвращает массив имён доступных атрибутов SSL. Завершается массив указателем NULL.
const char * const * PQsslAttributeNames(const PGconn *conn);
PQsslStructВозвращает указатель на специфичный для реализации SSL объект, описывающий подключение. Если соединение не зашифровано или реализация SSL, используемая для подключения, не поддерживает запрошенный тип объекта, возвращается NULL.
void *PQsslStruct(const PGconn *conn, const char *struct_name);
Какие структуры можно получить, зависит от используемой реализации SSL. OpenSSL предоставляет одну структуру с именем
OpenSSLи возвращает указатель на объектSSLstruct, описанный в OpenSSL. Для написания вызова этой функции можно воспользоваться кодом в следующих строках:#include <libpq-fe.h> #include <openssl/ssl.h> ... SSL *ssl; dbconn = PQconnectdb(...); ... ssl = PQsslStruct(dbconn, "OpenSSL"); if (ssl) { /* use OpenSSL functions to access ssl */ }Эта структура может использоваться, чтобы сличить уровни шифрования, проверить сертификаты сервера и т. д. За информацией об этой структуре обратитесь к документации по OpenSSL.
PQgetsslВозвращает структуру SSL, использовавшуюся в соединении, или NULL, если SSL не используется.
void *PQgetssl(const PGconn *conn);
Эта функция равнозначна
PQsslStruct(conn, "OpenSSL"). Её не следует применять в новых приложениях, так как возвращаемая структура специфична для OpenSSL и её нельзя будет получить с другой реализацией SSL. Чтобы проверить, использует ли подключение SSL, лучше вызватьPQsslInUse, а чтобы получить свойства подключения —PQsslAttribute.
36.2. Connection Status Functions
These functions can be used to interrogate the status of an existing database connection object.
Tip
libpq application programmers should be careful to maintain the PGconn abstraction. Use the accessor functions described below to get at the contents of PGconn. Reference to internal PGconn fields using libpq-int.h is not recommended because they are subject to change in the future.
The following functions return parameter values established at connection. These values are fixed for the life of the connection. If a multi-host connection string is used, the values of PQhost, PQport, and PQpass can change if a new connection is established using the same PGconn object. Other values are fixed for the lifetime of the PGconn object.
PQdbReturns the database name of the connection.
char *PQdb(const PGconn *conn);
PQuserReturns the user name of the connection.
char *PQuser(const PGconn *conn);
PQpassReturns the password of the connection.
char *PQpass(const PGconn *conn);
PQpasswill return either the password specified in the connection parameters, or if there was none and the password was obtained from the password file, it will return that. In the latter case, if multiple hosts were specified in the connection parameters, it is not possible to rely on the result ofPQpassuntil the connection is established. The status of the connection can be checked using the functionPQstatus.PQhostReturns the server host name of the active connection. This can be a host name, an IP address, or a directory path if the connection is via Unix socket. (The path case can be distinguished because it will always be an absolute path, beginning with
/.)char *PQhost(const PGconn *conn);
If the connection parameters specified both
hostandhostaddr, thenPQhostwill return thehostinformation. If onlyhostaddrwas specified, then that is returned. If multiple hosts were specified in the connection parameters,PQhostreturns the host actually connected to.PQhostreturnsNULLif theconnargument isNULL. Otherwise, if there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.If multiple hosts were specified in the connection parameters, it is not possible to rely on the result of
PQhostuntil the connection is established. The status of the connection can be checked using the functionPQstatus.PQhostaddrReturns the server IP address of the active connection. This can be the address that a host name resolved to, or an IP address provided through the
hostaddrparameter.char *PQhostaddr(const PGconn *conn);
PQhostaddrreturnsNULLif theconnargument isNULL. Otherwise, if there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.PQportReturns the port of the active connection.
char *PQport(const PGconn *conn);
If multiple ports were specified in the connection parameters,
PQportreturns the port actually connected to.PQportreturnsNULLif theconnargument isNULL. Otherwise, if there is an error producing the port information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.If multiple ports were specified in the connection parameters, it is not possible to rely on the result of
PQportuntil the connection is established. The status of the connection can be checked using the functionPQstatus.PQttyThis function no longer does anything, but it remains for backwards compatibility. The function always return an empty string, or
NULLif theconnargument isNULL.char *PQtty(const PGconn *conn);
PQoptionsReturns the command-line options passed in the connection request.
char *PQoptions(const PGconn *conn);
The following functions return status data that can change as operations are executed on the PGconn object.
PQstatusReturns the status of the connection.
ConnStatusType PQstatus(const PGconn *conn);
The status can be one of a number of values. However, only two of these are seen outside of an asynchronous connection procedure:
CONNECTION_OKandCONNECTION_BAD. A good connection to the database has the statusCONNECTION_OK. A failed connection attempt is signaled by statusCONNECTION_BAD. Ordinarily, an OK status will remain so untilPQfinish, but a communications failure might result in the status changing toCONNECTION_BADprematurely. In that case the application could try to recover by callingPQreset.See the entry for
PQconnectStartParams,PQconnectStartandPQconnectPollwith regards to other status codes that might be returned.PQtransactionStatusReturns the current in-transaction status of the server.
PGTransactionStatusType PQtransactionStatus(const PGconn *conn);
The status can be
PQTRANS_IDLE(currently idle),PQTRANS_ACTIVE(a command is in progress),PQTRANS_INTRANS(idle, in a valid transaction block), orPQTRANS_INERROR(idle, in a failed transaction block).PQTRANS_UNKNOWNis reported if the connection is bad.PQTRANS_ACTIVEis reported only when a query has been sent to the server and not yet completed.PQparameterStatusLooks up a current parameter setting of the server.
const char *PQparameterStatus(const PGconn *conn, const char *paramName);
Certain parameter values are reported by the server automatically at connection startup or whenever their values change.
PQparameterStatuscan be used to interrogate these settings. It returns the current value of a parameter if known, orNULLif the parameter is not known.Parameters reported as of the current release include
server_version,server_encoding,client_encoding,application_name,default_transaction_read_only,in_hot_standby,is_superuser,session_authorization,DateStyle,IntervalStyle,TimeZone,integer_datetimes, andstandard_conforming_strings. (server_encoding,TimeZone, andinteger_datetimeswere not reported by releases before 8.0;standard_conforming_stringswas not reported by releases before 8.1;IntervalStylewas not reported by releases before 8.4;application_namewas not reported by releases before 9.0;default_transaction_read_onlyandin_hot_standbywere not reported by releases before 14.) Note thatserver_version,server_encodingandinteger_datetimescannot change after startup.If no value for
standard_conforming_stringsis reported, applications can assume it isoff, that is, backslashes are treated as escapes in string literals. Also, the presence of this parameter can be taken as an indication that the escape string syntax (E'...') is accepted.Although the returned pointer is declared
const, it in fact points to mutable storage associated with thePGconnstructure. It is unwise to assume the pointer will remain valid across queries.PQprotocolVersionInterrogates the frontend/backend protocol being used.
int PQprotocolVersion(const PGconn *conn);
Applications might wish to use this function to determine whether certain features are supported. Currently, the possible values are 3 (3.0 protocol), or zero (connection bad). The protocol version will not change after connection startup is complete, but it could theoretically change during a connection reset. The 3.0 protocol is supported by PostgreSQL server versions 7.4 and above.
PQserverVersionReturns an integer representing the server version.
int PQserverVersion(const PGconn *conn);
Applications might use this function to determine the version of the database server they are connected to. The result is formed by multiplying the server'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. Zero is returned if the connection is bad.
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,
PQserverVersionuses 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
PQserverVersionby 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).PQerrorMessageReturns the error message most recently generated by an operation on the connection.
char *PQerrorMessage(const PGconn *conn);
Nearly all libpq functions will set a message for
PQerrorMessageif they fail. Note that by libpq convention, a nonemptyPQerrorMessageresult can consist of multiple lines, and will include a trailing newline. The caller should not free the result directly. It will be freed when the associatedPGconnhandle is passed toPQfinish. The result string should not be expected to remain the same across operations on thePGconnstructure.PQsocketObtains the file descriptor number of the connection socket to the server. A valid descriptor will be greater than or equal to 0; a result of -1 indicates that no server connection is currently open. (This will not change during normal operation, but could change during connection setup or reset.)
int PQsocket(const PGconn *conn);
PQbackendPIDReturns the process ID (PID) of the backend process handling this connection.
int PQbackendPID(const PGconn *conn);
The backend PID is useful for debugging purposes and for comparison to
NOTIFYmessages (which include the PID of the notifying backend process). Note that the PID belongs to a process executing on the database server host, not the local host!PQconnectionNeedsPasswordReturns true (1) if the connection authentication method required a password, but none was available. Returns false (0) if not.
int PQconnectionNeedsPassword(const PGconn *conn);
This function can be applied after a failed connection attempt to decide whether to prompt the user for a password.
PQconnectionUsedPasswordReturns true (1) if the connection authentication method used a password. Returns false (0) if not.
int PQconnectionUsedPassword(const PGconn *conn);
This function can be applied after either a failed or successful connection attempt to detect whether the server demanded a password.
The following functions return information related to SSL. This information usually doesn't change after a connection is established.
PQsslInUseReturns true (1) if the connection uses SSL, false (0) if not.
int PQsslInUse(const PGconn *conn);
PQsslAttributeReturns SSL-related information about the connection.
const char *PQsslAttribute(const PGconn *conn, const char *attribute_name);
The list of available attributes varies depending on the SSL library being used and the type of connection. Returns NULL if the connection does not use SSL or the specified attribute name is not defined for the library in use.
The following attributes are commonly available:
libraryName of the SSL implementation in use. (Currently, only
"OpenSSL"is implemented)protocolSSL/TLS version in use. Common values are
"TLSv1","TLSv1.1"and"TLSv1.2", but an implementation may return other strings if some other protocol is used.key_bitsNumber of key bits used by the encryption algorithm.
cipherA short name of the ciphersuite used, e.g.,
"DHE-RSA-DES-CBC3-SHA". The names are specific to each SSL implementation.compressionReturns "on" if SSL compression is in use, else it returns "off".
As a special case, the
libraryattribute may be queried without a connection by passing NULL as theconnargument. The result will be the default SSL library name, or NULL if libpq was compiled without any SSL support. (Prior to Postgres Pro version 15, passing NULL as theconnargument always resulted in NULL. Client programs needing to differentiate between the newer and older implementations of this case may check theLIBPQ_HAS_SSL_LIBRARY_DETECTIONfeature macro.)PQsslAttributeNamesReturns an array of SSL attribute names available. The array is terminated by a NULL pointer.
const char * const * PQsslAttributeNames(const PGconn *conn);
PQsslStructReturns a pointer to an SSL-implementation-specific object describing the connection. Returns NULL if the connection is not encrypted or the requested type of object is not available from the connection's SSL implementation.
void *PQsslStruct(const PGconn *conn, const char *struct_name);
The struct(s) available depend on the SSL implementation in use. For OpenSSL, there is one struct, available under the name
OpenSSL, and it returns a pointer to OpenSSL'sSSLstruct. To use this function, code along the following lines could be used:#include <libpq-fe.h> #include <openssl/ssl.h> ... SSL *ssl; dbconn = PQconnectdb(...); ... ssl = PQsslStruct(dbconn, "OpenSSL"); if (ssl) { /* use OpenSSL functions to access ssl */ }This structure can be used to verify encryption levels, check server certificates, and more. Refer to the OpenSSL documentation for information about this structure.
PQgetsslReturns the SSL structure used in the connection, or NULL if SSL is not in use.
void *PQgetssl(const PGconn *conn);
This function is equivalent to
PQsslStruct(conn, "OpenSSL"). It should not be used in new applications, because the returned struct is specific to OpenSSL and will not be available if another SSL implementation is used. To check if a connection uses SSL, callPQsslInUseinstead, and for more details about the connection, usePQsslAttribute.