randolf.ca
1.00
Randolf Richardson's C++ classes
|
The pq namespace is an object-oriented interface version of the PostgreSQL C library API, but with resources freed automatically in the destructor (in accordance with RAII principles), errors thrown as exceptions, etc. More...
#include <pq/connection>
Public Member Functions | |
connection () noexcept | |
Default constructor. This does not connect to a PostgreSQL database (see the connectdb and connectdbParams methods). | |
connection (PGconn *conn) noexcept | |
Constructor that uses an existing PGconn handle. If the handle has not yet been connected to a PostgreSQL database, then it will need to be (see the connectdb and connectdbParams methods). | |
~connection () noexcept | |
Destructor, which automatically performs the following actions once the instantiated object of this class goes out of scope: | |
PGconn * | _handle (const bool handover=false) noexcept |
Obtain the underlying PostgreSQL database connection handle. | |
int32_t | _pg_type (const char *typname, const uint datatype=0) noexcept |
Obtain OID from cached pg_type table. The pg_type cache must first be initialized (see the cache_pg_types flag in any of the connectdb and connectdbParams methods). | |
int | backendPID () |
Returns the Process ID (PID) of the backend process handling this connection. | |
connection & | connectdb (const char *connection_string, const int cache_pg_types=0) |
Connect to a database. | |
connection & | connectdb (const std::string &connection_string, const int cache_pg_types=0) |
Connect to a database. | |
connection & | connectdbParams (const char *const *keywords, const char *const *values, const bool expand_dbname, const int cache_pg_types=0) |
Connect to a database. | |
connection & | connectdbParams (const std::initializer_list< const std::string > keywords, const std::initializer_list< const std::string > values, const bool expand_dbname, const int cache_pg_types=0) |
Connect to a database. | |
bool | connectionNeedsPassword () noexcept |
Indicates whether the connection authentication method required a password, but none was available. | |
bool | connectionUsedPassword () noexcept |
Indicates whether the connection authentication method used a password. | |
PostgresPollingStatusType | connectPoll (const int cache_pg_types=0) |
Poll an ongoing attempt to connect to a database in a non-blocking fashion. | |
connection & | connectStart (const char *connection_string) |
Connect to a database in a non-blocking fashion. | |
connection & | connectStart (const std::string &connection_string) |
Connect to a database in a non-blocking fashion. | |
connection & | connectStartParams (const char *const *keywords, const char *const *values, const bool expand_dbname) |
Connect to a database in a non-blocking fashion. | |
connection & | connectStartParams (const std::initializer_list< const std::string > keywords, const std::initializer_list< const std::string > values, const bool expand_dbname) |
Connect to a database in a non-blocking fashion. | |
PQconninfoOption * | conninfo () noexcept |
Returns the connection options used by a live connection. | |
char * | db () noexcept |
Returns the database name of the connection. | |
result | describePortal (const char *portalName) |
Obtains information about a previously created portal. | |
result | describePrepared (const char *stmtName) |
Obtain information about the specified - by name - prepared statement. | |
char * | errorMessage () noexcept |
Returns the error message most recently generated by an operation on the underlying connection. | |
unsigned char * | escapeByteaConn (const unsigned char *from, const size_t from_length, size_t *to_length) |
Escapes binary data for use within an SQL command with the bytea data type. As with the escapeStringConn method, this is only used when inserting data directly into an SQL command string. | |
char * | escapeIdentifier (const char *str, const size_t length) |
Escape a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved. | |
char * | escapeLiteral (const char *str, const size_t length) |
Escape a string for use within an SQL command. This is useful when inserting data values as literal constants in SQL commands. Certain characters (such as quotes and backslashes) must be escaped to prevent them from being interpreted specially by the SQL parser; this method performs this operation. | |
size_t | escapeStringConn (char *to, const char *from, size_t length, int *error=nullptr) |
The escapeStringConn method escapes string literals, much like the escapeLiteral method does. However, unlike the escapeLiteral method, the caller is responsible for providing an appropriately sized to buffer beforehand. Furthermore, this escapeStringConn method does not generate the apostrophes that must surround PostgreSQL string literals; they should be provided in the SQL command that the result is inserted into. | |
result | exec (const char *query_string) |
Submit a command/query to the server and wait for the result. | |
result | exec (const std::string &query_string) |
Submit a command/query to the server and wait for the result. | |
result | execParams (const char *query_string, const int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, const int resultFormat) |
Submit a command/query to the server and wait for the result, with the ability to pass parameters separately from the SQL command text. | |
result | execParams (const std::string query_string, const std::initializer_list< const char * > paramValues, const int resultFormat=0, const int *paramLengths=nullptr, const int *paramFormats=nullptr, const std::initializer_list< const Oid > paramTypes={}) |
Submit a command/query to the server and wait for the result, with the ability to pass parameters separately from the SQL command text. | |
result | execPrepared (const char *stmtName, const int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, const int resultFormat) |
Sends a request to execute a prepared statement with given parameters, and waits for the result. | |
connection & | finish () |
Closes the connection to the server. Also frees memory used by the underlying conn object. | |
void * | getssl () noexcept |
Returns the SSL structure used in the connection. | |
char * | host () |
Returns the hostname of the active connection. This can be a hostname, an IP address, or a directory path (if the connection is via Unix socket; in which case the path can be distinguished because it will always be an absolute path, beginning with / .) | |
char * | hostaddr () |
Returns the server IP address of the active connection. This can be the address that a hostname resolved to, or an IP address provided through the hostaddr connection parameter. | |
char * | options () noexcept |
Returns the command-line options passed in the connection request. | |
const char * | parameterStatus (const char *paramName) |
Returns the status of the connection. | |
char * | pass () noexcept |
Returns the password of the connection. | |
char * | port () |
Returns the TCP port number of the active connection. | |
result | prepare (const char *stmtName, const char *query, const int nParams, const Oid *paramTypes=nullptr) |
Submits a request to create a prepared statement with the given parameters, and waits for completion. | |
int | protocolVersion () |
Interrogates the frontend/backend protocol being used. | |
connection & | reset () |
Re-connect to the database, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods. | |
PostgresPollingStatusType | resetPoll () |
Re-connect to the database in a non-blocking fashion, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods. | |
connection & | resetStart () |
Re-connect to the database in a non-blocking fashion, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods. | |
int | serverVersion () |
Returns an integer representing the server version. | |
connection & | setdb (const char *pgHost=nullptr, const char *pgPort=nullptr, const char *pgOptions=nullptr, const char *pgTTY=nullptr, const char *dbName=nullptr) |
Connect to a database server. This is the same as setdbLogin except that the username and password are each set to nullptr . | |
connection & | setdbLogin (const char *pgHost=nullptr, const char *pgPort=nullptr, const char *pgOptions=nullptr, const char *pgTTY=nullptr, const char *dbName=nullptr, const char *login=nullptr, const char *pwd=nullptr) |
Connect to a database server. This is the predecessor of connectdb with a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. Provide nullptr or an empty string for any one of these fixed parameters that is to be defaulted. | |
int | socket () noexcept |
Obtains the file descriptor number of the connection socket to the server. A valid descriptor will be greater than or equal to 0; a result of -1 indicates that no server connection is currently open. (This will not change during normal operation, but could change during connection setup or reset.) | |
const char * | sslAttribute (const char *attribute_name) noexcept |
Returns SSL-related information about the underlying connection. The list of available attributes varies depending on the SSL library being used and the type of connection. | |
const char *const * | sslAttributeNames () noexcept |
Returns an array of SSL attribute names available. | |
bool | sslInUse () noexcept |
Indicates whether the connection is using SSL. | |
void * | sslStruct (const char *struct_name) noexcept |
Returns a pointer to an SSL-implementation-specific object describing the connection. | |
ConnStatusType | status () noexcept |
Returns the status of the connection. | |
PGTransactionStatusType | transactionStatus () noexcept |
Returns the current in-transaction status of the server. | |
char * | tty () noexcept |
This method no longer does anything, but it remains for backwards compatibility. | |
char * | user () noexcept |
Returns the user name of the connection. | |
Static Public Member Functions | |
static const long | _hash64 (const char *str) |
Generate a 64-bit hash of an ASCIIZ string using the high-performance xxHash library. | |
static const char * | _hash64z (const char *str, char *hash=nullptr) |
Generate a 64-bit hash of a string using the high-performance xxHash library. The target char[] array will contain the hexadecimal representation of the resulting 64-bit hash value (a total of 17 bytes, including the termianting NULL character). | |
static PQconninfoOption * | conndefaults (void) |
Returns the global default connection options. | |
static PQconninfoOption * | conninfoParse (const char *conninfo, char **errmsg=nullptr) noexcept |
Returns parsed connection options from the provided connection string. | |
static unsigned char * | escapeBytea (const unsigned char *from, const size_t from_length, size_t *to_length) noexcept |
This escapeBytea method is an older, deprecated version of the escapeByteaConn method. It is retained for backward compatibility. | |
static size_t | escapeString (char *to, const char *from, const size_t length) noexcept |
This escapeString method is an older, deprecated version of the escapeStringConn method. It is retained for backward compatibility. | |
static void | freemem (void *ptr) noexcept |
Free memory that was allocated by a method that indicates that the return value requires it. | |
static bool | isthreadsafe () noexcept |
Returns the thread safety status of the libpq library. | |
static PGPing | ping (const char *conninfo) noexcept |
This method reports the status of the server, although not quite the same way as the traditional UNIX/Linux "ping" (Packet INternet Groper) shell command does. Although it accepts connection parameters identical to those of the connectdb method, 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. | |
static PGPing | pingParams (const char *const *keywords, const char *const *values, const bool expand_dbname) noexcept |
This method reports the status of the server, although not quite the same way as the traditional UNIX/Linux "ping" (Packet INternet Groper) shell command does. Although it accepts connection parameters identical to those of the connectdbParams method, 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. | |
static unsigned char * | unescapeBytea (const unsigned char *from, size_t *to_length) |
Converts a string representation of binary data into binary data, which is the reverse of escapeBytea. This is needed when retrieving bytea data in text format (but not when retrieving it in binary format). | |
The pq namespace is an object-oriented interface version of the PostgreSQL C library API, but with resources freed automatically in the destructor (in accordance with RAII principles), errors thrown as exceptions, etc.
Aside from the object-oriented benefits provided by C++, the intention is to be consistent with the PostgreSQL C library API as much as possible, which is important because this makes it easier for developers to transition C code to C++ (and vice-versa).
If you're needing a more in-depth object-oriented implementation of the PostgreSQL API, then I highly recommend libpqxx
which offers an excellent feature-rich API, and the author actively supports it:
The C++ connector for PostgreSQL
https://www.pqxx.org/libpqxx/
Writing a lot of code that checks error status after each API function call and having to track resources (so they can be freed accordingly later on), despite being quite important, is a lot of work. By utilizing exceptions and RAII priniciples, coding becomes a lot less tedious and, consequently, also less likey to have errors because C++ developers will have more time to focus on other aspects of their programming tasks.
I created this class to make it easier to make server daemons that utilize PostgreSQL databases.
An ASCIIZ string is a C-string (char* array) that includes a terminating null (0) character at the end.
I use the term "ASCIIZ string" to indicate an array of characters that's terminated by a 0 (a.k.a., null). Although this is very much the same as a C-string, the difference is that in many API functions a C-string must often be accompanied by its length value. When referring to an ASCIIZ string, I'm intentionally indicating that the length of the string is not needed because the string is null-terminated. (This term was also commonly used in assembly language programming in the 1970s, 1980s, and 1990s, and as far as I know is still used by machine language programmers today.)
Parameter stacking is also supported (with methods that return connection&
).
|
inlinenoexcept |
Default constructor. This does not connect to a PostgreSQL database (see the connectdb and connectdbParams methods).
|
inlinenoexcept |
Constructor that uses an existing PGconn handle. If the handle has not yet been connected to a PostgreSQL database, then it will need to be (see the connectdb and connectdbParams methods).
conn | PostgreSQL connection handle |
|
inlinenoexcept |
Destructor, which automatically performs the following actions once the instantiated object of this class goes out of scope:
|
inlinenoexcept |
Obtain the underlying PostgreSQL database connection handle.
This is primarily needed for utilizing functionality from the PostgreSQL C programming API directly.
PGconn
handle automatically (unldess the handover
flag is set). handover | Whether to prevent destructor invalidation of the underlying handle TRUE = prevent destructor invalidation FALSE = don't prevent destructor invalidation (default) |
|
inlinestatic |
Generate a 64-bit hash of an ASCIIZ string using the high-performance xxHash library.
This is provided as a convenience for developers who need thread safety when manually generating names for their prepared statements.
This method uses the xxHash library, which provides the fastest-performing hash available according to public benchmarks as of 2025-Mar-11 (the time of this writing).
str | Pointer to source ASCIIZ string to use when generating the hash |
|
inlinestatic |
Generate a 64-bit hash of a string using the high-performance xxHash library. The target char[] array will contain the hexadecimal representation of the resulting 64-bit hash value (a total of 17 bytes, including the termianting NULL character).
This is primarily used internally to generate unique names for use with prepared SQL statements (when a prepared-statement name wasn't provided), which a 64-bit hash is expected to be more than adequate for.
strdup
or assigning it to an std::string
object). This method uses the xxHash library, which provides the fastest-performing hash available according to public benchmarks as of 2025-Mar-11 (the time of this writing).
str | Pointer to source ASCIIZ string to use when generating the hash |
hash | Pointer to char[17] array for storing the 17-byte hexadecimal rendition of the resulting hash value as an ASCIIZ stringnullptr = allocate a 17-byte portion of memory using malloc (which will need to be freed after it's no longer needed) |
|
inlinenoexcept |
Obtain OID from cached pg_type
table. The pg_type
cache must first be initialized (see the cache_pg_types
flag in any of the connectdb and connectdbParams methods).
The following conditions return zero:
typname
parameter is nullptr
datatype
parameter value was specifiedThis method is optimized to lookup the type quickly by repeatedly reducing the index pointer in half until a match is found. This reduces the total number of comparisons needed down to approximately 2%, which means that less CPU cycles are needed to find and return the OID
or typelen
value, compared to utilizing a sequential scan.
OID
or typelen
value. typname | The typname string |
datatype | Type's informational data to return (an incorrect value here will yield a return value of 0): 0 = datatype's OID 1 = datatype's length ( typelen ) |
|
inlineLIBPQ |
Returns the Process ID (PID) of the backend process handling this connection.
The backend PID is useful for debugging purposes and for comparison to NOTIFY messages (which include the PID of the notifying backend process).
pq_connection_error | If there's no open connection to a PostgreSQL server |
|
inlinestaticLIBPQ |
Returns the global default connection options.
The "connection options" array that is returned can be used to determine all possible connectdb and connectStart options, and their current default values. The return value points to an array of conninfoOption
structures, which ends with an entry having a nulllptr
keyword pointer.
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 the conninfoFree method to prevent a small amount of memory from being leaked with each call to this conndefaults method.
PQconninfoOption
structure
|
inlineLIBPQ |
Connect to a database.
pq_connection_error | If the connection failed for any number of reasons |
pq_command_error | If cache_pg_types is non-zero and a problem is encountered with the pg_type system table |
connection
object so as to facilitate stacking connection_string | Connection stringempty-string = defer to system default |
cache_pg_types | Cache pg_type table for use with named types (usually only needed with advanced placeholders) 0 = don't set up a cache of the pg_type table1 = set up a class-wide cache of the pg_type table set up a local cache of the pg_type table (for this object only, which is useful for connecting to a different PostgreSQL server that that has a different set of pg_type values) (All other values are reserved for future use, and have the same effect as the number 0) |
|
inline |
Connect to a database.
pq_connection_error | If the connection failed for any number of reasons |
pq_command_error | If cache_pg_types is non-zero and a problem is encountered with the pg_type system table |
connection
object so as to facilitate stacking connection_string | Connection string |
cache_pg_types | Cache pg_type table for use with named types (usually only needed with advanced placeholders) 0 = don't set up a cache of the pg_type table1 = set up a class-wide cache of the pg_type table set up a local cache of the pg_type table (for this object only, which is useful for connecting to a different PostgreSQL server that that has a different set of pg_type values) (All other values are reserved for future use, and have the same effect as the number 0) |
|
inlineLIBPQ |
Connect to a database.
Certain versions of the GNU C++ compiler fail to compile with this error due to the inclusion of the std::initializer_list
headers (clang++ does not fail to compile with either coding style):
However, one of the following warnings may also be emitted when using the -pedantic
compiler option:
compound literals are a C99-specific feature
ISO C++ forbids compound-literals
The solution for both of the above is to declare k_tmp
and v_tmp
outside of the method call parameters, which may make it easier to support user-configurable database connection values:
pq_connection_error | If the connection failed for any number of reasons |
pq_command_error | If cache_pg_types is non-zero and a problem is encountered with the pg_type system table |
connection
object so as to facilitate stacking keywords | Connection keywords arary |
values | Connection values arary |
expand_dbname | Whether to interpret the value associated with the first keyword "dbname" as a connection stringTRUE = yes (like non-zero in the PostgreSQL C programming API) FALSE = no (like zero in the PostgreSQL C programming API) |
cache_pg_types | Cache pg_type table for use with named types (usually only needed with advanced placeholders) 0 = don't set up a cache of the pg_type table1 = set up a class-wide cache of the pg_type table set up a local cache of the pg_type table (for this object only, which is useful for connecting to a different PostgreSQL server that that has a different set of pg_type values) (All other values are reserved for future use, and have the same effect as the number 0) |
|
inline |
Connect to a database.
pq_connection_error | If the connection failed for any number of reasons |
pq_command_error | If cache_pg_types is non-zero and a problem is encountered with the pg_type system table |
connection
object so as to facilitate stacking keywords | Connection keywords arary |
values | Connection values arary |
expand_dbname | Whether to interpret the value associated with the first keyword "dbname" as a connection stringTRUE = yes (like non-zero in the PostgreSQL C programming API) FALSE = no (like zero in the PostgreSQL C programming API) |
cache_pg_types | Cache pg_type table for use with named types (usually only needed with advanced placeholders) 0 = don't set up a cache of the pg_type table1 = set up a class-wide cache of the pg_type table set up a local cache of the pg_type table (for this object only, which is useful for connecting to a different PostgreSQL server that that has a different set of pg_type values) (All other values are reserved for future use, and have the same effect as the number 0) |
|
inlinenoexceptLIBPQ |
Indicates whether the connection authentication method required a password, but none was available.
TRUE
= password needed, and not availableFALSE
= password was provided, and was available
|
inlinenoexceptLIBPQ |
Indicates whether the connection authentication method used a password.
TRUE
= password was usedFALSE
= password was not used
|
inlineLIBPQ |
Poll an ongoing attempt to connect to a database in a non-blocking fashion.
hostaddr
parameter must be used appropriately to prevent DNS queries. See the documentation of this parameter in Section 34.1.2 of the official PostgreSQL documentation for details.To begin a nonblocking connection request, call the connectStart or connectStartParams method. Then, poll libpq
by calling the connectPoll method so that it can proceed with the connection sequence. Use the socket method to obtain the descriptor of the socket underlying the database connection (caution: do not assume that the socket remains the same across connectPoll calls.) Loop thus: If connectPoll last returned PGRES_POLLING_READING
, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then, call connectPoll again. Conversely, if connectPoll last returned PGRES_POLLING_WRITING
, wait until the socket is ready to write, then call connectPoll again. On the first iteration (e.g., if you have yet to call connectPoll), behave as if it last returned PGRES_POLLING_WRITING
. Continue this loop until connectPoll 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 status. If this call returns CONNECTION_BAD
, then it means that the connection procedure failed; if the call returns CONNECTION_OK
, then it means that the connection is ready. Both of these states are equally detectable from the return value of connectPoll as well, 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, for example, be useful for providing helpful feedback to the user. These statuses are:
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_CHECK_WRITABLE
CONNECTION_CONSUME
Note that, although these constants will remain (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 by connectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, connectStart followed by a connectPoll loop is equivalent to connectdb.
pq_command_error | If cache_pg_types is non-zero and a problem is encountered with the pg_type system table |
cache_pg_types | Cache pg_type table for use with named types (usually only needed with advanced placeholders) 0 = don't set up a cache of the pg_type table1 = set up a class-wide cache of the pg_type table set up a local cache of the pg_type table (for this object only, which is useful for connecting to a different PostgreSQL server that that has a different set of pg_type values) (All other values are reserved for future use, and have the same effect as the number 0) |
|
inlineLIBPQ |
Connect to a database in a non-blocking fashion.
hostaddr
parameter must be used appropriately to prevent DNS queries. See the documentation of this parameter in Section 34.1.2 of the official PostgreSQL documentation for details.To begin a nonblocking connection request, call the connectStart or connectStartParams method. Then, poll libpq
by calling the connectPoll method so that it can proceed with the connection sequence. Use the socket method to obtain the descriptor of the socket underlying the database connection (caution: do not assume that the socket remains the same across connectPoll calls.) Loop thus: If connectPoll last returned PGRES_POLLING_READING
, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then, call connectPoll again. Conversely, if connectPoll last returned PGRES_POLLING_WRITING
, wait until the socket is ready to write, then call connectPoll again. On the first iteration (e.g., if you have yet to call connectPoll), behave as if it last returned PGRES_POLLING_WRITING
. Continue this loop until connectPoll 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 status. If this call returns CONNECTION_BAD
, then it means that the connection procedure failed; if the call returns CONNECTION_OK
, then it means that the connection is ready. Both of these states are equally detectable from the return value of connectPoll as well, 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, for example, be useful for providing helpful feedback to the user. These statuses are:
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_CHECK_WRITABLE
CONNECTION_CONSUME
Note that, although these constants will remain (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 by connectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, connectStart followed by a connectPoll loop is equivalent to connectdb.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking connection_string | Connection stringempty-string = defer to system default |
|
inline |
Connect to a database in a non-blocking fashion.
hostaddr
parameter must be used appropriately to prevent DNS queries. See the documentation of this parameter in Section 34.1.2 of the official PostgreSQL documentation for details.To begin a nonblocking connection request, call the connectStart or connectStartParams method. Then, poll libpq
by calling the connectPoll method so that it can proceed with the connection sequence. Use the socket method to obtain the descriptor of the socket underlying the database connection (caution: do not assume that the socket remains the same across connectPoll calls.) Loop thus: If connectPoll last returned PGRES_POLLING_READING
, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then, call connectPoll again. Conversely, if connectPoll last returned PGRES_POLLING_WRITING
, wait until the socket is ready to write, then call connectPoll again. On the first iteration (e.g., if you have yet to call connectPoll), behave as if it last returned PGRES_POLLING_WRITING
. Continue this loop until connectPoll 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 status. If this call returns CONNECTION_BAD
, then it means that the connection procedure failed; if the call returns CONNECTION_OK
, then it means that the connection is ready. Both of these states are equally detectable from the return value of connectPoll as well, 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, for example, be useful for providing helpful feedback to the user. These statuses are:
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_CHECK_WRITABLE
CONNECTION_CONSUME
Note that, although these constants will remain (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 by connectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, connectStart followed by a connectPoll loop is equivalent to connectdb.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking connection_string | Connection string |
|
inlineLIBPQ |
Connect to a database in a non-blocking fashion.
Certain versions of the GNU C++ compiler fail to compile with this error due to the inclusion of the std::initializer_list
headers (clang++ does not fail to compile with either coding style):
However, one of the following warnings may also be emitted when using the -pedantic
compiler option:
compound literals are a C99-specific feature
ISO C++ forbids compound-literals
The solution for both of the above is to declare k_tmp
and v_tmp
outside of the method call parameters, which may make it easier to support user-configurable database connection values:
The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:
hostaddr
parameter must be used appropriately to prevent DNS queries. See the documentation of this parameter in Section 34.1.2 of the official PostgreSQL documentation for details.To begin a nonblocking connection request, call the connectStart or connectStartParams method. Then, poll libpq
by calling the connectPoll method so that it can proceed with the connection sequence. Use the socket method to obtain the descriptor of the socket underlying the database connection (caution: do not assume that the socket remains the same across connectPoll calls.) Loop thus: If connectPoll last returned PGRES_POLLING_READING
, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then, call connectPoll again. Conversely, if connectPoll last returned PGRES_POLLING_WRITING
, wait until the socket is ready to write, then call connectPoll again. On the first iteration (e.g., if you have yet to call connectPoll), behave as if it last returned PGRES_POLLING_WRITING
. Continue this loop until connectPoll 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 status. If this call returns CONNECTION_BAD
, then it means that the connection procedure failed; if the call returns CONNECTION_OK
, then it means that the connection is ready. Both of these states are equally detectable from the return value of connectPoll as well, 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, for example, be useful for providing helpful feedback to the user. These statuses are:
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_CHECK_WRITABLE
CONNECTION_CONSUME
Note that, although these constants will remain (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 by connectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, connectStart followed by a connectPoll loop is equivalent to connectdb.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking keywords | Connection keywords arary |
values | Connection values arary |
expand_dbname | Whether to interpret the value associated with the first keyword "dbname" as a connection stringTRUE = yes (like non-zero in the PostgreSQL C programming API) FALSE = no (like zero in the PostgreSQL C programming API) |
|
inline |
Connect to a database in a non-blocking fashion.
hostaddr
parameter must be used appropriately to prevent DNS queries. See the documentation of this parameter in Section 34.1.2 of the official PostgreSQL documentation for details.To begin a nonblocking connection request, call the connectStart or connectStartParams method. Then, poll libpq
by calling the connectPoll method so that it can proceed with the connection sequence. Use the socket method to obtain the descriptor of the socket underlying the database connection (caution: do not assume that the socket remains the same across connectPoll calls.) Loop thus: If connectPoll last returned PGRES_POLLING_READING
, wait until the socket is ready to read (as indicated by select()
, poll()
, or similar system function). Then, call connectPoll again. Conversely, if connectPoll last returned PGRES_POLLING_WRITING
, wait until the socket is ready to write, then call connectPoll again. On the first iteration (e.g., if you have yet to call connectPoll), behave as if it last returned PGRES_POLLING_WRITING
. Continue this loop until connectPoll 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 status. If this call returns CONNECTION_BAD
, then it means that the connection procedure failed; if the call returns CONNECTION_OK
, then it means that the connection is ready. Both of these states are equally detectable from the return value of connectPoll as well, 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, for example, be useful for providing helpful feedback to the user. These statuses are:
CONNECTION_STARTED
CONNECTION_MADE
CONNECTION_AWAITING_RESPONSE
CONNECTION_AUTH_OK
CONNECTION_SSL_STARTUP
CONNECTION_SETENV
CONNECTION_CHECK_WRITABLE
CONNECTION_CONSUME
Note that, although these constants will remain (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 by connectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, connectStart followed by a connectPoll loop is equivalent to connectdb.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking keywords | Connection keywords arary |
values | Connection values arary |
expand_dbname | Whether to interpret the value associated with the first keyword "dbname" as a connection stringTRUE = yes (like non-zero in the PostgreSQL C programming API) FALSE = no (like zero in the PostgreSQL C programming API) |
|
inlinenoexceptLIBPQ |
Returns the connection options used by a live connection.
The "connection options" array that is returned can be used to determine all possible connectdb and connectStart options, and their current default values. The return value points to an array of conninfoOption
structures, which ends with an entry having a nulllptr
keyword pointer.
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 the conninfoFree method to prevent a small amount of memory from being leaked with each call to this conndefaults method.
PQconninfoOption
structure
|
inlinestaticnoexceptLIBPQ |
Returns parsed connection options from the provided connection string.
After parsing the provided connection string, the resulting options are returned as an array. This function can be used to extract the connectdb or connectStart options in the provided connection string. The return value points to an array of conninfoOption structures, which ends with an entry with a nullptr
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 nullptr
(default values are not inserted).
If the errmsg parameter is not nullptr
, then *errmsg
is set to nullptr
on success, else to a malloc'd error string explaining the problem. (It is also possible for *errmsg
to be set to nullptr
and function to return nullptr
, which indicates an out-of-memory condition.)
After processing the options array, free it by passing it to the conninfoFree
method. If this is not done, some memory is leaked for each call to this conninfoParse method. Conversely, if an error occurs and errmsg
is not nullptr
, be sure to free the error string using the freemem method to prevent small amounts of memory from being leaked.
PQconninfoOption
structure conninfo | Connection string to parse |
errmsg | Where to store the array of error messagesnullptr = don't allocate any memory for error messages |
|
inlinenoexceptLIBPQ |
Returns the database name of the connection.
|
inlinenoexceptLIBPQ |
Returns the error message most recently generated by an operation on the underlying connection.
In addition to throwing an exception, nearly all methods will set a message for this errorMessage method if they fail. Note that by libpq
convention, a non-empty errorMessage result can consist of multi-line string, and will include a trailing newline character. The caller should not free the result directly because it will be freed when the underlying connection handle is freed automatically by this class's destructor. The result string should also not be expected to persist consistently following additional commands, queries, and other operations.
|
inlinestaticnoexceptLIBPQ |
This escapeBytea
method is an older, deprecated version of the escapeByteaConn method. It is retained for backward compatibility.
The only difference from the escapeByteaConn method is that the escapeBytea method does not take any PGconn
or error parameters, and so it cannot adjust its behavior depending on the connection properties (such as character encoding) and therefore it might provide the wrong results. Also, it has no way to report error conditions.
escapeBytea
method can be used safely in client programs that work with only one PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections (e.g., use the escapeByteaConn method in such cases). from | String to convert from |
from_length | Length of from string |
to_length | Length of string whose pointer will be returned |
|
inlineLIBPQ |
Escapes binary data for use within an SQL command with the bytea
data type. As with the escapeStringConn method, this is only used when inserting data directly into an SQL command string.
Certain byte values must be escaped when used as part of a bytea
literal in an SQL statement. The escapeByteaConn method escapes bytes using either hex encoding or backslash escaping. See Section 8.4 of the official PostgreSQL documentation for more information.
The from
parameter points to the first byte of the string that is to be escaped, and the from_length
parameter provides the number of bytes in this binary string. (A terminating zero byte is neither necessary nor counted.)
The to_length
parameter points to a variable that will hold the resultant escaped string length. This result string length includes the terminating zero byte of the result.
escapeByteaConn
method returns an escaped version of the from
parameter binary string in memory allocated with ::malloc()
. This memory must be freed using the freemem() method after the result is no longer needed.The return string has all special characters replaced so that they can be properly processed by the PostgreSQL string literal parser and the bytea
input function. A terminating zero byte is also added. The apostrophes that must surround PostgreSQL string literals are not part of the result string.
pq::pq_error | If insufficient memory |
to
parameter from | String to convert from |
from_length | Length of from string |
to_length | Length of string whose pointer will be returned |
|
inlineLIBPQ |
Escape a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved.
length
parameter. (If a terminating zero byte is found before length
bytes are processed, this method stops at the zero; this behavior is thus rather like that of strncpy
.) std::invalid_argument | If there's a formatting problem |
str
parameter (see Postcondition
important notes about memory management) str | String to process |
length | Length of string |
|
inlineLIBPQ |
Escape a string for use within an SQL command. This is useful when inserting data values as literal constants in SQL commands. Certain characters (such as quotes and backslashes) must be escaped to prevent them from being interpreted specially by the SQL parser; this method performs this operation.
length
parameter. (If a terminating zero byte is found before length
bytes are processed, this method stops at the zero; this behavior is thus rather like that of strncpy
.) std::invalid_argument | If there's a formatting problem |
str
parameter (see Postcondition
important notes about memory management) str | String to process |
length | Length of string |
|
inlinestaticnoexceptLIBPQ |
This escapeString
method is an older, deprecated version of the escapeStringConn method. It is retained for backward compatibility.
The only difference from the escapeStringConn method is that the escapeString method does not take any PGconn
or error parameters, and so it cannot adjust its behavior depending on the connection properties (such as character encoding) and therefore it might provide the wrong results. Also, it has no way to report error conditions.
escapeString
method can be used safely in client programs that work with only one PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). In other contexts it is a security hazard and should be avoided in favor of the escapeStringConn method. to
parameter to | Array to save to |
from | String to convert from |
length | Length of string |
|
inlineLIBPQ |
The escapeStringConn
method escapes string literals, much like the escapeLiteral method does. However, unlike the escapeLiteral method, the caller is responsible for providing an appropriately sized to
buffer beforehand. Furthermore, this escapeStringConn
method does not generate the apostrophes that must surround PostgreSQL string literals; they should be provided in the SQL command that the result is inserted into.
The from
parameter points to the first character of the string that is to be escaped, and the length
parameter specifies the number of bytes in this string. A terminating zero byte is not required, and should not be counted in the length
. (If a terminating zero byte is found before length
bytes are processed, this escapeStringConn
method stops at the zero; the behavior is thus rather like strncpy
.)
The to
parameter shall point to a buffer that is sufficiently-sized to hold at least one more byte than twice the value of length
, otherwise the behavior is undefined. Behavior is likewise also undefined if the to
and from
strings overlap.
If the error parameter is not nullptr
, then *error
is set to zero on success, nonzero on error. Presently the only possible error conditions involve invalid multibyte encoding in the source string – the output string is still generated on error, but it can be expected that the server will reject it as malformed. On error, an exception is thrown in addition to a suitable message being stored in the conn object, regardless of whether the error
parameter is set to nullptr
.
PQescapeStringConn returns the number of bytes written to to
, not including the terminating zero byte.
std::invalid_argument | If there's a formatting problem |
to
parameter to | Array to save to |
from | String to convert from |
length | Length of string |
error | Pointer to where to store error codenullptr = don't store error code (an exception will still be thrown if an error is encountered) |
|
inlineLIBPQ |
Submit a command/query to the server and wait for the result.
pq_command_error | If the command failed for any number of reasons |
connection
object so as to facilitate stacking query_string | Query string |
|
inlineLIBPQ |
Submit a command/query to the server and wait for the result.
pq_command_error | If the command failed for any number of reasons |
connection
object so as to facilitate stacking query_string | Query string |
|
inlineLIBPQ |
Submit a command/query to the server and wait for the result, with the ability to pass parameters separately from the SQL command text.
pq_command_error | If the command failed for any number of reasons |
query_string | Query string |
nParams | Number of parameters |
paramTypes | Data types, by OIDnullptr = server infers data types automatically |
paramValues | Values of the parameters to use in the query; any values in the array that are set to nullptr will be interpreted by the server as NULL |
paramLengths | Lengths of binary-format parameter values (ignored for values that are text-format or nullptr ) |
paramFormats | Indicates whether parameter values are text (FALSE ) or binary (TRUE ), or if this parameter is nullptr then all parameter values are presumed to be text strings |
resultFormat | Whether to obtain results in text format (0 ) or binary (1 ) |
|
inlineLIBPQ |
Submit a command/query to the server and wait for the result, with the ability to pass parameters separately from the SQL command text.
nParams
was removed (this is obtained from the std::vector
class, with the paramValues
parameter)paramTypes
was moved to the very end because it's rarely neededresultFormat
was moved to the position after paramValues
because it's convenientpq_command_error | If the command failed for any number of reasons |
result
object query_string | Query string |
paramValues | Values of the parameters to use in the query; any values in the array that are set to nullptr will be interpreted by the server as NULL |
resultFormat | Whether to obtain results in text format (0 ) or binary (1 ) |
paramLengths | Lengths of binary-format parameter values (ignored for values that are text-format or nullptr ) |
paramFormats | Indicates whether parameter values are text (FALSE ) or binary (TRUE ), or if this parameter is nullptr then all parameter values are presumed to be text strings |
paramTypes | Data types, by OIDnullptr = server infers data types automatically |
|
inlineLIBPQ |
Closes the connection to the server. Also frees memory used by the underlying conn
object.
The destructor calls this method automatically after this object goes out of scope, so it's not necessary to use this method (unlike in C, which doesn't have support for destructors in the way C++ does).
connection
object so as to facilitate stacking
|
inlinestaticnoexceptLIBPQ |
Free memory that was allocated by a method that indicates that the return value requires it.
This method frees memory allocated by libpq
functions, particularly the escapeByteaConn, escapeBytea, unescapeBytea, and notifies methods (there may be others as well).
::free()
, be used on Microsoft Windows, because allocating memory in a DLL and releasing it in the application works only if multithreaded/single-threaded, release/debug, and static/dynamic flags are the same for the DLL and the application. On non-Microsoft Windows platforms, however, this function is the same as the standard ::free()
library function. ptr | Pointer to memory that was allocated by libpq@n nullptr is ignored |
|
inlinenoexceptLIBPQ |
Returns the SSL structure used in the connection.
sslStruct("OpenSSL")
, and should not be used in newer applications because the returned struct
is specific to OpenSSL which might not be available if a different SSL implementation is used. To check whether a connection uses SSL, see sslInUse instead; and for more details about the connection, use the sslAttribute method. nullptr
when the connection does not use SSL or the requested type of object is not available from the SSL implementation
|
inlineLIBPQ |
Returns the hostname of the active connection. This can be a hostname, an IP address, or a directory path (if the connection is via Unix socket; in which case the path can be distinguished because it will always be an absolute path, beginning with /
.)
If the connection parameters specified both host
and hostaddr
, then the host
information. If only hostaddr
was specified, then that is what is returned. If multiple hosts were specified in the connection parameters, this method will return the host actually connected to.
If multiple hosts were specified in the connection parameters, it is not possible to rely on the result of this method until after the connection is established. The status of the connection can be checked using the status method.
pq_connection_error | If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error); or if the database isn't connected status method. |
|
inlineLIBPQ |
Returns the server IP address of the active connection. This can be the address that a hostname resolved to, or an IP address provided through the hostaddr
connection parameter.
pq_connection_error | If there is an error producing the hostaddr information (perhaps if the connection has not been fully established or there was an error); or if the database isn't connected status method. |
|
inlinestaticnoexceptLIBPQ |
Returns the thread safety status of the libpq library.
PGresult
objects are normally read-only after creation, and so can be passed around freely between threads. However, if you use any of the PGresult
-modifying functions that are described in the official PostgreSQL documentation, it's up to you to avoid concurrent operations on the same PGresult
, too. TRUE
= the underlying libpq
library is threadsafeFALSE
= the underlying libpq
library is not threadsafe
|
inlinenoexceptLIBPQ |
Returns the command-line options passed in the connection request.
|
inlineLIBPQ |
Returns the status of the connection.
Certain parameter values are reported by the server automatically at connection startup or whenever their values change. The parameterStatus method can be used to interrogate these settings.
pq_connection_error | If the value of the specified parameter is not known |
paramName | Parameter name to interrogate |
|
inlinenoexceptLIBPQ |
Returns the password of the connection.
This method will return either the password specified in the connection parameters, or if there was none and the password was obtained from the password file, it will return that. In the latter case, if multiple hosts were specified in the connection parameters, it is not possible to rely on the result of this method until after the connection is established. The status of the connection can be checked using the status method.
|
inlinestaticnoexceptLIBPQ |
This method reports the status of the server, although not quite the same way as the traditional UNIX/Linux "ping" (Packet INternet Groper) shell command does. Although it accepts connection parameters identical to those of the connectdb method, 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
PQPING_REJECT
PQPING_NO_RESPONSE
PQPING_NO_ATTEMPT
conninfo | Connection string |
|
inlinestaticnoexceptLIBPQ |
This method reports the status of the server, although not quite the same way as the traditional UNIX/Linux "ping" (Packet INternet Groper) shell command does. Although it accepts connection parameters identical to those of the connectdbParams method, 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
PQPING_REJECT
PQPING_NO_RESPONSE
PQPING_NO_ATTEMPT
keywords | Connection keywords arary |
values | Connection values arary |
expand_dbname | Whether to interpret the value associated with the first keyword "dbname" as a connection stringTRUE = yes (like non-zero in the PostgreSQL C programming API) FALSE = no (like zero in the PostgreSQL C programming API) |
|
inlineLIBPQ |
Returns the TCP port number of the active connection.
If multiple ports were specified in the connection parameters, this method returns the port actually connected to.
If multiple ports were specified in the connection parameters, it is not possible to rely on the result of this method until the connection is established. The status of the connection can be checked using the
pq_connection_error | If there is an error producing the port information (perhaps if the connection has not been fully established or there was an error); or if the database isn't connected status method. |
|
inlineLIBPQ |
Submits a request to create a prepared statement with the given parameters, and waits for completion.
This prepare method creates a prepared statement for later execution with the execPrepared method. This feature makes it possible for commands to be executed repeatedly without repeating the parsing and planning functions each time; see the PREPARE
command in the official PostgreSQL documentation for details.
This method creates a prepared statement named stmtName
from the query string, which must contain a single SQL command. The stmtName
can point to an empty string (""
) to create an unnamed statement, in which case any
pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1
, $2
, etc.
The nParams
value is the number of parameters for which types are pre-specified in the paramTypes
[] array. (The array pointer can be set to nullptr
when nParams
is zero.) The paramTypes
[] array specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes
is nullptr
, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string. Also, the query can use parameter symbols with numbers higher than nParams
; data types will be inferred for these symbols as well. (See describePrepared for a means to find out what data types were inferred.)
As with exec, the result is normally a result object whose contents indicate server-side success, otherwise an exception is thrown if this command failed. You can use errorMessage to get more information about any errors.
Prepared statements for use with execPrepared can also be created by executing SQL PREPARE
statements. Also, although there is no libpq
function for deleting a prepared statement, the SQL DEALLOCATE
statement can be used for that purpose.
pq_command_error | If the command failed for any number of reasons |
stmtName | Statement name |
query | Query string |
nParams | Number of parameters |
paramTypes | Data types, by OIDnullptr = server infers data types automatically |
|
inlineLIBPQ |
Sends a request to execute a prepared statement with given parameters, and waits for the result.
This execPrepared method is like the execParams method, but the command to be executed is specified by naming a previously-prepared statement instead of providing a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session.
The parameters are identical to that of the execParams method, except that the name of a prepared statement is given instead of a query string, and the paramTypes
[] parameter is not present (it is not needed since the prepared statement's parameter types were determined when it was created).
pq_command_error | If the command failed for any number of reasons |
stmtName | Statement name |
nParams | Number of parameters |
paramValues | Values of the parameters to use in the query; any values in the array that are set to nullptr will be interpreted by the server as NULL |
paramLengths | Lengths of binary-format parameter values (ignored for values that are text-format or nullptr ) |
paramFormats | Indicates whether parameter values are text (FALSE ) or binary (TRUE ), or if this parameter is nullptr then all parameter values are presumed to be text strings |
resultFormat | Whether to obtain results in text format (0 ) or binary (1 ) |
|
inlineLIBPQ |
Obtains information about a previously created portal.
The portalName
parameter can be ""
or nullptr
to reference the unnamed portal, otherwise it must be the name of an existing portal. On success, a result object with status PGRES_COMMAND_OK
is returned, otherwise an exception is thrown.
The result::nparams and result::paramtype methods can be used with the returned result object to obtain information about the parameters of the prepared statement, and the result::nfields, result::fname, result::ftype, etc., provide further information about the result columns (if any) of the portal.
pq_command_error | If the portal name is invalid |
pq_connection_error | If the connection is bad |
portalName | Portal name |
|
inlineLIBPQ |
Obtain information about the specified - by name - prepared statement.
The describePrepared method makes it possible for an application to obtain information about a previously prepared statement.
The stmtName
parameter can be ""
or nullptr
to reference the unnamed statement, otherwise it must be the name of an existing prepared statement. On success, a result with status PGRES_COMMAND_OK is returned, otherwise an exception is thrown (which indicates failure).
The result::nparams and result::paramtype methods can be used with the returned result object to obtain information about the parameters of the prepared statement, and the result::nfields, result::fname, result::ftype, etc., provide further information about the result columns (if any) of the statement.
pq_connection_error | If the connection is bad |
stmtName | Statement name |
|
inlineLIBPQ |
Interrogates the frontend/backend protocol being used.
Applications might wish to use this function to determine whether certain features are supported. Currently, the possible value us 3 (3.0 protocol), although more values may be possible when connecting to newer versions of PostgreSQL servers in the future.
The protocol version will not change after connection startup is complete, but it could theoretically change during a connection reset. The version 3.0 protocol is supported by PostgreSQL server versions 7.4 and newer.
pq_connection_error | If the connection is bad |
|
inlineLIBPQ |
Re-connect to the database, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking
|
inlineLIBPQ |
Re-connect to the database in a non-blocking fashion, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods.
These methods 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.
This method suffers from the same restrictions as connectPoll.
To initiate a connection reset, call this resetStart method. If it succeeds, poll the reset using PQresetPoll in exactly the same way as you would create the connection using PQconnectPoll.
pq_connection_error | If the connection failed for any number of reasons |
|
inlineLIBPQ |
Re-connect to the database in a non-blocking fashion, re-using the same credentials that were originally provided to one of the connectdb, connectdbParams, connectStart, or connectStartParams methods.
These methods 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.
This method suffers from the same restrictions as connectPoll.
To initiate a connection reset, call this resetStart method. If it succeeds, poll the reset using PQresetPoll in exactly the same way as you would create the connection using PQconnectPoll.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking
|
inlineLIBPQ |
Returns an integer representing the server version.
Applications might use this function to determine the version of the database server they are connected to. The result is formed by multiplying the server's major version number by 10000
and adding the minor version number (for example, version 10.1 will be returned as #c 100001, and version 11.0 will be returned as 110000
).
90105
, and version 9.2.10 will be returned as 90210
. 100
, not 10000
, to determine a logical major version number. In all release series, only the last two digits differ between minor releases (e.g., bug-fix releases). pq_connection_error | If the connection is bad |
|
inlineLIBPQ |
Connect to a database server. This is the same as setdbLogin except that the username and password are each set to nullptr
.
It method is provided for backward compatibility with very old programs.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking pgHost | Hostname of PostgreSQL server (default is local UNIX socket or localhost) |
pgPort | TCP port number to use (default is 3456) |
pgOptions | PostgreSQL options |
pgTTY | This TTY parameter is no longer used and any value passed to it will be ignored |
dbName | Name of database to connect to |
|
inlineLIBPQ |
Connect to a database server. This is the predecessor of connectdb with a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. Provide nullptr
or an empty string for any one of these fixed parameters that is to be defaulted.
pq_connection_error | If the connection failed for any number of reasons |
connection
object so as to facilitate stacking pgHost | Hostname of PostgreSQL server (default is local UNIX socket or localhost) |
pgPort | TCP port number to use (default is 3456) |
pgOptions | PostgreSQL options |
pgTTY | This TTY parameter is no longer used and any value passed to it will be ignored |
dbName | Name of database to connect to |
login | Login name (local to PostgreSQL) |
pwd | Password |
|
inlinenoexceptLIBPQ |
Obtains the file descriptor number of the connection socket to the server. A valid descriptor will be greater than or equal to 0; a result of -1 indicates that no server connection is currently open. (This will not change during normal operation, but could change during connection setup or reset.)
-1
indicates that no server connection is currently open
|
inlinenoexceptLIBPQ |
Indicates whether the connection is using SSL.
TRUE
= SSL in useFALSE
= SSL not in use
|
inlinenoexceptLIBPQ |
Returns SSL-related information about the underlying connection. The list of available attributes varies depending on the SSL library being used and the type of connection.
The following attributes are commonly available:
library
protocol
TLSv1
, TLSv1.1
, and TLSv1.2
, but an implementation may return other strings if some other protocol is used. key_bits
cipher
DHE-RSA-DES-CBC3-SHA
); the names are specific to each SSL implementation. compression
on
if SSL compression is in use, otherwise off
is returned.As a special case, the library attribute may be queried before connecting to a database (which will effectively pass nullptr
as the conn
argument), and the result will be the default SSL library name (or nullptr
if libpq
was compiled without any SSL support. (Prior to PostgreSQL version 15, passing nullptr
as the conn
argument always resulted in returning nullptr
. Client programs needing to differentiate between the newer and older implementations of this case may check the LIBPQ_HAS_SSL_LIBRARY_DETECTION
feature macro.)
const char*
list of attributesnullptr
when the connection does not use SSL or the specified attribute name is not defined for the OpenSSL library that's in use attribute_name | Attribute name |
|
inlinenoexceptLIBPQ |
Returns an array of SSL attribute names available.
nullptr
)
|
inlinenoexceptLIBPQ |
Returns a pointer to an SSL-implementation-specific object describing the connection.
The struct(s) available depend on the SSL implementation in use; for OpenSSL, there is one struct, available under the name OpenSSL, and it returns a pointer to OpenSSL's SSL struct.
nullptr
when the connection does not use SSL or the requested type of object is not available from the SSL implementationstruct_name | SSL structure name |
|
inlinenoexceptLIBPQ |
Returns the status of the connection.
The status can be one of a number of values. However, only two of these are seen outside of an asynchronous connection procedure:
CONNECTION_OK
CONNECTION_BAD
A good connection to the database has the CONNECTION_OK
status, while a failed connection attempt is signaled by the CONNECTION_BAD
status. Ordinarily, an OK status will remain so until finish (which is also called automatically by this class's destructor), but a communications failure might result in the status changing to CONNECTION_BAD
prematurely, in which case the application could try to recover by calling reset.
|
inlinenoexceptLIBPQ |
Returns the current in-transaction status of the server.
The status can be one of the following values:
PQTRANS_ACTIVE
(a command is in-progress; query not yet completed)PQTRANS_IDLE
(currently idle)PQTRANS_INTRANS
(idle, in a valid transaction block)PQTRANS_INERROR
(idle, in a failed transaction block)PQTRANS_UNKNOWN
(bad connection)
|
inlinenoexceptLIBPQ |
This method no longer does anything, but it remains for backwards compatibility.
nullptr
if there is no database connection
|
inlinestaticLIBPQ |
Converts a string representation of binary data into binary data, which is the reverse of escapeBytea. This is needed when retrieving bytea data in text format (but not when retrieving it in binary format).
The from
parameter points to a string such as might be returned by the result::getvalue method when applied to a bytea
column. This this unescapeBytea
method converts this string representation into its raw binary representation. It returns a pointer to a newly allocated buffer, which must be freed using the freemem method after it is no longer needed.
This conversion is not exactly the inverse of escapeBytea, because the string is not expected to be “escaped” when received from the result::getvalue method. In particular, this means there is no need for string quoting considerations, and so no need for a PGconn
parameter.
from | String to convert from |
to_length | Length of string whose pointer will be returned |
|
inlinenoexceptLIBPQ |