| The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide
by The PostgreSQL Global Development Group Paperback (6"x9"), 478 pages ISBN 9781906966065 RRP £14.95 ($19.95) Sales of this book support the PostgreSQL project! Get a printed copy>>> |
1.1 Database Connection Control Functions
The following functions deal with making a connection to a
PostgreSQL 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
whether a connection was successfully made before queries are sent
via the connection object.
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
execfrom the child process to load a new executable is safe.
Note: On Windows, there is a way to improve performance if a single database connection is repeatedly started and shutdown. Internally, libpq calls
WSAStartup()andWSACleanup()for connection startup and shutdown, respectively.WSAStartup()increments an internal Windows library reference count which is decremented byWSACleanup(). When the reference count is just one, callingWSACleanup()frees all resources and all DLLs are unloaded. This is an expensive operation. To avoid this, an application can manually callWSAStartup()so resources will not be freed when the last database connection is closed.
PQconnectdbParams-
Makes a new connection to the database server.
PGconn *PQconnectdbParams(const char **keywords, const char **values, int expand_dbname);
This function opens a new database connection using the parameters taken from twoNULL-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. Whenexpand_dbnameis non-zero, thedbnamekey word value is allowed to be recognized as aconninfostring. See below for details. The passed arrays can be empty to use all default parameters, or can contain one or more parameter settings. They should be matched in length. Processing will stop with the last non-NULLelement of thekeywordsarray. The currently recognized parameter key words are:host-
Name of host to connect to.
If this 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 is to connect to a Unix-domain socket in ‘/tmp’ (or whatever socket directory was specified when PostgreSQL was built). On machines without Unix-domain sockets, the default is to connect tolocalhost. hostaddr-
Numeric 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. Usinghostaddrinstead 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 Kerberos, GSSAPI, or SSPI authentication, as well as for full SSL certificate verification. The following rules are used: Ifhostis specified withouthostaddr, a host name lookup occurs. Ifhostaddris specified withouthost, the value forhostaddrgives the server address. The connection attempt will fail in any of the cases where a host name is required. If bothhostandhostaddrare specified, the value forhostaddrgives the server address. The value forhostis ignored unless needed for authentication or verification purposes, in which case it will be used as the host name. Note that authentication is likely to fail ifhostis not the name of the machine athostaddr. Also, note thathostrather thanhostaddris used to identify the connection in ‘~/.pgpass’ (see section 1.14 The Password File). 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 tolocalhost. port- Port number to connect to at the server host, or socket file name extension for Unix-domain connections.
dbname- The database name. Defaults to be the same as the user name.
user- PostgreSQL user name to connect as. Defaults to be the same as the operating system name of the user running the application.
password- Password to be used if the server demands password authentication.
connect_timeout- Maximum wait for connection, in seconds (write as a decimal integer string). Zero or not specified means wait indefinitely. It is not recommended to use a timeout of less than 2 seconds.
options-
Adds command-line options to send to the server at run-time.
For example, setting this to
-c geqo=offsets the session's value of thegeqoparameter tooff. For a detailed discussion of the available options, consult Volume 3: Server Configuration. application_name-
Specifies a value for the
application_nameconfiguration parameter. fallback_application_name-
Specifies a fallback value for the
application_nameconfiguration parameter. This value will be used if no value has been given forapplication_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. keepalives- Controls 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_idle-
Controls 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 the
TCP_KEEPIDLEorTCP_KEEPALIVEsocket option is available, and on Windows; on other systems, it has no effect. keepalives_interval-
Controls 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 the
TCP_KEEPINTVLsocket option is available, and on Windows; on other systems, it has no effect. keepalives_count-
Controls 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 the
TCP_KEEPINTVLsocket option is available; on other systems, it has no effect. tty- Ignored (formerly, this specified where to send server debug output).
sslmode-
This option determines whether or with what priority a secure
SSL TCP/IP connection will be negotiated with the
server. There are six modes:
See section 1.17 SSL Support for a detailed description of how these options work.Table 1-1:
sslmodeoptionsOption Description
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
verify-caonly try an SSL connection, and verify that the server certificate is issued by a trusted CA
verify-fullonly try an SSL connection, verify that the server certificate is issued by a trusted CA and that the server host name matches that in the certificate sslmodeis ignored for Unix domain socket communication. If PostgreSQL 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. requiressl-
This option is deprecated in favor of the
sslmodesetting. If set to 1, an SSL connection to the server is required (this is equivalent tosslmoderequire). 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 PostgreSQL is compiled with SSL support. sslcert- This 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.
sslkey- This 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.
sslrootcert- This 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’.
sslcrl- This parameter specifies the file name of the SSL 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’.
krbsrvname- Kerberos service name to use when authenticating with Kerberos 5 or GSSAPI. This must match the service name specified in the server configuration for Kerberos authentication to succeed. (See also Volume 3: Kerberos authentication and Volume 3: GSSAPI authentication.)
gsslib-
GSS library to use for GSSAPI authentication. Only used on Windows.
Set to
gssapito force libpq to use the GSSAPI library for authentication instead of the default SSPI. service- Service name to use for additional parameters. It specifies a service name in ‘pg_service.conf’ that holds additional connection parameters. This allows applications to specify only a service name so connection parameters can be centrally maintained. See section 1.15 The Connection Service File.
expand_dbnameis non-zero anddbnamecontains an=sign, it is taken as aconninfostring in exactly the same way as if it had been passed toPQconnectdb(see below). Previously processed key words will be overridden by key words in theconninfostring. In general key words are processed from the beginning of these arrays in index order. The effect of this is that when key words are repeated, the last processed value is retained. Therefore, through careful placement of thedbnamekey word, it is possible to determine what may be overridden by aconninfostring, and what may not. PQconnectdb-
Makes 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 stringconninfo. The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the formkeyword = value. Spaces around the equal sign are optional. To write an empty value, or a value containing spaces, surround it with single quotes, e.g.,keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e.,\'and\\. The currently recognized parameter key words are the same as above. PQsetdbLogin-
Makes 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 ofPQconnectdbwith 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 thedbNamecontains an=sign, 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 above. PQsetdb-
Makes a new connection to the database server.
PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);This is a macro that callsPQsetdbLoginwith null pointers for theloginandpwdparameters. It is provided for backward compatibility with very old programs. PQconnectStartParamsPQconnectStartPQconnectPoll-
Make a connection to the database server in a nonblocking manner.
PGconn *PQconnectStartParams(const char **keywords, const char **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 insidePQconnectdbParamsorPQconnectdb, and so the application can manage this operation in parallel with other activities. WithPQconnectStartParams, the database connection is made using the parameters taken from thekeywordsandvaluesarrays, and controlled byexpand_dbname, as described above forPQconnectdbParams. WithPQconnectStart, the database connection is made using the parameters taken from the stringconninfoas described above forPQconnectdb. NeitherPQconnectStartParamsnorPQconnectStartnorPQconnectPollwill block, so long as a number of restrictions are met:-
The
hostaddrandhostparameters are used appropriately to ensure that name and reverse name queries are not made. See the documentation of these parameters underPQconnectdbParamsabove for details. -
If you call
PQtrace, ensure that the stream object into which you trace will not block. -
You ensure that the socket is in the appropriate state
before calling
PQconnectPoll, as described below.
PQconnectStartParamsis analogous toPQconnectStartshown below. To begin a nonblocking connection request, call the connect function asconn = PQconnectStart("connection_info_string"). Ifconnis 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). On return fromPQconnectStart, callstatus = PQstatus(conn). IfstatusequalsCONNECTION_BAD,PQconnectStarthas failed. IfPQconnectStartsucceeds, 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. Loop thus: IfPQconnectPoll(conn)last returnedPGRES_POLLING_READING, wait until the socket is ready to read (as indicated byselect(),poll(), or similar system function). Then callPQconnectPoll(conn)again. Conversely, ifPQconnectPoll(conn)last returnedPGRES_POLLING_WRITING, wait until the socket is ready to write, then callPQconnectPoll(conn)again. If you have yet to callPQconnectPoll, i.e., just after the call toPQconnectStart, 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 callingPQstatus. If this givesCONNECTION_BAD, then the connection procedure has failed; if it givesCONNECTION_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_STARTED- Waiting for connection to be made.
CONNECTION_MADE- Connection OK; waiting to send.
CONNECTION_AWAITING_RESPONSE- Waiting for a response from the server.
CONNECTION_AUTH_OK- Received authentication; waiting for backend start-up to finish.
CONNECTION_SSL_STARTUP- Negotiating SSL encryption.
CONNECTION_SETENV- Negotiating environment-driven parameter settings.
switch(PQstatus(conn)) { case CONNECTION_STARTED: feedback = "Connecting..."; break; case CONNECTION_MADE: feedback = "Connected to server..."; break; . . . default: feedback = "Connecting..."; }Theconnect_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 ifPQconnectStartreturns 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. -
The
PQconndefaults-
Returns 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 possiblePQconnectdboptions 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. Callers must treat the connection options data as read-only. After processing the options array, free it by passing it toPQconninfoFree. If this is not done, a small amount of memory is leaked for each call toPQconndefaults. PQconninfoParse-
Returns 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 returnsNULLif there is a problem with the connection string. This can be used to determine thePQconnectdboptions in the provided connection string. The return value points to an array ofPQconninfoOptionstructures, which ends with an entry having a nullkeywordpointer. Note that only options explicitly specified in the string will have values set in the result array; no defaults are inserted. Iferrmsgis notNULL, then*errmsgis set toNULLon success, else to amalloc'd error string explaining the problem. (It is also possible for*errmsgto be set toNULLeven whenNULLis returned; this indicates an out-of-memory situation.) After processing the options array, free it by passing it toPQconninfoFree. 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. PQfinish-
Closes 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 byPQstatus), the application should callPQfinishto free the memory used by thePGconnobject. ThePGconnpointer must not be used again afterPQfinishhas been called. PQreset-
Resets the communication channel to the server.
void PQreset(PGconn *conn);
This function will close the connection to the server and attempt to reestablish a new connection to the same server, using all the same parameters previously used. This might be useful for error recovery if a working connection is lost. PQresetStartPQresetPoll-
Reset 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 reestablish a new connection to the same server, using all the same parameters previously used. This can be useful for error recovery if a working connection is lost. They differ fromPQreset(above) in that they act in a nonblocking manner. These functions suffer from the same restrictions asPQconnectStartParams,PQconnectStartandPQconnectPoll. To initiate a connection reset, callPQresetStart. 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.
| ISBN 9781906966065 | The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide | See the print edition |