randolf.ca  1.00
Randolf Richardson's C++ classes
Loading...
Searching...
No Matches
pq::connection Class Reference

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>

+ Collaboration diagram for 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.
 
connectionconnectdb (const char *connection_string, const int cache_pg_types=0)
 Connect to a database.
 
connectionconnectdb (const std::string &connection_string, const int cache_pg_types=0)
 Connect to a database.
 
connectionconnectdbParams (const char *const *keywords, const char *const *values, const bool expand_dbname, const int cache_pg_types=0)
 Connect to a database.
 
connectionconnectdbParams (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.
 
connectionconnectStart (const char *connection_string)
 Connect to a database in a non-blocking fashion.
 
connectionconnectStart (const std::string &connection_string)
 Connect to a database in a non-blocking fashion.
 
connectionconnectStartParams (const char *const *keywords, const char *const *values, const bool expand_dbname)
 Connect to a database in a non-blocking fashion.
 
connectionconnectStartParams (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.
 
connectionfinish ()
 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.
 
connectionreset ()
 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.
 
connectionresetStart ()
 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.
 
connectionsetdb (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.
 
connectionsetdbLogin (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).
 

Detailed Description

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).

Other solutions

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/

Use case

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.

Background

I created this class to make it easier to make server daemons that utilize PostgreSQL databases.

Getting started
Author
Randolf Richardson
Version
1.00
History
  • 2025-Mar-02 v1.00 Initial version
Conventions
Lower-case letters "cx" are regularly used in partial example code to represent an instantiated PostgreSQL connection object.

An ASCIIZ string is a C-string (char* array) that includes a terminating null (0) character at the end.

Dependencies
Notes

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.)

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdb("user=postgres");
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
The pq namespace is an object-oriented interface version of the PostgreSQL C library API,...
Definition connection:121
Exception handling of connection-specific errors.
Definition errors:33

Parameter stacking is also supported (with methods that return connection&).

Constructor & Destructor Documentation

◆ connection() [1/2]

pq::connection::connection ( )
inlinenoexcept

Default constructor. This does not connect to a PostgreSQL database (see the connectdb and connectdbParams methods).

See also
connectdb
connectdbParams

◆ connection() [2/2]

pq::connection::connection ( PGconn * conn)
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).

See also
connectdb
connectdbParams
Parameters
connPostgreSQL connection handle

◆ ~connection()

pq::connection::~connection ( )
inlinenoexcept

Destructor, which automatically performs the following actions once the instantiated object of this class goes out of scope:

  1. free resources that were allocated
  2. close the connection (if it was opened)

Member Function Documentation

◆ _handle()

PGconn * pq::connection::_handle ( const bool handover = false)
inlinenoexcept

Obtain the underlying PostgreSQL database connection handle.

This is primarily needed for utilizing functionality from the PostgreSQL C programming API directly.

Warning
When this instantiated object goes out of scope, its destructor invalidate the underlying PGconn handle automatically (unldess the handover flag is set).
Returns
PostgreSQL connection handle
See also
socket
Parameters
handoverWhether to prevent destructor invalidation of the underlying handle
TRUE = prevent destructor invalidation
FALSE = don't prevent destructor invalidation (default)

◆ _hash64()

static const long pq::connection::_hash64 ( const char * str)
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.

Note
This 64-bit value will probably need to be converted to hexadecimal, which can be handled efficiently by the __hash64z method.

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).

Returns
Pointer to the hexadecimal ASCIIZ string representing the hash value
See also
_hash64z
Parameters
strPointer to source ASCIIZ string to use when generating the hash

◆ _hash64z()

static const char * pq::connection::_hash64z ( const char * str,
char * hash = nullptr )
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.

Note
With each call to this method, the same internal 17-byte stack-allocated character array that stores the new/resulting ASCIIZ string (this class actually stores this string after the prefix characters "pq_", but this method operates impartially to this as it functions in a generic way).

Using an internal char[] array eliminates additional memory management needs in a manner that also improves processing speed, which is more optimal. As long as multiple statements aren't prepared in parallel (per instantiated class), which isn't supported anyway, this won't be a problem, but it's also important to understand the consequence of calling this method again - or preparing another statement (which also calls this method) - will result in overwriting the underlying string (this is easily remedied by copying the resulting string with strdup or assigning it to an std::string object).

If you need more speed, the _hash64 method returns a pure 64-bit binary hash by value instead, without converting it to a string and without overwriting any existing memory space.

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).

Returns
Pointer to the hexadecimal ASCIIZ string representing the hash value
See also
_hash64
Parameters
strPointer to source ASCIIZ string to use when generating the hash
hashPointer to char[17] array for storing the 17-byte hexadecimal rendition of the resulting hash value as an ASCIIZ string
nullptr = allocate a 17-byte portion of memory using malloc (which will need to be freed after it's no longer needed)

◆ _pg_type()

int32_t pq::connection::_pg_type ( const char * typname,
const uint datatype = 0 )
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:

  • the type was not found
  • the cache was not available (e.g., because it was not initialized)
  • the typname parameter is nullptr
  • an unsupported datatype parameter value was specified

This 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.

Returns
Respective OID or typelen value.
See also
connectdb
connectdbParams
Parameters
typnameThe typname string
datatypeType'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)

◆ backendPID()

int pq::connection::backendPID ( )
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).

Note
The PID belongs to a process executing on the database server host; not the local host.
Exceptions
pq_connection_errorIf there's no open connection to a PostgreSQL server
Returns
Process ID

◆ conndefaults()

static PQconninfoOption * pq::connection::conndefaults ( void )
inlinestaticLIBPQ

Returns the global default connection options.

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 nullptr
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;

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.

Note
The current default values (val fields) will depend on environment variables and other context. A missing or invalid service file will be silently ignored. Callers must treat the connection options data as read-only.

After processing the options array, free it by passing it to the conninfoFree method to prevent a small amount of memory from being leaked with each call to this conndefaults method.

Returns
Pointer to the PQconninfoOption structure
See also
conninfo

◆ connectdb() [1/2]

connection & pq::connection::connectdb ( const char * connection_string,
const int cache_pg_types = 0 )
inlineLIBPQ

Connect to a database.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdb("user=postgres");
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exceptions
pq_connection_errorIf the connection failed for any number of reasons
pq_command_errorIf cache_pg_types is non-zero and a problem is encountered with the pg_type system table
Returns
The same connection object so as to facilitate stacking
See also
connectdbParams
connectPoll
connectStart
connectStartParams
reset
setdbLogin
Parameters
connection_stringConnection string
empty-string = defer to system default
cache_pg_typesCache 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 table
1 = set up a class-wide cache of the pg_type table2 = 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)

◆ connectdb() [2/2]

connection & pq::connection::connectdb ( const std::string & connection_string,
const int cache_pg_types = 0 )
inline

Connect to a database.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <string>
#include <pq/pq>
pq::connection conn(); // Declaration only
std::string connection_details("user=postgres");
int main(int argc, char *argv[]) {
try {
conn.connectdb(connection_details);
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exceptions
pq_connection_errorIf the connection failed for any number of reasons
pq_command_errorIf cache_pg_types is non-zero and a problem is encountered with the pg_type system table
Returns
The same connection object so as to facilitate stacking
See also
connectdbParams
connectPoll
connectStart
connectStartParams
reset
setdbLogin
Parameters
connection_stringConnection string
cache_pg_typesCache 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 table
1 = set up a class-wide cache of the pg_type table2 = 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)

◆ connectdbParams() [1/2]

connection & pq::connection::connectdbParams ( const char *const * keywords,
const char *const * values,
const bool expand_dbname,
const int cache_pg_types = 0 )
inlineLIBPQ

Connect to a database.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdbParams((const char*[]){"user", nullptr},
(const char*[]){"postgres", nullptr},
false);
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-

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):

error: taking address of temporary array
conn.connectdbParams((const char*[]){"user", nullptr},
^~~~~~~~~~~~~~~~~~~~~

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:

const char* k_tmp[] = {"user", nullptr};
const char* v_tmp[] = {"postgres", nullptr};
conn.connectdbParams(k_tmp,
v_tmp,
false);
Exceptions
pq_connection_errorIf the connection failed for any number of reasons
pq_command_errorIf cache_pg_types is non-zero and a problem is encountered with the pg_type system table
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectPoll
connectStart
connectStartParams
reset
setdbLogin
Parameters
keywordsConnection keywords arary
valuesConnection values arary
expand_dbnameWhether to interpret the value associated with the first keyword "dbname" as a connection string
TRUE = yes (like non-zero in the PostgreSQL C programming API)
FALSE = no (like zero in the PostgreSQL C programming API)
cache_pg_typesCache 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 table
1 = set up a class-wide cache of the pg_type table2 = 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)

◆ connectdbParams() [2/2]

connection & pq::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 )
inline

Connect to a database.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdbParams({"user"},
{"postgres"},
false);
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exceptions
pq_connection_errorIf the connection failed for any number of reasons
pq_command_errorIf cache_pg_types is non-zero and a problem is encountered with the pg_type system table
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectPoll
connectStart
connectStartParams
reset
setdbLogin
Parameters
keywordsConnection keywords arary
valuesConnection values arary
expand_dbnameWhether to interpret the value associated with the first keyword "dbname" as a connection string
TRUE = yes (like non-zero in the PostgreSQL C programming API)
FALSE = no (like zero in the PostgreSQL C programming API)
cache_pg_typesCache 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 table
1 = set up a class-wide cache of the pg_type table2 = 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)

◆ connectionNeedsPassword()

bool pq::connection::connectionNeedsPassword ( )
inlinenoexceptLIBPQ

Indicates whether the connection authentication method required a password, but none was available.

Returns
TRUE = password needed, and not available
FALSE = password was provided, and was available
See also
connectionUsedPassword

◆ connectionUsedPassword()

bool pq::connection::connectionUsedPassword ( )
inlinenoexceptLIBPQ

Indicates whether the connection authentication method used a password.

Returns
TRUE = password was used
FALSE = password was not used
See also
connectionNeedsPassword
connectionUsedGSSAPI

◆ connectPoll()

PostgresPollingStatusType pq::connection::connectPoll ( const int cache_pg_types = 0)
inlineLIBPQ

Poll an ongoing attempt to connect to a database in a non-blocking fashion.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdbParams({"user"},
{"postgres"},
false);
{
// Perform other initializations, work, etc., here
}
conn.connectPoll();
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:
  • The 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.
  • If you call trace, ensure that the stream object into which you trace will not block.
  • You must ensure that the socket is in the appropriate state before calling connectPoll, as described below.

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
    Waiting for connection to be made.

  • CONNECTION_MADE
    Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE
    Waiting for a response from the server.

  • CONNECTION_AUTH_OK
    Received authentication; waiting for backend start-up to finish.

  • CONNECTION_SSL_STARTUP
    Negotiating SSL encryption.

  • CONNECTION_SETENV
    Negotiating environment-driven parameter settings.

  • CONNECTION_CHECK_WRITABLE
    Checking if connection is able to handle write transactions.

  • CONNECTION_CONSUME
    Consuming any remaining response messages on connection.

Note that, although these constants will remain (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(conn.status()) {
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
// Handling of other case conditions.
// ...
// ...
default:
feedback = "Connecting...";
}

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.

Exceptions
pq_command_errorIf cache_pg_types is non-zero and a problem is encountered with the pg_type system table
Returns
polling status
See also
connectdb
connectdbParams
connectStart
connectStartParams
reset
setdbLogin
Parameters
cache_pg_typesCache 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 table
1 = set up a class-wide cache of the pg_type table2 = 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)

◆ connectStart() [1/2]

connection & pq::connection::connectStart ( const char * connection_string)
inlineLIBPQ

Connect to a database in a non-blocking fashion.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectStart("user=postgres");
{
// Perform other initializations, work, etc., here
}
conn.connectPoll();
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:
  • The 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.
  • If you call trace, ensure that the stream object into which you trace will not block.
  • You must ensure that the socket is in the appropriate state before calling connectPoll, as described below.

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
    Waiting for connection to be made.

  • CONNECTION_MADE
    Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE
    Waiting for a response from the server.

  • CONNECTION_AUTH_OK
    Received authentication; waiting for backend start-up to finish.

  • CONNECTION_SSL_STARTUP
    Negotiating SSL encryption.

  • CONNECTION_SETENV
    Negotiating environment-driven parameter settings.

  • CONNECTION_CHECK_WRITABLE
    Checking if connection is able to handle write transactions.

  • CONNECTION_CONSUME
    Consuming any remaining response messages on connection.

Note that, although these constants will remain (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(pq.status()) {
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
// Handling of other case conditions.
// ...
// ...
default:
feedback = "Connecting...";
}

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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStartParams
reset
setdbLogin
Parameters
connection_stringConnection string
empty-string = defer to system default

◆ connectStart() [2/2]

connection & pq::connection::connectStart ( const std::string & connection_string)
inline

Connect to a database in a non-blocking fashion.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <string>
#include <pq/pq>
pq::connection conn(); // Declaration only
std::string connection_details("user=postgres");
int main(int argc, char *argv[]) {
try {
conn.connectStart(connection_details);
{
// Perform other initializations, work, etc., here
}
conn.connectPoll();
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:
  • The 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.
  • If you call trace, ensure that the stream object into which you trace will not block.
  • You must ensure that the socket is in the appropriate state before calling connectPoll, as described below.

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
    Waiting for connection to be made.

  • CONNECTION_MADE
    Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE
    Waiting for a response from the server.

  • CONNECTION_AUTH_OK
    Received authentication; waiting for backend start-up to finish.

  • CONNECTION_SSL_STARTUP
    Negotiating SSL encryption.

  • CONNECTION_SETENV
    Negotiating environment-driven parameter settings.

  • CONNECTION_CHECK_WRITABLE
    Checking if connection is able to handle write transactions.

  • CONNECTION_CONSUME
    Consuming any remaining response messages on connection.

Note that, although these constants will remain (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(conn.status()) {
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
// Handling of other case conditions.
// ...
// ...
default:
feedback = "Connecting...";
}

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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStartParams
reset
setdbLogin
Parameters
connection_stringConnection string

◆ connectStartParams() [1/2]

connection & pq::connection::connectStartParams ( const char *const * keywords,
const char *const * values,
const bool expand_dbname )
inlineLIBPQ

Connect to a database in a non-blocking fashion.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectStartParams((const char*[]){"user", nullptr},
(const char*[]){"postgres", nullptr},
false);
{
// Perform other initializations, work, etc., here
}
conn.connectPoll();
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-

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):

error: taking address of temporary array
conn.connectdbParams((const char*[]){"user", nullptr},
^~~~~~~~~~~~~~~~~~~~~

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:

const char* k_tmp[] = {"user", nullptr};
const char* v_tmp[] = {"postgres", nullptr};
conn.connectdbParams(k_tmp,
v_tmp,
false);

The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:

  • The 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.
  • If you call trace, ensure that the stream object into which you trace will not block.
  • You must ensure that the socket is in the appropriate state before calling connectPoll, as described below.

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
    Waiting for connection to be made.

  • CONNECTION_MADE
    Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE
    Waiting for a response from the server.

  • CONNECTION_AUTH_OK
    Received authentication; waiting for backend start-up to finish.

  • CONNECTION_SSL_STARTUP
    Negotiating SSL encryption.

  • CONNECTION_SETENV
    Negotiating environment-driven parameter settings.

  • CONNECTION_CHECK_WRITABLE
    Checking if connection is able to handle write transactions.

  • CONNECTION_CONSUME
    Consuming any remaining response messages on connection.

Note that, although these constants will remain (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(conn.status()) {
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
// Handling of other case conditions.
// ...
// ...
default:
feedback = "Connecting...";
}

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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStart
reset
setdbLogin
Parameters
keywordsConnection keywords arary
valuesConnection values arary
expand_dbnameWhether to interpret the value associated with the first keyword "dbname" as a connection string
TRUE = yes (like non-zero in the PostgreSQL C programming API)
FALSE = no (like zero in the PostgreSQL C programming API)

◆ connectStartParams() [2/2]

connection & pq::connection::connectStartParams ( const std::initializer_list< const std::string > keywords,
const std::initializer_list< const std::string > values,
const bool expand_dbname )
inline

Connect to a database in a non-blocking fashion.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectStartParams({"user"},
{"postgres"},
false);
{
// Perform other initializations, work, etc., here
}
conn.connectPoll();
} catch (pq::pq_connection_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
The connectStart, connectStartParams, and connectPoll methods do not block, so long as a number of restrictions are met:
  • The 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.
  • If you call trace, ensure that the stream object into which you trace will not block.
  • You must ensure that the socket is in the appropriate state before calling connectPoll, as described below.

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
    Waiting for connection to be made.

  • CONNECTION_MADE
    Connection OK; waiting to send.

  • CONNECTION_AWAITING_RESPONSE
    Waiting for a response from the server.

  • CONNECTION_AUTH_OK
    Received authentication; waiting for backend start-up to finish.

  • CONNECTION_SSL_STARTUP
    Negotiating SSL encryption.

  • CONNECTION_SETENV
    Negotiating environment-driven parameter settings.

  • CONNECTION_CHECK_WRITABLE
    Checking if connection is able to handle write transactions.

  • CONNECTION_CONSUME
    Consuming any remaining response messages on connection.

Note that, although these constants will remain (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(conn.status()) {
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
// Handling of other case conditions.
// ...
// ...
default:
feedback = "Connecting...";
}

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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStart
reset
setdbLogin
Parameters
keywordsConnection keywords arary
valuesConnection values arary
expand_dbnameWhether to interpret the value associated with the first keyword "dbname" as a connection string
TRUE = yes (like non-zero in the PostgreSQL C programming API)
FALSE = no (like zero in the PostgreSQL C programming API)

◆ conninfo()

PQconninfoOption * pq::connection::conninfo ( )
inlinenoexceptLIBPQ

Returns the connection options used by a live connection.

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 nullptr
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;

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.

Note
The current default values (val fields) will depend on environment variables and other context. A missing or invalid service file will be silently ignored. Callers must treat the connection options data as read-only.

After processing the options array, free it by passing it to the conninfoFree method to prevent a small amount of memory from being leaked with each call to this conndefaults method.

Returns
Pointer to the PQconninfoOption structure
See also
conninfoOption

◆ conninfoParse()

static PQconninfoOption * pq::connection::conninfoParse ( const char * conninfo,
char ** errmsg = nullptr )
inlinestaticnoexceptLIBPQ

Returns parsed connection options from the provided connection string.

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 nullptr
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;

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.

Returns
Pointer to the PQconninfoOption structure
See also
conninfo
Parameters
conninfoConnection string to parse
errmsgWhere to store the array of error messages
nullptr = don't allocate any memory for error messages

◆ db()

char * pq::connection::db ( )
inlinenoexceptLIBPQ

Returns the database name of the connection.

Returns
Database name

◆ errorMessage()

char * pq::connection::errorMessage ( )
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.

Returns
Error message string

◆ escapeBytea()

static unsigned char * pq::connection::escapeBytea ( const unsigned char * from,
const size_t from_length,
size_t * to_length )
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.

Warning
The 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).
Returns
Pointer to escaped string holding the binary data
See also
escapeByteaConn
escapeStringConn
unescapeBytea
Parameters
fromString to convert from
from_lengthLength of from string
to_lengthLength of string whose pointer will be returned

◆ escapeByteaConn()

unsigned char * pq::connection::escapeByteaConn ( const unsigned char * from,
const size_t from_length,
size_t * to_length )
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.

Warning
The 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.

Exceptions
pq::pq_errorIf insufficient memory
Returns
Size of the string pointed to by the to parameter
See also
escapeString
Parameters
fromString to convert from
from_lengthLength of from string
to_lengthLength of string whose pointer will be returned

◆ escapeIdentifier()

char * pq::connection::escapeIdentifier ( const char * str,
const size_t length )
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.

Precondition
Security Tip: As with string literals, to prevent SQL injection attacks, SQL identifiers must be escaped when they are received from an untrustworthy source.
Note
It is neither necessary nor correct to do escaping when a data value is passed as a separate parameter in execParams or its sibling routines.

A terminating zero byte is not required, and should not be counted in the 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.)
Postcondition
The string returned needs to be freed using the freemem() method when it 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. A terminating zero byte is also added. The single quotes that must surround PostgreSQL string literals are included in the result string.
Exceptions
std::invalid_argumentIf there's a formatting problem
Returns
an escaped version of the str parameter (see Postcondition important notes about memory management)
See also
escapeLiteral
Parameters
strString to process
lengthLength of string

◆ escapeLiteral()

char * pq::connection::escapeLiteral ( const char * str,
const size_t length )
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.

Precondition
Security Tip: It is especially important to do proper escaping when handling strings that were received from an untrustworthy source. Otherwise there is a security risk: you are vulnerable to “SQL injection” attacks wherein unwanted SQL commands are fed to your database.
Note
It is neither necessary nor correct to do escaping when a data value is passed as a separate parameter in execParams or its sibling routines.

A terminating zero byte is not required, and should not be counted in the 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.)
Postcondition
The string returned needs to be freed using the freemem() method when it 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. A terminating zero byte is also added. The single quotes that must surround PostgreSQL string literals are included in the result string.
Exceptions
std::invalid_argumentIf there's a formatting problem
Returns
an escaped version of the str parameter (see Postcondition important notes about memory management)
See also
escapeIdentifier
Parameters
strString to process
lengthLength of string

◆ escapeString()

static size_t pq::connection::escapeString ( char * to,
const char * from,
const size_t length )
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.

Warning
The 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.
Returns
Size of the string pointed to by the to parameter
See also
escapeByteaConn
escapeStringConn
Parameters
toArray to save to
fromString to convert from
lengthLength of string

◆ escapeStringConn()

size_t pq::connection::escapeStringConn ( char * to,
const char * from,
size_t length,
int * error = nullptr )
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.

Exceptions
std::invalid_argumentIf there's a formatting problem
Returns
Size of the string pointed to by the to parameter
See also
escapeByteaConn
escapeString
Parameters
toArray to save to
fromString to convert from
lengthLength of string
errorPointer to where to store error code
nullptr = don't store error code (an exception will still be thrown if an error is encountered)

◆ exec() [1/2]

result pq::connection::exec ( const char * query_string)
inlineLIBPQ

Submit a command/query to the server and wait for the result.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdb("user=postgres");
pq::result result = conn.exec("SELECT 'allballs'::TIME");
// The stroke of midnight: 00:00:00
} catch (pq::pq_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exception handling class that all pq exceptions inherit from. May serve as a general catch-all for al...
Definition errors:13
The result class is an object-oriented interface to the PostgreSQL C library API's PGresult structure...
Definition result:70
Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
Parameters
query_stringQuery string

◆ exec() [2/2]

result pq::connection::exec ( const std::string & query_string)
inlineLIBPQ

Submit a command/query to the server and wait for the result.

Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <stream>
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdb("user=postgres");
std::string query("SELECT 'allballs'::TIME");
pq::result result = conn.exec(query);
// The stroke of midnight: 00:00:00
} catch (pq::pq_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
Parameters
query_stringQuery string

◆ execParams() [1/2]

result pq::connection::execParams ( const char * query_string,
const int nParams,
const Oid * paramTypes,
const char *const * paramValues,
const int * paramLengths,
const int * paramFormats,
const int resultFormat )
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.

Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
The expected result object
Parameters
query_stringQuery string
nParamsNumber of parameters
paramTypesData types, by OID
nullptr = server infers data types automatically
paramValuesValues 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
paramLengthsLengths of binary-format parameter values (ignored for values that are text-format or nullptr)
paramFormatsIndicates 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
resultFormatWhether to obtain results in text format (0) or binary (1)

◆ execParams() [2/2]

result pq::connection::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 = {} )
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.

Note
Some changes are made to the parameters that deviate from the PostgreSQL C library API standard:
  • 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 needed
  • resultFormat was moved to the position after paramValues because it's convenient
Example
#include <iostream> // std::cout, std::cerr, std::endl, etc.
#include <stream>
#include <pq/pq>
pq::connection conn(); // Declaration only
int main(int argc, char *argv[]) {
try {
conn.connectdb("user=postgres");
pq::result result = conn.execParams(
"SELECT $1::TIME",
{ "allballs" } // The stroke of midnight: 00:00:00
);
} catch (pq::pq_error& e) {
std::cout << e << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} // -x- int main -x-
Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
The expected result object
Parameters
query_stringQuery string
paramValuesValues 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
resultFormatWhether to obtain results in text format (0) or binary (1)
paramLengthsLengths of binary-format parameter values (ignored for values that are text-format or nullptr)
paramFormatsIndicates 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
paramTypesData types, by OID
nullptr = server infers data types automatically

◆ finish()

connection & pq::connection::finish ( )
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).

Warning
This object must not be used again after this finish method has been called (except for setting up a new connection).
Returns
The same connection object so as to facilitate stacking

◆ freemem()

static void pq::connection::freemem ( void * ptr)
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).

Warning
It is particularly important that this method, rather than ::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.
Returns
Nothing
Parameters
ptrPointer to memory that was allocated by libpq@n nullptr is ignored

◆ getssl()

void * pq::connection::getssl ( )
inlinenoexceptLIBPQ

Returns the SSL structure used in the connection.

Warning
This method is equivalent to 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.
Returns
SSL structure
nullptr when the connection does not use SSL or the requested type of object is not available from the SSL implementation
See also
sslAttribute
sslInUse
sslStruct

◆ host()

char * pq::connection::host ( )
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.

Exceptions
pq_connection_errorIf 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.
Returns
Hostname
See also
hostaddr
port

◆ hostaddr()

char * pq::connection::hostaddr ( )
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.

Exceptions
pq_connection_errorIf 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.
Returns
Hostaddr
See also
host
port

◆ isthreadsafe()

static bool pq::connection::isthreadsafe ( )
inlinestaticnoexceptLIBPQ

Returns the thread safety status of the libpq library.

Note
One thread restriction is that no two threads attempt to manipulate the same connection at the same time. In particular, you cannot issue concurrent commands from different threads through the same connection object. (If you need to run concurrent commands, use multiple connections.)

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.
Returns
TRUE = the underlying libpq library is threadsafe
FALSE = the underlying libpq library is not threadsafe

◆ options()

char * pq::connection::options ( )
inlinenoexceptLIBPQ

Returns the command-line options passed in the connection request.

Returns
Command-line options (if any)

◆ parameterStatus()

const char * pq::connection::parameterStatus ( const char * paramName)
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.

Exceptions
pq_connection_errorIf the value of the specified parameter is not known
Returns
Parameter value
Parameters
paramNameParameter name to interrogate

◆ pass()

char * pq::connection::pass ( )
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.

Returns
Password
See also
status
user

◆ ping()

static PGPing pq::connection::ping ( const char * conninfo)
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
    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).
    Returns
    Ping status
    See also
    pingParams
Parameters
conninfoConnection string

◆ pingParams()

static PGPing pq::connection::pingParams ( const char *const * keywords,
const char *const * values,
const bool expand_dbname )
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
    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).
    Returns
    Ping status
    See also
    ping
Parameters
keywordsConnection keywords arary
valuesConnection values arary
expand_dbnameWhether to interpret the value associated with the first keyword "dbname" as a connection string
TRUE = yes (like non-zero in the PostgreSQL C programming API)
FALSE = no (like zero in the PostgreSQL C programming API)

◆ port()

char * pq::connection::port ( )
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

Exceptions
pq_connection_errorIf 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.
Returns
TCP port
See also
host
hostaddr
status

◆ prepare()

result pq::connection::prepare ( const char * stmtName,
const char * query,
const int nParams,
const Oid * paramTypes = nullptr )
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.

Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
Result set
See also
execPrepared
describePrepared
Parameters
stmtNameStatement name
queryQuery string
nParamsNumber of parameters
paramTypesData types, by OID
nullptr = server infers data types automatically

◆ execPrepared()

result pq::connection::execPrepared ( const char * stmtName,
const int nParams,
const char *const * paramValues,
const int * paramLengths,
const int * paramFormats,
const int resultFormat )
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).

Exceptions
pq_command_errorIf the command failed for any number of reasons
Returns
Result set
See also
describePrepared
prepare
Parameters
stmtNameStatement name
nParamsNumber of parameters
paramValuesValues 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
paramLengthsLengths of binary-format parameter values (ignored for values that are text-format or nullptr)
paramFormatsIndicates 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
resultFormatWhether to obtain results in text format (0) or binary (1)

◆ describePortal()

result pq::connection::describePortal ( const char * portalName)
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.

Exceptions
pq_command_errorIf the portal name is invalid
pq_connection_errorIf the connection is bad
Returns
Result set
See also
declarePortal
closePortal
pq::portal
Parameters
portalNamePortal name

◆ describePrepared()

result pq::connection::describePrepared ( const char * stmtName)
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.

Exceptions
pq_connection_errorIf the connection is bad
Returns
Result set
See also
execPrepared
prepare
Parameters
stmtNameStatement name

◆ protocolVersion()

int pq::connection::protocolVersion ( )
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.

Exceptions
pq_connection_errorIf the connection is bad
Returns
Version number

◆ reset()

connection & pq::connection::reset ( )
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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStart
connectStartParams
resetPoll
resetStart
setdbLogin

◆ resetPoll()

PostgresPollingStatusType pq::connection::resetPoll ( )
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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
Polling status (type code)
See also
connectdb
connectdbParams
connectPoll
connectStart
connectStartParams
reset
resetStart
setdbLogin

◆ resetStart()

connection & pq::connection::resetStart ( )
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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
connectPoll
connectStart
connectStartParams
reset
resetPoll
setdbLogin

◆ serverVersion()

int pq::connection::serverVersion ( )
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).

Note
Prior to major version 10, PostgreSQL used three-part version numbers in which the first two parts together represented the major version. For those versions, the serverVersion method uses two digits for each part; for example version 9.1.5 will be returned as 90105, and version 9.2.10 will be returned as 90210.

Therefore, for purposes of determining feature compatibility, applications should divide the result of this serverVersion method by 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).
Exceptions
pq_connection_errorIf the connection is bad
Returns
Version number

◆ setdb()

connection & pq::connection::setdb ( const char * pgHost = nullptr,
const char * pgPort = nullptr,
const char * pgOptions = nullptr,
const char * pgTTY = nullptr,
const char * dbName = nullptr )
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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
reset
setdbLogin
Parameters
pgHostHostname of PostgreSQL server (default is local UNIX socket or localhost)
pgPortTCP port number to use (default is 3456)
pgOptionsPostgreSQL options
pgTTYThis TTY parameter is no longer used and any value passed to it will be ignored
dbNameName of database to connect to

◆ setdbLogin()

connection & pq::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 )
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.

Exceptions
pq_connection_errorIf the connection failed for any number of reasons
Returns
The same connection object so as to facilitate stacking
See also
connectdb
connectdbParams
reset
setdb
Parameters
pgHostHostname of PostgreSQL server (default is local UNIX socket or localhost)
pgPortTCP port number to use (default is 3456)
pgOptionsPostgreSQL options
pgTTYThis TTY parameter is no longer used and any value passed to it will be ignored
dbNameName of database to connect to
loginLogin name (local to PostgreSQL)
pwdPassword

◆ socket()

int pq::connection::socket ( )
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.)

Returns
Underlying file descriptor
-1 indicates that no server connection is currently open
See also
_handle

◆ sslInUse()

bool pq::connection::sslInUse ( )
inlinenoexceptLIBPQ

Indicates whether the connection is using SSL.

Returns
TRUE = SSL in use
FALSE = SSL not in use

◆ sslAttribute()

const char * pq::connection::sslAttribute ( const char * attribute_name)
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
    Name of the SSL implementation in use (currently, only "OpenSSL" is implemented).

  • protocol
    SSL/TLS version in use; common values are TLSv1, TLSv1.1, and TLSv1.2, but an implementation may return other strings if some other protocol is used.

  • key_bits
    Number of key bits used by the encryption algorithm.

  • cipher
    A short name of the ciphersuite used (e.g., DHE-RSA-DES-CBC3-SHA); the names are specific to each SSL implementation.

  • compression
    Returns 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.)

Returns
const char* list of attributes
nullptr when the connection does not use SSL or the specified attribute name is not defined for the OpenSSL library that's in use
Parameters
attribute_nameAttribute name

◆ sslAttributeNames()

const char *const * pq::connection::sslAttributeNames ( )
inlinenoexceptLIBPQ

Returns an array of SSL attribute names available.

Returns
ASCIIZ string array (the final entry is nullptr)

◆ sslStruct()

void * pq::connection::sslStruct ( const char * struct_name)
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.

Returns
SSL-implementation-specific object describing the connection
nullptr when the connection does not use SSL or the requested type of object is not available from the SSL implementation
See also
getssl
Parameters
struct_nameSSL structure name

◆ status()

ConnStatusType pq::connection::status ( )
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.
    Returns
    Connection status
    See also
    result::resultStatus

◆ transactionStatus()

PGTransactionStatusType pq::connection::transactionStatus ( )
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)
    Returns
    Transaction status

◆ tty()

char * pq::connection::tty ( )
inlinenoexceptLIBPQ

This method no longer does anything, but it remains for backwards compatibility.

Returns
An empty string, or nullptr if there is no database connection

◆ unescapeBytea()

static unsigned char * pq::connection::unescapeBytea ( const unsigned char * from,
size_t * to_length )
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.

Returns
Pointer to raw binary data, which will need to be freed using the freemem method after it's no longer needed
See also
escapeBytea
escapeByteaConn
escapeStringConn
Parameters
fromString to convert from
to_lengthLength of string whose pointer will be returned

◆ user()

char * pq::connection::user ( )
inlinenoexceptLIBPQ

Returns the user name of the connection.

Returns
User name
See also
pass

The documentation for this class was generated from the following file: