libpq is the C application programmer's interface to PostgreSQL. libpq is a set of library functions that allow client programs to pass queries to the PostgreSQL backend server and to receive the results of these queries. libpq is also the underlying engine for several other PostgreSQL application interfaces, including libpq++ (C++), libpgtcl (Tcl), Perl, and ECPG. So some aspects of libpq's behavior will be important to you if you use one of those packages.
Some short programs are included at the end of this chapter ( Seção 27.14 ) to show how to write programs that use libpq. There are also several complete examples of libpq applications in the directory src/test/examples in the source code distribution.
Client programs that use libpq must include the header file libpq-fe.h and must link with the libpq library.
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
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.
PQconnectdb
PGconn *PQconnectdb(const char *conninfo);This function opens a new database connection using the parameters taken from the string conninfo. Unlike
PQsetdbLogin
below, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analogues PQconnectStart
and PQconnectPoll
) is preferred for new application programming.
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 form keyword = value. (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 \\.) Spaces around the equal sign are optional.
The currently recognized parameter key words are:
If any parameter is unspecified, then the corresponding environment variable (see Seção 27.10 ) is checked. If the environment variable is not set either, then built-in defaults are used.
PQsetdbLogin
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
PQconnectdb
with a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. Write NULL or an empty string for any one of the fixed parameters that is to be defaulted.
PQsetdb
PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);This is a macro that calls
PQsetdbLogin
with null pointers for the login and pwd parameters. It is provided for backward compatibility with very old programs.
PQconnectStart
PQconnectPoll
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType PQconnectPoll(PGconn *conn);These two 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
PQconnectdb
, and so the application can manage this operation in parallel with other activities.
The database connection is made using the parameters taken from the string conninfo, passed to PQconnectStart
. This string is in the same format as described above for PQconnectdb
.
Neither PQconnectStart
nor PQconnectPoll
will block, so long as a number of restrictions are met:
PQconnectdb
above for details.
PQtrace
, ensure that the stream object into which you trace will not block.
PQconnectPoll
, as described below.
PQconnectStart
, call status = PQstatus(conn). If status equals CONNECTION_BAD, PQconnectStart
has failed.
If PQconnectStart
succeeds, the next stage is to poll libpq so that it may proceed with the connection sequence. Use PQsocket(conn)
to obtain the descriptor of the socket underlying the database connection. Loop thus: If PQconnectPoll(conn)
last returned PGRES_POLLING_READING, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then call PQconnectPoll(conn)
again. Conversely, if PQconnectPoll(conn)
last returned PGRES_POLLING_WRITING, wait until the socket is ready to write, then call PQconnectPoll(conn)
again. If you have yet to call PQconnectPoll
, i.e., just after the call to PQconnectStart
, behave as if it last returned PGRES_POLLING_WRITING. Continue this loop until PQconnectPoll(conn)
returns PGRES_POLLING_FAILED, indicating the connection procedure has failed, or PGRES_POLLING_OK, indicating the connection has been successfully made.
At any time during connection, the status of the connection may be checked by calling PQstatus
. If this gives CONNECTION_BAD, then the connection procedure has failed; if it gives CONNECTION_OK
, then the connection is ready. Both of these states are equally detectable from the return value of PQconnectPoll
, described above. Other states may also occur during (and only during) an asynchronous connection procedure. These indicate the current stage of the connection procedure and may be useful to provide feedback to the user for example. These statuses are:
Note that, although these constants will remain (in order to maintain compatibility), an application should never rely upon these appearing 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_timeout connection parameter is ignored when using PQconnectPoll
; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, PQconnectStart
followed by a PQconnectPoll
loop is equivalent to PQconnectdb
.
Note that if PQconnectStart
returns a non-null pointer, you must call PQfinish
when 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.
PQconndefaults
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; /* Character to display for 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 may be used to determine all possible
PQconnectdb
options and their current default values. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer. Note that the current default values (val fields) 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 to PQconninfoFree
. If this is not done, a small amount of memory is leaked for each call to PQconndefaults
.
PQfinish
void PQfinish(PGconn *conn);Note that even if the server connection attempt fails (as indicated by
PQstatus
), the application should call PQfinish
to free the memory used by the PGconn object. The PGconn pointer must not be used again after PQfinish
has been called.
PQreset
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 may be useful for error recovery if a working connection is lost.
PQresetStart
PQresetPoll
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 may 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 as PQconnectStart
and PQconnectPoll
.
To initiate a connection reset, call PQresetStart
. If it returns 0, the reset has failed. If it returns 1, poll the reset using PQresetPoll
in exactly the same way as you would create the connection using PQconnectPoll
.