Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
30.1. Database Connection Control Functions
Prev UpChapter 30. libpq - C LibraryHome Next

30.1. Database Connection Control Functions

The following functions deal with making a connection to aPostgres 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 aPGconn object, which is obtained from the functionPQconnectdb,PQconnectdbParams, orPQsetdbLogin. Note that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate thePGconn object. ThePQstatus 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 asecure schema usage pattern, begin each session by removing publicly-writable schemas fromsearch_path. One can set parameter key wordoptions to value-csearch_path=. Alternately, one can issuePQexec(conn, "SELECT pg_catalog.set_config('search_path', '', false)") after connecting. This consideration is not specific tolibpq; 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 anexec from the child process to load a new executable is safe.

PQconnectdbParams

Makes 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 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. UnlikePQsetdbLogin below, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analogsPQconnectStartParams andPQconnectPoll) is preferred for new application programming.

The currently recognized parameter key words are listed inSection 30.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 firstNULL entry in thekeywords array. Also, if thevalues entry associated with a non-NULLkeywords entry isNULL or an empty string, that entry is ignored and processing continues with the next pair of array entries.

Whenexpand_dbname is non-zero, the value for the firstdbname key word is checked to see if it is aconnection string. If so, it isexpanded 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 inSection 30.1.1.) Only the first occurrence ofdbname is treated in this way; any subsequentdbname 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 notNULL or empty) is used. This rule applies in particular when a key word found in a connection string conflicts with one appearing in thekeywords 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 expandeddbname entry 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 (seeSection 30.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.

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, or it can contain aURI. SeeSection 30.1.1 for details.

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 ofPQconnectdb with a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. WriteNULL or an empty string for any one of the fixed parameters that is to be defaulted.

If thedbName contains an= sign or has a valid connectionURI prefix, it is taken as aconninfo string in exactly the same way as if it had been passed toPQconnectdb, and the remaining parameters are then applied as specified forPQconnectdbParams.

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 callsPQsetdbLogin with null pointers for thelogin andpwd 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.

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 insidePQconnectdbParams orPQconnectdb, and so the application can manage this operation in parallel with other activities.

WithPQconnectStartParams, the database connection is made using the parameters taken from thekeywords andvalues arrays, and controlled byexpand_dbname, as described above forPQconnectdbParams.

WithPQconnectStart, the database connection is made using the parameters taken from the stringconninfo as described above forPQconnectdb.

NeitherPQconnectStartParams norPQconnectStart norPQconnectPoll will block, so long as a number of restrictions are met:

  • Thehostaddr andhost parameters are used appropriately to ensure that name and reverse name queries are not made. See the documentation of these parameters inSection 30.1.2 for details.

  • If you callPQtrace, ensure that the stream object into which you trace will not block.

  • You ensure that the socket is in the appropriate state before callingPQconnectPoll, as described below.

Note: use ofPQconnectStartParams is analogous toPQconnectStart shown below.

To begin a nonblocking connection request, callconn = PQconnectStart("connection_info_string"). Ifconn is null, thenlibpq has been unable to allocate a newPGconn structure. Otherwise, a validPGconn pointer is returned (though not yet representing a valid connection to the database). On return fromPQconnectStart, callstatus = PQstatus(conn). Ifstatus equalsCONNECTION_BAD,PQconnectStart has failed.

IfPQconnectStart succeeds, the next stage is to polllibpq 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 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_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.

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...";}

Theconnect_timeout connection parameter is ignored when usingPQconnectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise,PQconnectStart followed by aPQconnectPoll loop is equivalent toPQconnectdb.

Note that ifPQconnectStart returns a non-null pointer, you must callPQfinish 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.

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 possiblePQconnectdb options and their current default values. The return value points to an array ofPQconninfoOption structures, which ends with an entry having a nullkeyword 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 toPQconninfoFree. If this is not done, a small amount of memory is leaked for each call toPQconndefaults.

PQconninfo

Returns the connection options used by a live connection.

PQconninfoOption *PQconninfo(PGconn *conn);

Returns a connection options array. This can be used to determine all possiblePQconnectdb options and the values that were used to connect to the server. The return value points to an array ofPQconninfoOption structures, which ends with an entry having a nullkeyword pointer. All notes above forPQconndefaults also apply to the result ofPQconninfo.

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 returnsNULL if there is a problem with the connection string. This function can be used to extract thePQconnectdb options in the provided connection string. The return value points to an array ofPQconninfoOption structures, which ends with an entry having a nullkeyword pointer.

All legal options will be present in the result array, but thePQconninfoOption for any option not present in the connection string will haveval set toNULL; default values are not inserted.

Iferrmsg is notNULL, then*errmsg is set toNULL on success, else to amalloc'd error string explaining the problem. (It is also possible for*errmsg to be set toNULL and the function to returnNULL; this indicates an out-of-memory condition.)

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 anderrmsg is notNULL, be sure to free the error string usingPQfreemem.

PQfinish

Closes the connection to the server. Also frees memory used by thePGconn object.

void PQfinish(PGconn *conn);

Note that even if the server connection attempt fails (as indicated byPQstatus), the application should callPQfinish to free the memory used by thePGconn object. ThePGconn pointer must not be used again afterPQfinish has 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.

PQresetStart
PQresetPoll

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,PQconnectStart andPQconnectPoll.

To initiate a connection reset, callPQresetStart. If it returns 0, the reset has failed. If it returns 1, poll the reset usingPQresetPoll in exactly the same way as you would create the connection usingPQconnectPoll.

PQpingParams

PQpingParams reports 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_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

PQping reports 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 forPQpingParams.

30.1.1. Connection Strings

Severallibpq functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plainkeyword = value strings andRFC 3986 URIs.

30.1.1.1. Keyword/Value Connection Strings

In the first format, 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\\.

Example:

host=localhost port=5432 dbname=mydb connect_timeout=10

The recognized parameter key words are listed inSection 30.1.2.

30.1.1.2. Connection URIs

The general form for a connectionURI is:

postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...]

