| PostgreSQL Reference Manual - Volume 2 - Programming Guide by The PostgreSQL Global Development Group Paperback (6"x9"), 408 pages ISBN 0954612035 RRP £19.95 ($34.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 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-
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. UnlikePQsetdbLoginbelow, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analoguesPQconnectStartandPQconnectPoll) 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 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: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 may be important in applications with time constraints. However, Kerberos authentication requires the host name. The following therefore applies: Ifhostis specified withouthostaddr, a host name lookup occurs. Ifhostaddris specified withouthost, the value forhostaddrgives the remote address. When Kerberos is used, a reverse name query occurs to obtain the host name for Kerberos. If bothhostandhostaddrare specified, the value forhostaddrgives the remote address; the value forhostis ignored, unless Kerberos is used, in which case that value is used for Kerberos authentication. (Note that authentication is likely to fail if libpq is passed a host name that is not the name of the machine athostaddr.) Also,hostrather thanhostaddris used to identify the connection in ‘~/.pgpass’ (see section 1.13 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- Command-line options to be sent to the server.
tty- Ignored (formerly, this specified where to send server debug output).
sslmode-
This option determines whether or with what priority an
SSL connection will be negotiated with the
server. There are four modes:
disablewill attempt only an unencrypted SSL connection;allowwill negotiate, trying first a non-SSL connection, then if that fails, trying an SSL connection;prefer(the default) will negotiate, trying first an SSL connection, then if that fails, trying a regular non-SSL connection;requirewill try only an SSL connection. If PostgreSQL is compiled without SSL support, using optionrequirewill cause an error, while optionsallowandpreferwill be accepted but libpq will not in fact 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. krbsrvname- Kerberos service name to use when authenticating with Kerberos 5. This must match the service name specified in the server configuration for Kerberos authentication to succeed. (See also Volume 3: Kerberos authentication.)
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.14 The Connection Service File.
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. 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. PQconnectStartPQconnectPoll-
Make a connection to the database server in a nonblocking manner.
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 insidePQconnectdb, and so the application can manage this operation in parallel with other activities. The database connection is made using the parameters taken from the stringconninfo, passed toPQconnectStart. This string is in the same format as described above forPQconnectdb. NeitherPQconnectStartnorPQconnectPollwill 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 underPQconnectdbabove 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.
conn = 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 may 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 may 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 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: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; /* 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 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. 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 may 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 may 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 asPQconnectStartandPQconnectPoll. 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 0954612035 | PostgreSQL Reference Manual - Volume 2 - Programming Guide | See the print edition |