35.1. Функции управления подключением к базе данных
Следующие функции имеют дело с созданием подключения к серверу Postgres Pro. Прикладная программа может иметь несколько подключений к серверу, открытых одновременно. (Одна из причин этого заключается в необходимости доступа к более чем одной базе данных.) Каждое соединение представляется объектом PGconn, который можно получить от функций PQconnectdb, PQconnectdbParams или PQsetdbLogin. Обратите внимание, что эти функции всегда возвратят ненулевой указатель на объект, если только, возможно, не осталось слишком мало памяти даже для того, чтобы выделить её для объекта PGconn. Прежде чем передавать запросы через объект подключения, следует вызвать функцию PQstatus для проверки возвращаемого значения в случае успешного подключения.
Предупреждение
Если к базе данных, которая не приведена в соответствие шаблону безопасного использования схем, имеют доступ недоверенные пользователи, начинайте сеанс с удаления доступных им для записи схем из пути поиска (search_path). Для этого можно присвоить параметру с ключом options значение -csearch_path=. Также можно выполнить PQexec( после подключения. Это касается не только psql, но и любых других интерфейсов для выполнения произвольных SQL-команд.соединение, "SELECT pg_catalog.set_config('search_path', '', false)")
Предупреждение
В системе Unix создание дочернего процесса на основе процесса, уже имеющего открытые подключения с помощью libpq, может привести к непредсказуемым результатам, потому что родительский и дочерний процессы совместно используют одни и те же сокеты и ресурсы операционной системы. По этой причине подобный подход не рекомендуется. Однако использование системного вызова exec из дочернего процесса для загрузки нового исполняемого файла является безопасным.
PQconnectdbParamsСоздаёт новое подключение к серверу баз данных.
PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname);Эта функция открывает новое соединение с базой данных, используя параметры, содержащиеся в двух массивах, завершающихся символом
NULL. Первый из них,keywords, определяется как массив строк, каждая из которых представляет собой ключевое слово. Второй,values, даёт значение для каждого ключевого слова. В отличие отPQsetdbLogin, описываемой ниже, набор параметров может быть расширен без изменения сигнатуры функции, поэтому использование данной функции (или её неблокирующих аналоговPQconnectStartParamsиPQconnectPoll) является предпочтительным при разработке новых приложений.Ключевые слова-параметры, распознаваемые в настоящее время, приведены в Подразделе 35.1.2.
Передаваемые массивы могут быть пустыми (в этом случае будут использоваться все параметры по умолчанию) или содержать одно или несколько имён/значений параметров. При этом они должны быть одинаковой длины. Просмотр массивов завершается, как только в массиве
keywordsвстречаетсяNULL. Если элемент массиваvalues, соответствующий отличному отNULLэлементуkeywords, содержит пустую строку или NULL, такой параметр пропускается и просматривается следующая пара элементов массива.Когда
expand_dbnameимеет ненулевое значение, первый параметрdbnameможет содержать строку подключения. В этом случае она «разворачивается» в отдельные параметры подключения, извлечённые из этой строки. Значение считается строкой подключения, а не просто именем базы данных, если оно содержит знак равно (=) или начинается с обозначения схемы URI. (Подробнее форматы строк подключения описаны в Подразделе 35.1.1.) Таким способом обрабатывается только первое вхождениеdbname, следующие параметрыdbnameбудут восприниматься как просто имя базы данных.Как правило, массивы параметров обрабатываются от начала к концу. Если какой-либо параметр указывается неоднократно, использоваться будет последнее значение (отличное от
NULLи непустое). Это справедливо, в частности, и тогда, когда ключевое слово, заданное в строке подключения, конфликтует с заданным в массивеkeywords. Таким образом, программист может по своему усмотрению решить, будут ли значения в массиве переопределять значения, заданными в строке подключения, или переопределяться ими. Элементы массива, предшествующие развёрнутому значениюdbname, могут быть переопределены значениями в строке подключения, которые в свою очередь переопределяются элементами массива, следующими послеdbname(и в этом случае речь идёт о непустых значениях).После разбора всех элементов массива и развёрнутой строки подключения (если она задана), параметры подключения, которые остались незаданными, получают значения по умолчанию. Если незаданному параметру соответствует установленная переменная окружения (см. Раздел 35.14), будет использоваться её значение. Если такая переменная не задана, для параметра будет использоваться встроенное значение по умолчанию.
PQconnectdbСоздаёт новое подключение к серверу баз данных.
PGconn *PQconnectdb(const char *conninfo);
Эта функция открывает новое соединение с базой данных, используя параметры, полученные из строки
conninfo.Передаваемая строка может быть пустой. В этом случае используются все параметры по умолчанию. Она также может содержать одно или более значений параметров, разделённых пробелами, или URI. За подробностями обратитесь к Подразделу 35.1.1.
PQsetdbLoginСоздаёт новое подключение к серверу баз данных.
PGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd);Это предшественница функции
PQconnectdbс фиксированным набором параметров. Она имеет такую же функциональность, за исключением того, что непереданные параметры всегда принимают значения по умолчанию. ПодставьтеNULLили пустую строку в качестве любого из фиксированных параметров, которые должны принять значения по умолчанию.Если параметр
dbNameсодержит знак=или имеет допустимый префикс URI для подключения, то он воспринимается в качестве строкиconninfoточно таким же образом, как если бы он был передан функцииPQconnectdb, а оставшиеся параметры затем применяются, как указано дляPQconnectdbParams.PQsetdbСоздаёт новое подключение к серверу баз данных.
PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);Это макрос, который вызывает
PQsetdbLoginс нулевыми указателями в качестве значений параметровloginиpwd. Обеспечивает обратную совместимость с очень старыми программами.PQconnectStartParamsPQconnectStartPQconnectPollСоздают подключение к серверу баз данных неблокирующим способом.
PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname); PGconn *PQconnectStart(const char *conninfo); PostgresPollingStatusType PQconnectPoll(PGconn *conn);Три эти функции используются для того, чтобы открыть подключение к серверу баз данных таким образом, чтобы поток исполнения вашего приложения не был заблокирован при выполнении удалённой операции ввода/вывода в процессе подключения. Суть этого подхода в том, чтобы ожидание завершения операций ввода/вывода могло происходить в главном цикле приложения, а не в внутри функций
PQconnectdbParamsилиPQconnectdb, с тем, чтобы приложение могло управлять этой операцией параллельно с другой работой.С помощью функции
PQconnectStartParamsподключение к базе данных выполняется, используя параметры, взятые из массивовkeywordsиvalues, а управление осуществляется с помощьюexpand_dbname, как описано выше дляPQconnectdbParams.С помощью функции
PQconnectStartподключение к базе данных выполняется, используя параметры, взятые из строкиconninfo, как описано выше дляPQconnectdb.Ни
PQconnectStartParams, ниPQconnectStart, ниPQconnectPollне заблокируются до тех пор, пока выполняется ряд ограничений:Параметр
hostaddrдолжен использоваться так, чтобы для разрешения заданного имени не требовалось выполнять запросы DNS. Подробнее этот параметр описан в Подразделе 35.1.2.Если вы вызываете
PQtrace, обеспечьте, чтобы поток, в который выводится трассировочная информация, не заблокировался.Перед вызовом
PQconnectPollвы должны перевести сокет в соответствующее состояние, как описано ниже.
Чтобы начать неблокирующий запрос на подключение, вызовите
PQconnectStartилиPQconnectStartParams. Если результатом будет null, значит libpq не смогла выделить память для новой структурыPGconn. В противном случае возвращается действительный указательPGconn(хотя он ещё не представляет установленное подключение к базе данных). Затем вызовитеPQstatus(conn). Если результатом будетCONNECTION_BAD, значит попытка подключения уже не будет успешной, возможно, из-за неверных параметров.Если вызов
PQconnectStartилиPQconnectStartParamsоказался успешным, теперь нужно опросить libpq для продолжения процедуры подключения. ВызовитеPQsocket(conn)для получения дескриптора нижележащего сокета, через который устанавливается соединение. (Внимание: этот сокет может меняться от вызова к вызовуPQconnectPoll.) Организуйте цикл таким образом: еслиPQconnectPoll(conn)при последнем вызове возвращаетPGRES_POLLING_READING, ожидайте, пока сокет не окажется готовым для чтения (это покажет функцияPQselect()). Затем снова вызовитеPQconnectPoll(conn). Если жеPQconnectPoll(conn)при последнем вызове возвратилаPGRES_POLLING_WRITING, дождитесь готовности сокета к записи, а затем снова вызовитеPQconnectPoll(conn). На первой итерации, то есть когда вы ещё не вызывалиPQconnectPoll, реализуйте то же поведение, что и после полученияPGRES_POLLING_WRITING. Продолжайте этот цикл, покаPQconnectPoll(conn)не выдаст значениеPGRES_POLLING_FAILED, сигнализирующее об ошибке при установлении соединения, илиPGRES_POLLING_OK, показывающее, что соединение установлено успешно.В любое время в процессе подключения его состояние можно проверить, вызвав
PQstatus. Если этот вызов возвратитCONNECTION_BAD, значит, процедура подключения завершилась сбоем; если вызов возвратитCONNECTION_OK, значит, соединение готово. Оба эти состояния можно определить на основе возвращаемого значения функцииPQconnectPoll, описанной выше. Другие состояния могут также иметь место в течение (и только в течение) асинхронной процедуры подключения. Они показывают текущую стадию процедуры подключения и могут быть полезны, например, для предоставления обратной связи пользователю. Вот эти состояния:CONNECTION_STARTEDОжидание, пока соединение будет установлено.
CONNECTION_MADEСоединение установлено; ожидание отправки.
CONNECTION_AWAITING_RESPONSEОжидание ответа от сервера.
CONNECTION_AUTH_OKАутентификация получена; ожидание завершения запуска серверной части.
CONNECTION_SSL_STARTUPСогласование SSL-шифрования.
CONNECTION_SETENVСогласование значений параметров, зависящих от программной среды.
CONNECTION_CHECK_WRITABLEПроверка, можно ли через подключение выполнять пишущие транзакции.
CONNECTION_CONSUMEПрочтение всех оставшихся ответных сообщений через подключение.
Заметьте, что, хотя эти константы и сохранятся (для поддержания совместимости), приложение никогда не должно полагаться на то, что они появятся в каком-то конкретном порядке или вообще появятся, а также на то, что состояние всегда примет одно из этих документированных значений. Приложение может сделать что-то наподобие:
switch(PQstatus(conn)) { case CONNECTION_STARTED: feedback = "Подключение..."; break; case CONNECTION_MADE: feedback = "Подключён к серверу..."; break; . . . default: feedback = "Подключение..."; }Параметр подключения
connect_timeoutигнорируется, когда используетсяPQconnectPoll; именно приложение отвечает за принятие решения о том, является ли истекшее время чрезмерным. В противном случае вызовPQconnectStartс последующим вызовомPQconnectPoll в циклебудут эквивалентны вызовуPQconnectdb.Заметьте, что если функция
PQconnectStartилиPQconnectStartParamsвозвращает ненулевой указатель, вы должны вызватьPQfinish, закончив его использование, чтобы освободить полученную структуру и все связанные с ней блоки памяти. Это нужно сделать, даже если попытка подключения не последует или окажется неуспешной.PQconndefaultsВозвращает значения по умолчанию для параметров подключения.
PQconninfoOption *PQconndefaults(void); typedef struct { char *keyword; /* Ключевое слово для данного параметра */ char *envvar; /* Имя альтернативной переменной окружения */ char *compiled; /* Альтернативное значение по умолчанию, назначенное при компиляции */ char *val; /* Текущее значение параметра или NULL */ char *label; /* Обозначение этого поля в диалоге подключения */ char *dispchar; /* Показывает, как отображать это поле в диалоге подключения. Значения следующие: "" Отображать введённое значение "как есть" "*" Поле пароля — скрывать значение "D" Параметр отладки — не показывать по умолчанию */ int dispsize; /* Размер поля в символах для диалога */ } PQconninfoOption;Возвращает массив параметров подключения. Он может использоваться для определения всех возможных параметров
PQconnectdbи их текущих значений по умолчанию. Возвращаемое значение указывает на массив структурPQconninfoOption, который завершается элементом, имеющим нулевой указательkeyword. Если выделить память не удалось, то возвращается нулевой указатель. Обратите внимание, что текущие значения по умолчанию (поляval) будут зависеть от переменных среды и другого контекста. Отсутствующий или неверный сервисный файл будет молча проигнорирован. Вызывающие функции должны рассматривать данные параметров по умолчанию как «только для чтения».После обработки массива параметров освободите память, передав его функции
PQconninfoFree. Если этого не делать, то при каждом вызове функцииPQconndefaultsбудет происходить небольшая утечка памяти.PQconninfoВозвращает параметры подключения, используемые действующим соединением.
PQconninfoOption *PQconninfo(PGconn *conn);
Возвращает массив параметров подключения. Он может использоваться для определения всех возможных параметров
PQconnectdbи значений, которые были использованы для подключения к серверу. Возвращаемое значение указывает на массив структурPQconninfoOption, который завершается элементом, имеющим нулевой указательkeyword. Все замечания, приведённые выше дляPQconndefaults, также справедливы и для результатаPQconninfo.PQconninfoParseВозвращает разобранные параметры подключения, переданные в строке подключения.
PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
Разбирает строку подключения и возвращает результирующие параметры в виде массива; возвращает
NULL, если возникают проблемы при разборе строки подключения. Эту функцию можно использовать для извлечения параметров функцииPQconnectdbиз предоставленной строки подключения. Возвращаемое значение указывает на массив структурPQconninfoOption, который завершается элементом, имеющим нулевой указательkeyword.Все разрешённые параметры будут присутствовать в результирующем массиве, но
PQconninfoOptionдля любого параметра, не присутствующего в строке подключения, будет иметь значениеNULLв полеval; значения по умолчанию не подставляются.Если
errmsgне равноNULL, тогда в случае успеха*errmsgприсваиваетсяNULL, а в противном случае -- адрес строки сообщения об ошибке, объясняющего проблему. Память для этой строки выделяет функцияmalloc. (Также возможна ситуация, когда*errmsgбудет установлено вNULL, и при этом функция возвращаетNULL. Это указывает на нехватку памяти.)После обработки массива параметров освободите память, передав его функции
PQconninfoFree. Если этого не делать, тогда некоторое количество памяти будет утекать при каждом вызовеPQconninfoParse. И наоборот, если произошла ошибка иerrmsgне равноNULL, обязательно освободите память, занимаемую строкой сообщения об ошибке, используяPQfreemem.PQfinishЗакрывает соединение с сервером. Также освобождает память, используемую объектом
PGconn.void PQfinish(PGconn *conn);
Обратите внимание, что даже если попытка подключения к серверу потерпела неудачу (как показывает
PQstatus), приложение все равно должно вызватьPQfinish, чтобы освободить память, используемую объектомPGconn. УказательPGconnне должен использоваться повторно после того, как была вызвана функцияPQfinish.PQresetПереустанавливает канал связи с сервером.
void PQreset(PGconn *conn);
Эта функция закроет подключение к серверу, а потом попытается установить новое подключение, используя все те же параметры, которые использовались прежде. Это может быть полезным для восстановления после ошибки, если работающее соединение было разорвано.
PQresetStartPQresetPollПереустанавливает канал связи с сервером неблокирующим способом.
int PQresetStart(PGconn *conn); PostgresPollingStatusType PQresetPoll(PGconn *conn);
Эти функции закроют подключение к серверу, а потом попытаются установить новое подключение, используя все те же параметры, которые использовались прежде. Это может быть полезным для восстановления после ошибки, если работающее соединение оказалось потерянным. Они отличаются от
PQreset(см. выше) тем, что действуют неблокирующим способом. На эти функции налагаются те же ограничения, что и наPQconnectStartParams,PQconnectStartиPQconnectPoll.Чтобы приступить к переустановке подключения, вызовите
PQresetStart. Если она возвратит 0, переустановка завершилась неудачно. Если она возвратит 1, опросите результат переустановки, используяPQresetPoll, точно таким же образом, как если бы вы создавали подключение, используяPQconnectPoll.PQpingParamsPQpingParamsсообщает состояние сервера. Она принимает параметры подключения, идентичные тем, что получает функцияPQconnectdbParams, описанная выше. Нет необходимости предоставлять корректные имя пользователя, пароль или имя базы данных, чтобы получить состояние сервера. Однако если предоставлены некорректные значения, сервер занесёт в журнал неудачную попытку подключения.PGPing PQpingParams(const char * const *keywords, const char * const *values, int expand_dbname);Функция возвращает одно из следующих значений:
PQPING_OKСервер работает и, по-видимому, принимает подключения.
PQPING_REJECTСервер работает, но находится в состоянии, которое запрещает подключения (запуск, завершение работы или восстановление после аварийного отказа).
PQPING_NO_RESPONSEКонтакт с сервером не удался. Это может указывать на то, что сервер не запущен или что-то не в порядке с параметрами данного подключения (например, неверный номер порта), или имеет место проблема с возможностью соединения по сети (например, брандмауэр блокирует запрос на подключение).
PQPING_NO_ATTEMPTНикакой попытки установить контакт с сервером сделано не было, поскольку предоставленные параметры были явно некорректными, или имела место какая-то проблема на стороне клиента (например, нехватка памяти).
PQpingPQpingсообщает состояние сервера. Она принимает параметры подключения, идентичные тем, что получает функцияPQconnectdb, описанная выше. Нет необходимости предоставлять корректные имя пользователя, пароль или имя базы данных, чтобы получить состояние сервера. Однако если предоставлены некорректные значения, сервер занесёт в журнал неудачную попытку подключения.PGPing PQping(const char *conninfo);
Возвращаемые значения такие же, как и для
PQpingParams.
35.1.1. Строки параметров подключения
Ряд функций libpq разбирают заданную пользователем строку для извлечения параметров подключения. Есть два принятых формата этих строк: простая строка ключ/значение и URI. Строки URI в основном соответствуют RFC 3986, но могут содержать также строки подключения с несколькими узлами, как описано ниже.
35.1.1.1. Строки параметров подключения вида «ключ/значение»
Согласно формату ключ/значение, установка каждого параметра выполняется в форме ключ = значение, с пробелами между параметрами. Пробелы вокруг знака равенства не являются обязательными. Для записи пустого значения или значения, содержащего пробелы, заключите его в одинарные кавычки, например, keyword = 'a value'. Одинарные кавычки и символы обратной косой черты внутри значения нужно обязательно экранировать с помощью символа обратной косой черты, т. е., \' и \\.
Пример:
host=localhost port=5432 dbname=mydb connect_timeout=10
Ключевые слова-параметры, распознаваемые в настоящее время, приведены в Подразделе 35.1.2.
35.1.1.2. URI для подключения
Основная форма URI подключения:
postgresql://[пользователь@][сервер][/база_данных][?указание_параметра] гдепользователь:имя_пользователя[:пароль] исервер: [узел][:порт][,...] иуказание_параметра:имя=значение[&...]
В качестве обозначения схемы URI может использоваться postgresql:// или postgres://. Остальные части URI являются необязательными. В следующих примерах показан допустимый синтаксис URI:
postgresql:// postgresql://localhost postgresql://localhost:5433 postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp postgresql://host1:123,host2:456/somedb?hostorder=random&target_session_attrs=any&application_name=myapp
Значения, которые обычно задаются в иерархической части URI, также можно задать в именованных параметрах. Например:
postgresql:///mydb?host=localhost&port=5433
Все именованные параметры должны соответствовать ключевым словам, перечисленным в Подраздел 35.1.2, за исключением того, что вхождения ssl=true заменяются на sslmode=require для совместимости с URI-строками JDBC.
Для включения символов, имеющих специальное значение, в любой части URI можно применять URL-кодирование (с использованием %), например заменить = на %3D.
Сервер можно представить либо сетевым именем, либо IP-адресом. При использовании протокола IPv6 нужно заключить адрес в квадратные скобки:
postgresql://[2001:db8::1234]/database
Часть host интерпретируется в соответствии с описанием параметра host. Так, если эта часть строки пуста или выглядит как абсолютный путь, выбирается соединение через Unix-сокеты, в противном случае инициируется соединение по TCP/IP. Учтите однако, что символ косой черты в иерархической части URI является зарезервированным. Поэтому, чтобы указать нестандартный каталог Unix-сокета, нужно поступить одним из двух способов: не задавать эту часть в URI и указать сервер в именованном параметре либо закодировать путь в части host с процентами:
postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
В одном URI можно задать несколько компонентов узлов, каждый с необязательным указанием порта. URI вида postgresql://host1:port1,host2:port2,host3:port3/ равнозначно строке подключения вида host=host1,host2,host3 port=port1,port2,port3. Все узлы из этого списка будут перебираться в порядке, заданном параметром hostorder, пока подключение не будет установлено успешно или не будет превышено время ожидания (failover_timeout). За подробностями обратитесь к Подразделу 35.1.1.3.
35.1.1.3. Указание нескольких узлов
В строке подключения можно задать несколько узлов, к которым клиент будет пытаться подключиться в заданном порядке. Параметры host, hostaddr и port в формате ключ/значение принимают списки значений, разделённых запятыми. В каждом определяемом параметре должно содержаться одинаковое число элементов, чтобы, например, первый элемент hostaddr соответствовал первому элементу host, второй — второму host и так далее. Исключение составляет port — если этот параметр содержит только один элемент, он применяется ко всем узлам.
В формате URI внутри компонента host можно указать несколько пар host:port, разделённых запятыми.
В любом формате одно имя узла может переводиться в несколько сетевых адресов. Например, часто бывает, что один узел имеет и адрес IPv4, и адрес IPv6.
Когда задаются несколько узлов или когда одно имя узла переводится в несколько адресов, все узлы и адреса перебираются в порядке, заданном параметром hostorder, пока подключение не будет установлено. По умолчанию для каждого узла выполняется только одна попытка подключения. Вы можете разрешить несколько попыток для каждого узла, воспользовавшись параметром failover_timeout, задающим максимальное время для установления соединения. Если ни один из узлов не будет доступен, произойдёт сбой подключения. Если подключение устанавливается успешно, но происходит ошибка аутентификации, остальные узлы в списке не перебираются.
Если используется файл паролей, в нём можно задать разные пароли для разных узлов. Все остальные параметры подключения будут одинаковыми для всех узлов; например, нельзя задать для разных узлов различные имена пользователей.
35.1.2. Ключевые слова-параметры
Ключевые слова-параметры, распознаваемые в настоящее время, следующие:
hostИмя узла для подключения. Если это имя начинается с косой черты, оно выбирает подключение через Unix-сокет, а не через TCP/IP, и задаёт имя каталога, содержащего файл сокета. По умолчанию, если параметр
hostотсутствует или пуст, выполняется подключение к Unix-сокету в/tmp(или в том каталоге сокетов, который был задан при сборке Postgres Pro). В системах, где Unix-сокеты не поддерживаются, по умолчанию выполняется подключение кlocalhost.Также принимается разделённый запятыми список имён узлов; при этом данные имена будут перебираться по порядку, который определён параметром hostorder. Для пустых элементов списка применяется поведение по умолчанию, описанное выше. За подробностями обратитесь к Подразделу 35.1.1.3.
hostaddrЧисловой IP-адрес узла для подключения. Он должен быть представлен в стандартном формате адресов IPv4, например,
172.28.40.9. Если ваша машина поддерживает IPv6, вы можете использовать и эти адреса. Связь по протоколу TCP/IP используется всегда, когда в качестве этого параметра передана непустая строка.Использование
hostaddrвместоhostпозволяет приложению избежать поиска на сервере имён, что может быть важно для приложений, имеющих ограничения по времени. Однако имя узла требуется для методов аутентификации GSSAPI или SSPI, а также для проверки полномочий на основе SSL-сертификатов в режимеverify-full. Применяются следующие правила:Если адрес
hostзадаётся безhostaddr, осуществляется разрешение имени. (При использованииPQconnectPollразрешение производится, когдаPQconnectPollрассматривает это имя в первый раз, и может заблокироватьPQconnectPollна неопределённое время.)Если указан
hostaddr, аhostне указан, тогда значениеhostaddrдаёт сетевой адрес сервера. Попытка подключения завершится неудачей, если метод аутентификации требует наличия имени узла.Если указаны как
host, так иhostaddr, тогда значениеhostaddrдаёт сетевой адрес сервера, а значениеhostигнорируется, если только метод аутентификации его не потребует. В таком случае оно будет использоваться в качестве имени узла.
Заметьте, что аутентификация может завершится неудачей, если
hostне является именем сервера с сетевым адресомhostaddr. Также заметьте, что когда указывается иhost, иhostaddr, соединение в файле паролей идентифицируется по значениюhost(см. Раздел 35.15).Также принимается разделённый запятыми список значений
hostaddr; при этом данные узлы будут перебираться по порядку, который определён параметром hostorder. Вместо пустого элемента в этом списке будет подставлено имя соответствующего узла или, если и оно не определено, имя узла по умолчанию. За подробностями обратитесь к Подразделу 35.1.1.3.Если не указаны ни имя узла, ни его адрес, libpq будет производить подключение, используя локальный Unix-сокет; в системах, не поддерживающих Unix-сокеты, она будет пытаться подключиться к
localhost.hostorderОпределяет порядок подключения к серверам, указанным в параметре host или hostaddr.
Если значение этого параметра —
sequential(по умолчанию), подключение к серверам будет устанавливаться в том порядке, в котором они указаны.Со значением
randomсервер для подключения выбирается из списка случайным образом. Этот вариант позволяет организовать балансировку нагрузки между несколькими узлами кластера, а не подключаться всегда к первому доступному узлу в списке. Вы также можете воспользоваться параметром target_session_attrs для отказа от подключений только для чтения.portНомер порта, к которому нужно подключаться на сервере, либо расширение имени файла сокета для соединений через Unix-сокеты. Если в параметрах
hostилиhostaddrзадано несколько серверов, в данном параметре может задаваться через запятую список портов такой же длины, либо может указываться один номер порта для всех узлов. Пустая строка или пустой элемент в списке через запятую воспринимается как номер порта по умолчанию, установленный при сборке Postgres Pro.dbnameИмя базы данных. По умолчанию оно совпадает с именем пользователя. В определённых контекстах это значение проверяется на соответствие расширенным форматам; см. Подраздел 35.1.1 для получения подробной информации.
userИмя пользователя Postgres Pro, используемое для подключения. По умолчанию используется то же имя, которое имеет в операционной системе пользователь, от лица которого выполняется приложение.
passwordПароль, используемый в случае, когда сервер требует аутентификации по паролю.
passfileЗадаёт имя файла, в котором будут храниться пароли (см. Раздел 35.15). По умолчанию это
~/.pgpassили%APPDATA%\postgresql\pgpass.confв Microsoft Windows. (Отсутствие этого файла не считается ошибкой.)reusepassОпределяет, разрешается ли использовать запрошенный пароль при повторном установлении подключения. Чтобы запретить многократное использование пароля, задайте для параметра
reusepassзначениеno. Этот параметр, в сочетании с idle_session_timeout, позволяет определить поведение при переподключении для сеансов, прерываемых по тайм-ауту.По умолчанию:
yesconnect_timeoutМаксимальное время ожидания подключения (задаётся десятичным целым числом, например:
10). При нуле, отрицательном или неопределённом значении ожидание будет бесконечным. Минимальный допустимый тайм-аут равен 2 секундам; таким образом, значение1воспринимается как2. Этот тайм-аут применяется для каждого отдельного IP-адреса или имени сервера. Например, если вы зададите адреса двух серверов и значениеconnect_timeoutбудет равно 5, тайм-аут при неудачной попытке подключения к каждому серверу произойдёт через 5 секунд, а общее время ожидания подключения может достигать 10 секунд.failover_timeoutМаксимальное время, в секундах, для циклического переподключения к узлам, указанным в строке соединения. Если этот параметр не задан (по умолчанию), выполняется только одна попытка подключения к каждому узлу. Заданное значение должно быть десятичным целым числом.
Используя этот параметр в кластерах с репликацией ведущий-ведомый, убедитесь, что его значение достаточно велико для того, чтобы ведомый сервер успел стать ведущим в случае отказа текущего ведущего. В этом случае клиенты смогут переподключиться к новому ведущему по завершении смены его роли.
client_encodingЭтим устанавливается конфигурационный параметр
client_encodingдля данного подключения. В дополнение к значениям, которые принимает соответствующий параметр сервера, вы можете использовать значениеauto. В этом случае правильная кодировка определяется на основе текущей локали на стороне клиента (в системах Unix это переменная системного окруженияLC_CTYPE).optionsЗадаёт параметры командной строки, которые будут отправлены серверу при установлении соединения. Например, значение
-c geqo=offустановит для параметра сеансаgeqoзначениеoff. Пробелы в этой строке считаются разделяющими аргументы командной строки, если только перед ними не стоит обратная косая черта (\); чтобы записать собственно обратную косую черту, её нужно продублировать (\\). Подробное описание возможных параметров можно найти в Главе 19.with_rsocketВыбирает для подключения к серверу API
rsocket. Вы также должны установить переменную listen_rdma_addresses на вашем сервере, чтобы он принимал подключения RDMA черезrsocket.application_nameУстанавливает значение для конфигурационного параметра application_name.
fallback_application_nameУстанавливает альтернативное значение для конфигурационного параметра application_name. Это значение будет использоваться, если для параметра
application_nameне было передано никакого значения с помощью параметров подключения или переменной системного окруженияPGAPPNAME. Задание альтернативного имени полезно для универсальных программ-утилит, которые желают установить имя приложения по умолчанию, но позволяют пользователю изменить его.keepalivesУправляет использованием сообщений keepalive протокола TCP на стороне клиента. Значение по умолчанию равно 1, что означает использование сообщений. Вы можете изменить его на 0, если эти сообщения не нужны. Для соединений, установленных через Unix-сокеты, этот параметр игнорируется.
keepalives_idleУправляет длительностью периода отсутствия активности, выраженного числом секунд, по истечении которого TCP должен отправить сообщение keepalive серверу. При значении 0 действует системная величина. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPIDLEили равнозначный, и в Windows; в других системах он не оказывает влияния.keepalives_intervalЗадаёт количество секунд, по прошествии которых сообщение keepalive протокола TCP, получение которого не подтверждено сервером, должно быть отправлено повторно. При значении 0 действует системная величина. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPINTVLили равнозначный, и в Windows; в других системах он не оказывает влияния.keepalives_countЗадаёт количество сообщений keepalive протокола TCP, которые могут быть потеряны, прежде чем соединение клиента с сервером будет признано неработающим. Нулевое значение этого параметра указывает, что будет использоваться системное значение по умолчанию. Этот параметр игнорируется для соединений, установленных через Unix-сокеты, или если сообщения keepalive отключены. Он поддерживается только в системах, воспринимающих параметр сокета
TCP_KEEPCNTили равнозначный; в других системах он не оказывает влияния.ttyИгнорируется (прежде он указывал, куда направить вывод отладочных сообщений сервера).
replicationЭтот параметр определяет, должно ли подключение использовать протокол репликации вместо обычного протокола. Этот вариант используют внутри механизмы репликации Postgres Pro и такие средства, как pg_basebackup, но он может также применяться и сторонними приложениями. За подробным описанием протокола репликации обратитесь к Разделу 54.4.
Поддерживаются следующие значения этого параметра, без учёта регистра:
true,on,yes,1Подключение осуществляется в режиме физической репликации.
databaseПодключение осуществляется в режиме логической репликации, целевая база данных задаётся параметром
dbname.false,off,no,0Подключение выполняется в обычном режиме; это поведение по умолчанию.
В режиме физической или логической репликации может использоваться только простой протокол запросов.
sslmodeЭтот параметр определяет, будет ли согласовываться с сервером защищённое SSL-соединение по протоколу TCP/IP, и если да, то в какой очередности. Всего предусмотрено шесть режимов:
disableследует пытаться установить только соединение без использования SSL
allowсначала следует попытаться установить соединение без использования SSL; если попытка будет неудачной, нужно попытаться установить SSL-соединение
prefer(по умолчанию)сначала следует попытаться установить SSL-соединение; если попытка будет неудачной, нужно попытаться установить соединение без использования SSL
requireследует попытаться установить только SSL-соединение. Если присутствует файл корневого центра сертификации, то нужно верифицировать сертификат таким же способом, как будто был указан параметр
verify-caverify-caследует попытаться установить только SSL-соединение, при этом проконтролировать, чтобы сертификат сервера был выпущен доверенным центром сертификации (CA)
verify-fullследует попытаться установить только SSL-соединение, при этом проконтролировать, чтобы сертификат сервера был выпущен доверенным центром сертификации (CA) и чтобы имя запрошенного сервера соответствовало имени в сертификате
В Разделе 35.18 приведено подробное описание работы этих режимов.
sslmodeигнорируется при использовании Unix-сокетов. Если Postgres Pro скомпилирован без поддержки SSL, использование параметровrequire,verify-caилиverify-fullприведёт к ошибке, в то время как параметрыallowиpreferбудут приняты, но libpq в действительности не будет пытаться установить SSL-соединение.requiresslИспользовать этот параметр не рекомендуется, в качестве замены предлагается установить
sslmode.Если установлено значение 1, то требуется SSL-соединение с сервером (это эквивалентно
sslmoderequire). libpq в таком случае откажется подключаться, если сервер не принимает SSL-соединений. Если установлено значение 0 (по умолчанию), тогда libpq будет согласовывать тип подключения с сервером (эквивалентноsslmodeprefer). Этот параметр доступен, если только Postgres Pro скомпилирован с поддержкой SSL.sslcompressionЕсли установлено значение 1, данные, передаваемые через SSL-соединения, будут сжиматься. Если установлено значение 0 (по умолчанию), сжатие будет отключено. Этот параметр игнорируется, если установлено подключение без SSL.
Сжатие SSL в настоящее время считается небезопасным, и использовать его уже не рекомендуется. В OpenSSL 1.1.0 сжатие отключено по умолчанию, к тому же во многих дистрибутивах оно отключается и с более ранними версиями. А если сервер не поддерживает сжатие, включение этого параметра не окажет никакого влияния. С другой стороны, OpenSSL до версии 1.0.0 не поддерживал отключение сжатия, так что с такими версиями этот параметр игнорируется, и использование сжатия зависит от сервера.
Если вопросы безопасности не стоят на первом месте, сжатие может ускорить передачу данных, когда узким местом является сеть. Отключение сжатия может улучшить время отклика и пропускную способность, если ограничивающим фактором является производительность CPU.
sslcertЭтот параметр предписывает имя файла для SSL-сертификата клиента, заменяющего файл по умолчанию
~/.postgresql/postgresql.crt. Этот параметр игнорируется, если SSL-подключение не выполнено.sslkeyЭтот параметр предписывает местоположение секретного ключа, используемого для сертификата клиента. Он может либо указывать имя файла, которое будет использоваться вместо имени по умолчанию
~/.postgresql/postgresql.key, либо он может указывать ключ, полученный от внешнего «криптомодуля» (криптомодули — это загружаемые модули OpenSSL). Спецификация внешнего криптомодуля должна состоять из имени модуля и ключевого идентификатора, зависящего от конкретного модуля, разделённых двоеточием. Этот параметр игнорируется, если SSL-подключение не выполнено.sslrootcertЭтот параметр указывает имя файла, содержащего SSL-сертификаты, выданные Центром сертификации (CA). Если файл существует, сертификат сервера будет проверен на предмет его подписания одним из этих центров. Имя по умолчанию —
~/.postgresql/root.crt.sslcrlЭтот параметр указывает имя файла, содержащего список отозванных серверных сертификатов (CRL) для SSL. Сертификаты, перечисленные в этом файле, если он существует, будут отвергаться при попытке установить подлинность сертификата сервера. Имя по умолчанию такое
~/.postgresql/root.crl.requirepeerЭтот параметр указывает имя пользователя операционной системы, предназначенное для сервера, например,
requirepeer=postgres. При создании подключения через Unix-сокет, если этот параметр установлен, клиент проверяет в самом начале процедуры подключения, что серверный процесс запущен от имени указанного пользователя; если это не так, соединение аварийно прерывается с ошибкой. Этот параметр можно использовать, чтобы обеспечить аутентификацию сервера, подобную той, которая доступна с помощью SSL-сертификатов при соединениях по протоколу TCP/IP. (Заметьте, что если Unix-сокет находится в каталоге/tmpили в другом каталоге, запись в который разрешена всем пользователям, тогда любой пользователь сможет запустить сервер, прослушивающий сокет в том каталоге. Используйте этот параметр, чтобы гарантировать, что вы подключены к серверу, запущенному доверенным пользователем.) Он поддерживается только на платформах, для которых реализован метод аутентификацииpeer; см. Раздел 20.9.krbsrvnameИмя сервиса Kerberos, предназначенное для использования при аутентификации на основе GSSAPI. Оно должно соответствовать имени сервиса, указанному в конфигурации сервера, чтобы аутентификация на основе Kerberos прошла успешно. (См. также Раздел 20.6.)
gsslibБиблиотека GSS, предназначенная для использования при аутентификации на основе GSSAPI. В настоящее время это действует только в сборках для Windows, поддерживающих одновременно и GSSAPI, и SSPI. Значение
gssapiв таких сборках позволяет указать, что libpq должна использовать для аутентификации библиотеку GSSAPI, а не подразумеваемую по умолчанию SSPI.serviceИмя сервиса, используемое для задания дополнительных параметров. Оно указывает имя сервиса в файле
pg_service.conf, который содержит дополнительные параметры подключения. Это позволяет приложениям указывать только имя сервиса, поскольку параметры подключения могут поддерживаться централизованно. См. Раздел 35.16.target_session_attrsЕсли этот параметр равен
read-writeилиmaster, по умолчанию будут приемлемы только подключения, допускающие транзакции на чтение/запись. При успешном подключении будет отправлен запросSHOW transaction_read_only; если он вернётon, соединение будет закрыто. Если в строке подключения указано несколько серверов, будут перебираться остальные серверы, как и при неудачной попытке подключения. Со значением по умолчанию (any) приемлемыми будут все подключения.target_server_typeРавнозначен target_session_attrs. Этот параметр поддерживается для обратной совместимости с Postgres Pro Enterprise 9.6.
35.1. Database Connection Control Functions
The following functions deal with making a connection to a Postgres Pro backend server. An application program can have several backend connections open at one time. (One reason to do that is to access more than one database.) Each connection is represented by a PGconn object, which is obtained from the function PQconnectdb, PQconnectdbParams, or PQsetdbLogin. Note that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate the PGconn object. The PQstatus function should be called to check the return value for a successful connection before queries are sent via the connection object.
Warning
If untrusted users have access to a database that has not adopted a secure schema usage pattern, begin each session by removing publicly-writable schemas from search_path. One can set parameter key word options to value -csearch_path=. Alternately, one can issue PQexec( after connecting. This consideration is not specific to libpq; it applies to every interface for executing arbitrary SQL commands. conn, "SELECT pg_catalog.set_config('search_path', '', false)")
Warning
On Unix, forking a process with open libpq connections can lead to unpredictable results because the parent and child processes share the same sockets and operating system resources. For this reason, such usage is not recommended, though doing an exec from the child process to load a new executable is safe.
PQconnectdbParamsMakes a new connection to the database server.
PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname);This function opens a new database connection using the parameters taken from two
NULL-terminated arrays. The first,keywords, is defined as an array of strings, each one being a key word. The second,values, gives the value for each key word. UnlikePQsetdbLoginbelow, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analogsPQconnectStartParamsandPQconnectPoll) is preferred for new application programming.The currently recognized parameter key words are listed in Section 35.1.2.
The passed arrays can be empty to use all default parameters, or can contain one or more parameter settings. They must be matched in length. Processing will stop at the first
NULLentry in thekeywordsarray. Also, if thevaluesentry associated with a non-NULLkeywordsentry isNULLor an empty string, that entry is ignored and processing continues with the next pair of array entries.When
expand_dbnameis non-zero, the value for the firstdbnamekey word is checked to see if it is a connection string. If so, it is “expanded” into the individual connection parameters extracted from the string. The value is considered to be a connection string, rather than just a database name, if it contains an equal sign (=) or it begins with a URI scheme designator. (More details on connection string formats appear in Section 35.1.1.) Only the first occurrence ofdbnameis treated in this way; any subsequentdbnameparameter is processed as a plain database name.In general the parameter arrays are processed from start to end. If any key word is repeated, the last value (that is not
NULLor empty) is used. This rule applies in particular when a key word found in a connection string conflicts with one appearing in thekeywordsarray. Thus, the programmer may determine whether array entries can override or be overridden by values taken from a connection string. Array entries appearing before an expandeddbnameentry can be overridden by fields of the connection string, and in turn those fields are overridden by array entries appearing afterdbname(but, again, only if those entries supply non-empty values).After processing all the array entries and any expanded connection string, any connection parameters that remain unset are filled with default values. If an unset parameter's corresponding environment variable (see Section 35.14) is set, its value is used. If the environment variable is not set either, then the parameter's built-in default value is used.
PQconnectdbMakes a new connection to the database server.
PGconn *PQconnectdb(const char *conninfo);
This function opens a new database connection using the parameters taken from the string
conninfo.The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace, or it can contain a URI. See Section 35.1.1 for details.
PQsetdbLoginMakes a new connection to the database server.
PGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd);This is the predecessor of
PQconnectdbwith a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. WriteNULLor an empty string for any one of the fixed parameters that is to be defaulted.If the
dbNamecontains an=sign or has a valid connection URI prefix, it is taken as aconninfostring in exactly the same way as if it had been passed toPQconnectdb, and the remaining parameters are then applied as specified forPQconnectdbParams.PQsetdbMakes a new connection to the database server.
PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);This is a macro that calls
PQsetdbLoginwith null pointers for theloginandpwdparameters. It is provided for backward compatibility with very old programs.PQconnectStartParamsPQconnectStartPQconnectPollMake a connection to the database server in a nonblocking manner.
PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname); PGconn *PQconnectStart(const char *conninfo); PostgresPollingStatusType PQconnectPoll(PGconn *conn);These three functions are used to open a connection to a database server such that your application's thread of execution is not blocked on remote I/O whilst doing so. The point of this approach is that the waits for I/O to complete can occur in the application's main loop, rather than down inside
PQconnectdbParamsorPQconnectdb, and so the application can manage this operation in parallel with other activities.With
PQconnectStartParams, the database connection is made using the parameters taken from thekeywordsandvaluesarrays, and controlled byexpand_dbname, as described above forPQconnectdbParams.With
PQconnectStart, the database connection is made using the parameters taken from the stringconninfoas described above forPQconnectdb.Neither
PQconnectStartParamsnorPQconnectStartnorPQconnectPollwill block, so long as a number of restrictions are met:The
hostaddrparameter must be used appropriately to prevent DNS queries from being made. See the documentation of this parameter in Section 35.1.2 for details.If you call
PQtrace, ensure that the stream object into which you trace will not block.You must ensure that the socket is in the appropriate state before calling
PQconnectPoll, as described below.
To begin a nonblocking connection request, call
PQconnectStartorPQconnectStartParams. If the result is null, then libpq has been unable to allocate a newPGconnstructure. Otherwise, a validPGconnpointer is returned (though not yet representing a valid connection to the database). Next callPQstatus(conn). If the result isCONNECTION_BAD, the connection attempt has already failed, typically because of invalid connection parameters.If
PQconnectStartorPQconnectStartParamssucceeds, the next stage is to poll libpq so that it can proceed with the connection sequence. UsePQsocket(conn)to obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same acrossPQconnectPollcalls.) Loop thus: IfPQconnectPoll(conn)last returnedPGRES_POLLING_READING, wait until the socket is ready to read (as indicated byPQselect()). Then callPQconnectPoll(conn)again. Conversely, ifPQconnectPoll(conn)last returnedPGRES_POLLING_WRITING, wait until the socket is ready to write, then callPQconnectPoll(conn)again. On the first iteration, i.e., if you have yet to callPQconnectPoll, behave as if it last returnedPGRES_POLLING_WRITING. Continue this loop untilPQconnectPoll(conn)returnsPGRES_POLLING_FAILED, indicating the connection procedure has failed, orPGRES_POLLING_OK, indicating the connection has been successfully made.At any time during connection, the status of the connection can be checked by calling
PQstatus. If this call returnsCONNECTION_BAD, then the connection procedure has failed; if the call returnsCONNECTION_OK, then the connection is ready. Both of these states are equally detectable from the return value ofPQconnectPoll, described above. Other states might also occur during (and only during) an asynchronous connection procedure. These indicate the current stage of the connection procedure and might be useful to provide feedback to the user for example. These statuses are:CONNECTION_STARTEDWaiting for connection to be made.
CONNECTION_MADEConnection OK; waiting to send.
CONNECTION_AWAITING_RESPONSEWaiting for a response from the server.
CONNECTION_AUTH_OKReceived authentication; waiting for backend start-up to finish.
CONNECTION_SSL_STARTUPNegotiating SSL encryption.
CONNECTION_SETENVNegotiating environment-driven parameter settings.
CONNECTION_CHECK_WRITABLEChecking if connection is able to handle write transactions.
CONNECTION_CONSUMEConsuming any remaining response messages on connection.
Note that, although these constants will remain (in order to maintain compatibility), an application should never rely upon these occurring in a particular order, or at all, or on the status always being one of these documented values. An application might do something like this:
switch(PQstatus(conn)) { case CONNECTION_STARTED: feedback = "Connecting..."; break; case CONNECTION_MADE: feedback = "Connected to server..."; break; . . . default: feedback = "Connecting..."; }The
connect_timeoutconnection parameter is ignored when usingPQconnectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise,PQconnectStartfollowed by aPQconnectPollloop is equivalent toPQconnectdb.Note that when
PQconnectStartorPQconnectStartParamsreturns a non-null pointer, you must callPQfinishwhen you are finished with it, in order to dispose of the structure and any associated memory blocks. This must be done even if the connection attempt fails or is abandoned.PQconndefaultsReturns the default connection options.
PQconninfoOption *PQconndefaults(void); typedef struct { char *keyword; /* The keyword of the option */ char *envvar; /* Fallback environment variable name */ char *compiled; /* Fallback compiled in default value */ char *val; /* Option's current value, or NULL */ char *label; /* Label for field in connect dialog */ char *dispchar; /* Indicates how to display this field in a connect dialog. Values are: "" Display entered value as is "*" Password field - hide value "D" Debug option - don't show by default */ int dispsize; /* Field size in characters for dialog */ } PQconninfoOption;Returns a connection options array. This can be used to determine all possible
PQconnectdboptions and their current default values. The return value points to an array ofPQconninfoOptionstructures, which ends with an entry having a nullkeywordpointer. The null pointer is returned if memory could not be allocated. Note that the current default values (valfields) will depend on environment variables and other context. A missing or invalid service file will be silently ignored. Callers must treat the connection options data as read-only.After processing the options array, free it by passing it to
PQconninfoFree. If this is not done, a small amount of memory is leaked for each call toPQconndefaults.PQconninfoReturns the connection options used by a live connection.
PQconninfoOption *PQconninfo(PGconn *conn);
Returns a connection options array. This can be used to determine all possible
PQconnectdboptions and the values that were used to connect to the server. The return value points to an array ofPQconninfoOptionstructures, which ends with an entry having a nullkeywordpointer. All notes above forPQconndefaultsalso apply to the result ofPQconninfo.PQconninfoParseReturns parsed connection options from the provided connection string.
PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
Parses a connection string and returns the resulting options as an array; or returns
NULLif there is a problem with the connection string. This function can be used to extract thePQconnectdboptions in the provided connection string. The return value points to an array ofPQconninfoOptionstructures, which ends with an entry having a nullkeywordpointer.All legal options will be present in the result array, but the
PQconninfoOptionfor any option not present in the connection string will havevalset toNULL; default values are not inserted.If
errmsgis notNULL, then*errmsgis set toNULLon success, else to amalloc'd error string explaining the problem. (It is also possible for*errmsgto be set toNULLand the function to returnNULL; this indicates an out-of-memory condition.)After processing the options array, free it by passing it to
PQconninfoFree. If this is not done, some memory is leaked for each call toPQconninfoParse. Conversely, if an error occurs anderrmsgis notNULL, be sure to free the error string usingPQfreemem.PQfinishCloses the connection to the server. Also frees memory used by the
PGconnobject.void PQfinish(PGconn *conn);
Note that even if the server connection attempt fails (as indicated by
PQstatus), the application should callPQfinishto free the memory used by thePGconnobject. ThePGconnpointer must not be used again afterPQfinishhas been called.PQresetResets the communication channel to the server.
void PQreset(PGconn *conn);
This function will close the connection to the server and attempt to establish a new connection, using all the same parameters previously used. This might be useful for error recovery if a working connection is lost.
PQresetStartPQresetPollReset the communication channel to the server, in a nonblocking manner.
int PQresetStart(PGconn *conn); PostgresPollingStatusType PQresetPoll(PGconn *conn);
These functions will close the connection to the server and attempt to establish a new connection, using all the same parameters previously used. This can be useful for error recovery if a working connection is lost. They differ from
PQreset(above) in that they act in a nonblocking manner. These functions suffer from the same restrictions asPQconnectStartParams,PQconnectStartandPQconnectPoll.To initiate a connection reset, call
PQresetStart. If it returns 0, the reset has failed. If it returns 1, poll the reset usingPQresetPollin exactly the same way as you would create the connection usingPQconnectPoll.PQpingParamsPQpingParamsreports the status of the server. It accepts connection parameters identical to those ofPQconnectdbParams, described above. It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.PGPing PQpingParams(const char * const *keywords, const char * const *values, int expand_dbname);The function returns one of the following values:
PQPING_OKThe server is running and appears to be accepting connections.
PQPING_REJECTThe server is running but is in a state that disallows connections (startup, shutdown, or crash recovery).
PQPING_NO_RESPONSEThe server could not be contacted. This might indicate that the server is not running, or that there is something wrong with the given connection parameters (for example, wrong port number), or that there is a network connectivity problem (for example, a firewall blocking the connection request).
PQPING_NO_ATTEMPTNo attempt was made to contact the server, because the supplied parameters were obviously incorrect or there was some client-side problem (for example, out of memory).
PQpingPQpingreports the status of the server. It accepts connection parameters identical to those ofPQconnectdb, described above. It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.PGPing PQping(const char *conninfo);
The return values are the same as for
PQpingParams.
35.1.1. Connection Strings
Several libpq functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain keyword/value strings and URIs. URIs generally follow RFC 3986, except that multi-host connection strings are allowed as further described below.
35.1.1.1. Keyword/Value Connection Strings
In the keyword/value format, each parameter setting is in the form keyword = value, with space(s) between settings. Spaces around a setting's equal sign are optional. To write an empty value, or a value containing spaces, surround it with single quotes, for example keyword = 'a value'. Single quotes and backslashes within a value must be escaped with a backslash, i.e., \' and \\.
Example:
host=localhost port=5432 dbname=mydb connect_timeout=10
The recognized parameter key words are listed in Section 35.1.2.
35.1.1.2. Connection URIs
The general form for a connection URI is:
postgresql://[userspec@][hostspec][/dbname][?paramspec] whereuserspecis:user[:password] andhostspecis: [host][:port][,...] andparamspecis:name=value[&...]
The URI scheme designator can be either postgresql:// or postgres://. Each of the remaining URI parts is optional. The following examples illustrate valid URI syntax:
postgresql:// postgresql://localhost postgresql://localhost:5433 postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp postgresql://host1:123,host2:456/somedb?hostorder=random&target_session_attrs=any&application_name=myapp
Values that would normally appear in the hierarchical part of the URI can alternatively be given as named parameters. For example:
postgresql:///mydb?host=localhost&port=5433
All named parameters must match key words listed in Section 35.1.2, except that for compatibility with JDBC connection URIs, instances of ssl=true are translated into sslmode=require.
Percent-encoding may be used to include symbols with special meaning in any of the URI parts, e.g., replace = with %3D.
The host part may be either a host name or an IP address. To specify an IPv6 address, enclose it in square brackets:
postgresql://[2001:db8::1234]/database
The host part is interpreted as described for the parameter host. In particular, a Unix-domain socket connection is chosen if the host part is either empty or looks like an absolute path name, otherwise a TCP/IP connection is initiated. Note, however, that the slash is a reserved character in the hierarchical part of the URI. So, to specify a non-standard Unix-domain socket directory, either omit the host part of the URI and specify the host as a named parameter, or percent-encode the path in the host part of the URI:
postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
It is possible to specify multiple host components, each with an optional port component, in a single URI. A URI of the form postgresql://host1:port1,host2:port2,host3:port3/ is equivalent to a connection string of the form host=host1,host2,host3 port=port1,port2,port3. Each host will be tried in the order defined by the hostorder parameter until a connection is successfully established, all hosts have been tried, or failover_timeout is reached. For details, see Section 35.1.1.3.
35.1.1.3. Specifying Multiple Hosts
It is possible to specify multiple hosts to connect to, so that they are tried in the given order. In the Keyword/Value format, the host, hostaddr, and port options accept comma-separated lists of values. The same number of elements must be given in each option that is specified, such that e.g., the first hostaddr corresponds to the first host name, the second hostaddr corresponds to the second host name, and so forth. As an exception, if only one port is specified, it applies to all the hosts.
In the connection URI format, you can list multiple host:port pairs separated by commas in the host component of the URI.
In either format, a single host name can translate to multiple network addresses. A common example of this is a host that has both an IPv4 and an IPv6 address.
When multiple hosts are specified, or when a single host name is translated to multiple addresses, all the hosts and addresses will be tried in the order defined by the hostorder parameter until one succeeds. By default, each host is tried only once. You can allow multiple connection attempts to each host using the failover_timeout parameter, which specifies the maximum time for making a connection. If none of the hosts can be reached, the connection fails. If a connection is established successfully, but authentication fails, the remaining hosts in the list are not tried.
If a password file is used, you can have different passwords for different hosts. All the other connection options are the same for every host in the list; it is not possible to e.g., specify different usernames for different hosts.
35.1.2. Parameter Key Words
The currently recognized parameter key words are:
hostName of host to connect to. If a host name begins with a slash, it specifies Unix-domain communication rather than TCP/IP communication; the value is the name of the directory in which the socket file is stored. The default behavior when
hostis not specified, or is empty, is to connect to a Unix-domain socket in/tmp(or whatever socket directory was specified when Postgres Pro was built). On machines without Unix-domain sockets, the default is to connect tolocalhost.A comma-separated list of host names is also accepted, in which case each host name in the list is tried in the order defined by the hostorder parameter; an empty item in the list selects the default behavior as explained above. See Section 35.1.1.3 for details.
hostaddrNumeric IP address of host to connect to. This should be in the standard IPv4 address format, e.g.,
172.28.40.9. If your machine supports IPv6, you can also use those addresses. TCP/IP communication is always used when a nonempty string is specified for this parameter.Using
hostaddrinstead ofhostallows the application to avoid a host name look-up, which might be important in applications with time constraints. However, a host name is required for GSSAPI or SSPI authentication methods, as well as forverify-fullSSL certificate verification. The following rules are used:If
hostis specified withouthostaddr, a host name lookup occurs. (When usingPQconnectPoll, the lookup occurs whenPQconnectPollfirst considers this host name, and it may causePQconnectPollto block for a significant amount of time.)If
hostaddris specified withouthost, the value forhostaddrgives the server network address. The connection attempt will fail if the authentication method requires a host name.If both
hostandhostaddrare specified, the value forhostaddrgives the server network address. The value forhostis ignored unless the authentication method requires it, in which case it will be used as the host name.
Note that authentication is likely to fail if
hostis not the name of the server at network addresshostaddr. Also, when bothhostandhostaddrare specified,hostis used to identify the connection in a password file (see Section 35.15).A comma-separated list of
hostaddrvalues is also accepted, in which case each host in the list is tried in the order defined by the hostorder parameter. An empty item in the list causes the corresponding host name to be used, or the default host name if that is empty as well. See Section 35.1.1.3 for details.Without either a host name or host address, libpq will connect using a local Unix-domain socket; or on machines without Unix-domain sockets, it will attempt to connect to
localhost.hostorderDefines the order of connecting to the hosts specified by the host or hostaddr parameter.
If the value of this parameter is
sequential(the default), connections to the hosts are attempted in the order in which the hosts are listed.If the value is
random, the host to connect to is randomly picked from the list. This setting can help you balance the load between several cluster nodes instead of always connecting to the first available host in the list. You can also use the target_session_attrs parameter to forbid read-only connections.portPort number to connect to at the server host, or socket file name extension for Unix-domain connections. If multiple hosts were given in the
hostorhostaddrparameters, this parameter may specify a comma-separated list of ports of the same length as the host list, or it may specify a single port number to be used for all hosts. An empty string, or an empty item in a comma-separated list, specifies the default port number established when Postgres Pro was built.dbnameThe database name. Defaults to be the same as the user name. In certain contexts, the value is checked for extended formats; see Section 35.1.1 for more details on those.
userPostgres Pro user name to connect as. Defaults to be the same as the operating system name of the user running the application.
passwordPassword to be used if the server demands password authentication.
passfileSpecifies the name of the file used to store passwords (see Section 35.15). Defaults to
~/.pgpass, or%APPDATA%\postgresql\pgpass.confon Microsoft Windows. (No error is reported if this file does not exist.)reusepassSpecifies whether reusing the prompted password is allowed when reestablishing connections. To forbid password reuse, set
reusepasstono. You can use this option together with idle_session_timeout to define the reconnection behavior for sessions terminated by timeout.Default:
yesconnect_timeoutMaximum wait for connection, in seconds (write as a decimal integer, e.g.,
10). Zero, negative, or not specified means wait indefinitely. The minimum allowed timeout is 2 seconds, therefore a value of1is interpreted as2. This timeout applies separately to each host name or IP address. For example, if you specify two hosts andconnect_timeoutis 5, each host will time out if no connection is made within 5 seconds, so the total time spent waiting for a connection might be up to 10 seconds.failover_timeoutMaximum time, in seconds, to cyclically retry to connect to the hosts specified in the connection string. If this parameter is not set (the default), connection to each host is tried only once. The specified value must be a decimal integer number.
When using this parameter in clusters with master-standby replication, make sure that its value provides enough time for a standby node to become the new master if the current master node fails. In this case, clients will be able to reconnect to the new master once failover is complete.
client_encodingThis sets the
client_encodingconfiguration parameter for this connection. In addition to the values accepted by the corresponding server option, you can useautoto determine the right encoding from the current locale in the client (LC_CTYPEenvironment variable on Unix systems).optionsSpecifies command-line options to send to the server at connection start. For example, setting this to
-c geqo=offsets the session's value of thegeqoparameter tooff. Spaces within this string are considered to separate command-line arguments, unless escaped with a backslash (\); write\\to represent a literal backslash. For a detailed discussion of the available options, consult Chapter 19.with_rsocketConnects to the server using
rsocketAPI. You must also set the listen_rdma_addresses variable for your server to enable RDMA connections viarsocket.application_nameSpecifies a value for the application_name configuration parameter.
fallback_application_nameSpecifies a fallback value for the application_name configuration parameter. This value will be used if no value has been given for
application_namevia a connection parameter or thePGAPPNAMEenvironment variable. Specifying a fallback name is useful in generic utility programs that wish to set a default application name but allow it to be overridden by the user.keepalivesControls whether client-side TCP keepalives are used. The default value is 1, meaning on, but you can change this to 0, meaning off, if keepalives are not wanted. This parameter is ignored for connections made via a Unix-domain socket.
keepalives_idleControls the number of seconds of inactivity after which TCP should send a keepalive message to the server. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where
TCP_KEEPIDLEor an equivalent socket option is available, and on Windows; on other systems, it has no effect.keepalives_intervalControls the number of seconds after which a TCP keepalive message that is not acknowledged by the server should be retransmitted. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where
TCP_KEEPINTVLor an equivalent socket option is available, and on Windows; on other systems, it has no effect.keepalives_countControls the number of TCP keepalives that can be lost before the client's connection to the server is considered dead. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where
TCP_KEEPCNTor an equivalent socket option is available; on other systems, it has no effect.ttyIgnored (formerly, this specified where to send server debug output).
replicationThis option determines whether the connection should use the replication protocol instead of the normal protocol. This is what Postgres Pro replication connections as well as tools such as pg_basebackup use internally, but it can also be used by third-party applications. For a description of the replication protocol, consult Section 54.4.
The following values, which are case-insensitive, are supported:
-
true,on,yes,1 The connection goes into physical replication mode.
databaseThe connection goes into logical replication mode, connecting to the database specified in the
dbnameparameter.-
false,off,no,0 The connection is a regular one, which is the default behavior.
In physical or logical replication mode, only the simple query protocol can be used.
-
sslmodeThis option determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. There are six modes:
disableonly try a non-SSL connection
allowfirst try a non-SSL connection; if that fails, try an SSL connection
prefer(default)first try an SSL connection; if that fails, try a non-SSL connection
requireonly try an SSL connection. If a root CA file is present, verify the certificate in the same way as if
verify-cawas specifiedverify-caonly try an SSL connection, and verify that the server certificate is issued by a trusted certificate authority (CA)
verify-fullonly try an SSL connection, verify that the server certificate is issued by a trusted CA and that the requested server host name matches that in the certificate
See Section 35.18 for a detailed description of how these options work.
sslmodeis ignored for Unix domain socket communication. If Postgres Pro is compiled without SSL support, using optionsrequire,verify-ca, orverify-fullwill cause an error, while optionsallowandpreferwill be accepted but libpq will not actually attempt an SSL connection.requiresslThis option is deprecated in favor of the
sslmodesetting.If set to 1, an SSL connection to the server is required (this is equivalent to
sslmoderequire). libpq will then refuse to connect if the server does not accept an SSL connection. If set to 0 (default), libpq will negotiate the connection type with the server (equivalent tosslmodeprefer). This option is only available if Postgres Pro is compiled with SSL support.sslcompressionIf set to 1, data sent over SSL connections will be compressed. If set to 0, compression will be disabled. The default is 0. This parameter is ignored if a connection without SSL is made.
SSL compression is nowadays considered insecure and its use is no longer recommended. OpenSSL 1.1.0 disables compression by default, and many operating system distributions disable it in prior versions as well, so setting this parameter to on will not have any effect if the server does not accept compression. On the other hand, OpenSSL before 1.0.0 does not support disabling compression, so this parameter is ignored with those versions, and whether compression is used depends on the server.
If security is not a primary concern, compression can improve throughput if the network is the bottleneck. Disabling compression can improve response time and throughput if CPU performance is the limiting factor.
sslcertThis parameter specifies the file name of the client SSL certificate, replacing the default
~/.postgresql/postgresql.crt. This parameter is ignored if an SSL connection is not made.sslkeyThis parameter specifies the location for the secret key used for the client certificate. It can either specify a file name that will be used instead of the default
~/.postgresql/postgresql.key, or it can specify a key obtained from an external “engine” (engines are OpenSSL loadable modules). An external engine specification should consist of a colon-separated engine name and an engine-specific key identifier. This parameter is ignored if an SSL connection is not made.sslrootcertThis parameter specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities. The default is
~/.postgresql/root.crt.sslcrlThis parameter specifies the file name of the SSL server certificate revocation list (CRL). Certificates listed in this file, if it exists, will be rejected while attempting to authenticate the server's certificate. The default is
~/.postgresql/root.crl.requirepeerThis parameter specifies the operating-system user name of the server, for example
requirepeer=postgres. When making a Unix-domain socket connection, if this parameter is set, the client checks at the beginning of the connection that the server process is running under the specified user name; if it is not, the connection is aborted with an error. This parameter can be used to provide server authentication similar to that available with SSL certificates on TCP/IP connections. (Note that if the Unix-domain socket is in/tmpor another publicly writable location, any user could start a server listening there. Use this parameter to ensure that you are connected to a server run by a trusted user.) This option is only supported on platforms for which thepeerauthentication method is implemented; see Section 20.9.krbsrvnameKerberos service name to use when authenticating with GSSAPI. This must match the service name specified in the server configuration for Kerberos authentication to succeed. (See also Section 20.6.)
gsslibGSS library to use for GSSAPI authentication. Currently this is disregarded except on Windows builds that include both GSSAPI and SSPI support. In that case, set this to
gssapito cause libpq to use the GSSAPI library for authentication instead of the default SSPI.serviceService name to use for additional parameters. It specifies a service name in
pg_service.confthat holds additional connection parameters. This allows applications to specify only a service name so connection parameters can be centrally maintained. See Section 35.16.target_session_attrsIf this parameter is set to
read-writeormaster, only a connection in which read-write transactions are accepted by default is considered acceptable. The querySHOW transaction_read_onlywill be sent upon any successful connection; if it returnson, the connection will be closed. If multiple hosts were specified in the connection string, any remaining servers will be tried just as if the connection attempt had failed. The default value of this parameter,any, regards all connections as acceptable.target_server_typeSame as target_session_attrs. This parameter is provided for backward compatibility with Postgres Pro Enterprise 9.6.