TheURI scheme designator can be eitherpostgresql:// orpostgres://. Each of the remainingURI parts is optional. The following examples illustrate validURI syntax:

postgresql://postgresql://localhostpostgresql://localhost:5433postgresql://localhost/mydbpostgresql://user@localhostpostgresql://user:secret@localhostpostgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp

Values that would normally appear in the hierarchical part of theURI can alternatively be given as named parameters. For example:

postgresql:///mydb?host=localhost&port=5433

All named parameters must match key words listed inSection 30.1.2, except that for compatibility with JDBC connectionURIs, instances ofssl=true are translated intosslmode=require.

Percent-encoding may be used to include symbols with special meaning in any of theURI parts.

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 parameterhost. 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/postgresqlpostgresql://%2Fvar%2Flib%2Fpostgresql/dbname

30.1.2. Parameter Key Words

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 whenhost is not specified is to connect to a Unix-domain socket in/tmp (or whatever socket directory was specified whenPostgres Pro 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.

Usinghostaddr instead ofhost allows 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-full SSL certificate verification. The following rules are used:

  • Ifhost is specified withouthostaddr, a host name lookup occurs.

  • Ifhostaddr is specified withouthost, the value forhostaddr gives the server network address. The connection attempt will fail if the authentication method requires a host name.

  • If bothhost andhostaddr are specified, the value forhostaddr gives the server network address. The value forhost is 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 ifhost is not the name of the server at network addresshostaddr. Also, note thathost rather thanhostaddr is used to identify the connection in~/.pgpass (seeSection 30.15).

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. In certain contexts, the value is checked for extended formats; seeSection 30.1.1 for more details on those.

user

Postgres Pro 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.

client_encoding

This sets theclient_encoding configuration parameter for this connection. In addition to the values accepted by the corresponding server option, you can useauto to determine the right encoding from the current locale in the client (LC_CTYPE environment variable on Unix systems).

options

Specifies command-line options to send to the server at connection start. For example, setting this to-c geqo=off sets the session's value of thegeqo parameter 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, consultChapter 18.

application_name

Specifies a value for theapplication_name configuration parameter.

fallback_application_name

Specifies a fallback value for theapplication_name configuration parameter. This value will be used if no value has been given forapplication_name via a connection parameter or thePGAPPNAME environment 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 whereTCP_KEEPIDLE or an equivalent socket 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 whereTCP_KEEPINTVL or an equivalent socket 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 whereTCP_KEEPCNT or an equivalent socket 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 secureSSL TCP/IP connection will be negotiated with the server. There are six modes:

SeeSection 30.18 for a detailed description of how these options work.

sslmode is ignored for Unix domain socket communication. IfPostgres Pro is compiled without SSL support, using optionsrequire,verify-ca, orverify-full will cause an error, while optionsallow andprefer will be accepted butlibpq will not actually attempt anSSL connection.

requiressl

This option is deprecated in favor of thesslmode setting.

If set to 1, anSSL connection to the server is required (this is equivalent tosslmoderequire).libpq will then refuse to connect if the server does not accept anSSL connection. If set to 0 (default),libpq will negotiate the connection type with the server (equivalent tosslmodeprefer). This option is only available ifPostgres Pro is compiled with SSL support.

sslcompression

If set to 1 (default), data sent over SSL connections will be compressed (this requiresOpenSSL version 0.9.8 or later). If set to 0, compression will be disabled (this requiresOpenSSL 1.0.0 or later). This parameter is ignored if a connection without SSL is made, or if the version ofOpenSSL used does not support it.

Compression uses CPU time, but can improve throughput if the network is the bottleneck. Disabling compression can improve response time and throughput if CPU performance is the limiting factor.

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 externalengine (engines areOpenSSL 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.

requirepeer

This parameter specifies the operating-system user name of the server, for examplerequirepeer=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/tmp or 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 thepeer authentication method is implemented; seeSection 19.3.6.

krbsrvname

Kerberos 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 alsoSection 19.3.3.)

gsslib

GSS 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 togssapi to cause 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 inpg_service.conf that holds additional connection parameters. This allows applications to specify only a service name so connection parameters can be centrally maintained. SeeSection 30.16.


Prev Home Next
Chapter 30. libpq - C Library Up 30.2. Connection Status Functions
pdfepub
Go to Postgres Pro Standard 9.6
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp