33.1. 資料庫連線控制函數
版本:11
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 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(
conn
, "SELECT pg_catalog.set_config('search_path', '', false)") after connecting. This consideration is not specific to libpq; it applies to every interface for executing arbitrary SQL commands.
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.
PQconnectdbParams
Makes a new connection to the database server.
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. Unlike PQsetdbLogin
below, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analogs PQconnectStartParams
and PQconnectPoll
) is preferred for new application programming.
The currently recognized parameter key words are listed in Section 33.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 NULL
entry in the keywords
array. Also, if the values
entry associated with a non-NULL
keywords
entry is NULL
or an empty string, that entry is ignored and processing continues with the next pair of array entries.
When expand_dbname
is non-zero, the value for the first dbname
key 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 33.1.1.) Only the first occurrence of dbname
is treated in this way; any subsequent dbname
parameter 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 NULL
or empty) is used. This rule applies in particular when a key word found in a connection string conflicts with one appearing in the keywords
array. 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 expanded dbname
entry can be overridden by fields of the connection string, and in turn those fields are overridden by array entries appearing after dbname
(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 33.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.
PQconnectdb
Makes a new connection to the database server.
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 33.1.1 for details.
PQsetdbLogin
Makes a new connection to the database server.
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.
If the dbName
contains an =
sign or has a valid connection URI prefix, it is taken as a conninfo
string in exactly the same way as if it had been passed to PQconnectdb
, and the remaining parameters are then applied as specified for PQconnectdbParams
.
PQsetdb
Makes a new connection to the database server.
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.PQconnectStartParams
PQconnectStart
PQconnectPoll
Make a connection to the database server in a nonblocking manner.
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 PQconnectdbParams
or PQconnectdb
, 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 the keywords
and values
arrays, and controlled by expand_dbname
, as described above for PQconnectdbParams
.
With PQconnectStart
, the database connection is made using the parameters taken from the string conninfo
as described above for PQconnectdb
.
Neither PQconnectStartParams
nor PQconnectStart
nor PQconnectPoll
will block, so long as a number of restrictions are met:
The
hostaddr
parameter must be used appropriately to prevent DNS queries from being made. See the documentation of this parameter in Section 33.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 PQconnectStart
or PQconnectStartParams
. If the result is null, then libpq has been unable to allocate a new PGconn
structure. Otherwise, a valid PGconn
pointer is returned (though not yet representing a valid connection to the database). Next call PQstatus(conn)
. If the result is CONNECTION_BAD
, the connection attempt has already failed, typically because of invalid connection parameters.
If PQconnectStart
or PQconnectStartParams
succeeds, the next stage is to poll libpq so that it can proceed with the connection sequence. Use PQsocket(conn)
to obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same across PQconnectPoll
calls.) 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. On the first iteration, i.e., if you have yet to call PQconnectPoll
, 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 can be checked by calling PQstatus
. If this call returns CONNECTION_BAD
, then the connection procedure has failed; if the call returns CONNECTION_OK
, then the connection is ready. Both of these states are equally detectable from the return value of PQconnectPoll
, 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.
CONNECTION_CHECK_WRITABLE
Checking if connection is able to handle write transactions.
CONNECTION_CONSUME
Consuming 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:
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 when PQconnectStart
or PQconnectStartParams
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
Returns the default connection options.
Returns a connection options array. This can 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. The null pointer is returned if memory could not be allocated. Note that the current default values (val
fields) 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 to PQconndefaults
.PQconninfo
Returns the connection options used by a live connection.
Returns a connection options array. This can be used to determine all possible PQconnectdb
options and the values that were used to connect to the server. The return value points to an array of PQconninfoOption
structures, which ends with an entry having a null keyword
pointer. All notes above for PQconndefaults
also apply to the result of PQconninfo
.
PQconninfoParse
Returns parsed connection options from the provided connection string.
Parses a connection string and returns the resulting options as an array; or returns NULL
if there is a problem with the connection string. This function can be used to extract the PQconnectdb
options in the provided connection string. The return value points to an array of PQconninfoOption
structures, which ends with an entry having a null keyword
pointer.
All legal options will be present in the result array, but the PQconninfoOption
for any option not present in the connection string will have val
set to NULL
; default values are not inserted.
If errmsg
is not NULL
, then *errmsg
is set to NULL
on success, else to a malloc
'd error string explaining the problem. (It is also possible for *errmsg
to be set to NULL
and the function to return NULL
; 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 to PQconninfoParse
. Conversely, if an error occurs and errmsg
is not NULL
, be sure to free the error string using PQfreemem
.
PQfinish
Closes the connection to the server. Also frees memory used by the PGconn
object.
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
Resets the communication channel to the server.
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.
PQresetStart
PQresetPoll
Reset the communication channel to the server, in a nonblocking manner.
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 as PQconnectStartParams
, 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
.
PQpingParams
PQpingParams
reports the status of the server. It accepts connection parameters identical to those of PQconnectdbParams
, 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.
The function returns one of the following values:
PQPING_OK
The server is running and appears to be accepting connections.
PQPING_REJECT
The server is running but is in a state that disallows connections (startup, shutdown, or crash recovery).
PQPING_NO_RESPONSE
The 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_ATTEMPT
No 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).
PQping