libpqxx  7.2.0
pqxx::connection Class Reference

Connection to a database. More...

#include <connection.hxx>

Public Member Functions

 connection ()
 
 connection (std::string const &options)
 
 connection (char const options[])
 
 connection (zview options)
 
 connection (connection &&rhs)
 Move constructor. More...
 
 ~connection ()
 
connectionoperator= (connection &&rhs)
 Move assignment. More...
 
 connection (connection const &)=delete
 
connectionoperator= (connection const &)=delete
 
bool PQXX_PURE is_open () const noexcept
 Is this connection open at the moment? More...
 
void process_notice (char const []) noexcept
 Invoke notice processor function. The message should end in newline. More...
 
void process_notice (std::string const &msg) noexcept
 Invoke notice processor function. Newline at end is recommended. More...
 
void process_notice (zview) noexcept
 Invoke notice processor function. Newline at end is recommended. More...
 
void trace (std::FILE *) noexcept
 Enable tracing to a given output stream, or nullptr to disable. More...
 
void set_variable (std::string_view var, std::string_view value)
 Set session variable, using SQL's SET command. More...
 
std::string get_variable (std::string_view)
 Read session variable, using SQL's SHOW command. More...
 
std::string encrypt_password (char const user[], char const password[], char const *algorithm=nullptr)
 Encrypt a password for a given user. More...
 
std::string encrypt_password (zview user, zview password, zview algorithm)
 
std::string adorn_name (std::string_view)
 Suffix unique number to name to make it unique within session context. More...
 
std::string esc (char const text[], std::size_t maxlen) const
 Escape string for use as SQL string literal on this connection. More...
 
std::string esc (char const text[]) const
 Escape string for use as SQL string literal on this connection. More...
 
std::string esc (std::string_view text) const
 Escape string for use as SQL string literal on this connection. More...
 
std::string esc_raw (unsigned char const bin[], std::size_t len) const
 Escape binary string for use as SQL string literal on this connection. More...
 
std::string esc_raw (std::basic_string_view< std::byte >) const
 Escape binary string for use as SQL string literal on this connection. More...
 
std::string unesc_raw (std::string const &text) const
 Unescape binary data, e.g. from a table field or notification payload. More...
 
std::string unesc_raw (zview text) const
 Unescape binary data, e.g. from a table field or notification payload. More...
 
std::string unesc_raw (char const text[]) const
 Unescape binary data, e.g. from a table field or notification payload. More...
 
std::string quote_raw (unsigned char const bin[], std::size_t len) const
 Escape and quote a string of binary data. More...
 
std::string quote_raw (std::basic_string_view< std::byte >) const
 Escape and quote a string of binary data. More...
 
std::string quote_name (std::string_view identifier) const
 Escape and quote an SQL identifier for use in a query. More...
 
template<typename T >
std::string quote (T const &t) const
 Represent object as SQL string, including quoting & escaping. More...
 
std::string quote (binarystring const &) const
 
std::string quote (std::basic_string_view< std::byte > bytes) const
 
std::string esc_like (std::string_view text, char escape_char='\\') const
 Escape string for literal LIKE match. More...
 
void cancel_query ()
 Attempt to cancel the ongoing query, if any. More...
 
void set_verbosity (error_verbosity verbosity) noexcept
 Set session verbosity. More...
 
std::vector< errorhandler * > get_errorhandlers () const
 Return pointers to the active errorhandlers. More...
 
std::string connection_string () const
 Return a connection string encapsulating this connection's options. More...
 
void close ()
 Explicitly close the connection. More...
 
Connection properties

These are probably not of great interest, since most are derived from information supplied by the client program itself, but they are included for completeness.

The connection needs to be currently active for these to work.

char const * dbname () const
 Name of database we're connected to, if any. More...
 
char const * username () const
 Database user ID we're connected under, if any. More...
 
char const * hostname () const
 Address of server, or nullptr if none specified (i.e. default or local) More...
 
char const * port () const
 Server port number we're connected to. More...
 
int PQXX_PURE backendpid () const noexcept
 Process ID for backend process, or 0 if inactive. More...
 
int PQXX_PURE sock () const noexcept
 Socket currently used for connection, or -1 for none. Use with care! More...
 
int PQXX_PURE protocol_version () const noexcept
 What version of the PostgreSQL protocol is this connection using? More...
 
int PQXX_PURE server_version () const noexcept
 What version of the PostgreSQL server are we connected to? More...
 
Text encoding
std::string get_client_encoding () const
 Get client-side character encoding, by name. More...
 
void set_client_encoding (std::string const &encoding)
 Set client-side character encoding, by name. More...
 
void set_client_encoding (char const encoding[])
 Set client-side character encoding, by name. More...
 
int encoding_id () const
 Get the connection's encoding, as a PostgreSQL-defined code. More...
 
Notifications and Receivers
int get_notifs ()
 Check for pending notifications and take appropriate action. More...
 
int await_notification ()
 Wait for a notification to come in. More...
 
int await_notification (std::time_t seconds, long microseconds)
 Wait for a notification to come in, or for given timeout to pass. More...
 
Prepared statements

PostgreSQL supports prepared SQL statements, i.e. statements that can be registered under a client-provided name, optimized once by the backend, and executed any number of times under the given name.

Prepared statement definitions are not sensitive to transaction boundaries. A statement defined inside a transaction will remain defined outside that transaction, even if the transaction itself is subsequently aborted. Once a statement has been prepared, it will only go away if you close the connection or explicitly "unprepare" the statement.

Use the pqxx::transaction_base::exec_prepared functions to execute a prepared statement. See Prepared statements for a full discussion.

Warning
Using prepared statements can save time, but if your statement takes parameters, it may also make your application significantly slower! The reason is that the server works out a plan for executing the query when you prepare it. At that time, the values for the parameters are of course not yet known. If you execute a query without preparing it, then the server works out the plan on the spot, with knowledge of the parameter values. It can use knowlege about these values for optimisation, and the prepared version does not have this knowledge.
void prepare (char const name[], char const definition[])
 Define a prepared statement. More...
 
void prepare (std::string const &name, std::string const &definition)
 
void prepare (zview name, zview definition)
 
void prepare (char const definition[])
 Define a nameless prepared statement. More...
 
void prepare (zview definition)
 
void unprepare (std::string_view name)
 Drop prepared statement. More...
 

Friends

class internal::gate::const_connection_largeobject
 
class internal::gate::connection_errorhandler
 
class internal::gate::connection_transaction
 
class internal::gate::connection_stream_from
 
class internal::gate::connection_stream_to
 
class internal::gate::connection_largeobject
 
class internal::gate::connection_notification_receiver
 
class internal::gate::connection_pipeline
 
class internal::gate::connection_dbtransaction
 
class internal::gate::connection_sql_cursor
 

Detailed Description

Connection to a database.

This is the first class to look at when you wish to work with a database through libpqxx. The connection opens during construction, and closes upon destruction.

When creating a connection, you can pass a connection URI or a postgres connection string, to specify the database server's address, a login username, and so on. If none is given, the connection will try to obtain them from certain environment variables. If those are not set either, the default is to try and connect to the local system's port 5432.

Find more about connection strings here:

https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING

The variables are documented here:

https://www.postgresql.org/docs/current/libpq-envars.html

To query or manipulate the database once connected, use one of the transaction classes (see pqxx/transaction_base.hxx) and perhaps also the transactor framework (see pqxx/transactor.hxx).

When a connection breaks, you will typically get a broken_connection exception. This can happen at almost any point.

Warning
On Unix-like systems, including GNU and BSD systems, your program may receive the SIGPIPE signal when the connection to the backend breaks. By default this signal will abort your program. Use "signal(SIGPIPE, SIG_IGN)" if you want your program to continue running after a connection fails.

Constructor & Destructor Documentation

◆ connection() [1/6]

pqxx::connection::connection ( )

Referenced by quote().

◆ connection() [2/6]

pqxx::connection::connection ( std::string const &  options)
explicit

◆ connection() [3/6]

pqxx::connection::connection ( char const  options[])
explicit

References pqxx::check_version().

◆ connection() [4/6]

pqxx::connection::connection ( zview  options)
explicit

References pqxx::zview::c_str().

◆ connection() [5/6]

pqxx::connection::connection ( connection &&  rhs)

Move constructor.

Moving a connection is not allowed if it has an open transaction, or has error handlers or notification receivers registered on it. In those situations, other objects may hold references to the old object which would become invalid and might produce hard-to-diagnose bugs.

◆ ~connection()

pqxx::connection::~connection ( )

◆ connection() [6/6]

pqxx::connection::connection ( connection const &  )
delete

Member Function Documentation

◆ adorn_name()

std::string pqxx::connection::adorn_name ( std::string_view  n)

Suffix unique number to name to make it unique within session context.

Used internally to generate identifiers for SQL objects (such as cursors and nested transactions) based on a given human-readable base name.

References pqxx::to_string().

Referenced by pqxx::cursor_base::cursor_base(), and pqxx::subtransaction::subtransaction().

◆ await_notification() [1/2]

int pqxx::connection::await_notification ( )

Wait for a notification to come in.

The wait may also be terminated by other events, such as the connection to the backend failing.

If a notification comes in, the call will process it. It will also process any notifications that may have been pending.

Returns
Number of notifications processed.

References get_notifs().

◆ await_notification() [2/2]

int pqxx::connection::await_notification ( std::time_t  seconds,
long  microseconds 
)

Wait for a notification to come in, or for given timeout to pass.

The wait may also be terminated by other events, such as the connection to the backend failing.

If a notification comes in, the call will process it. It will also process any notifications that may have been pending.

Returns
Number of notifications processed

References get_notifs().

◆ backendpid()

int pqxx::connection::backendpid ( ) const
noexcept

Process ID for backend process, or 0 if inactive.

◆ cancel_query()

void pqxx::connection::cancel_query ( )

Attempt to cancel the ongoing query, if any.

You can use this from another thread, and/or while a query is executing in a pipeline, but it's up to you to ensure that you're not canceling the wrong query. This may involve locking.

◆ close()

void pqxx::connection::close ( )

Explicitly close the connection.

You won't normally need this. Destroying a connection object will have the same effect.

References pqxx::check_cast(), process_notice(), and pqxx::to_string().

Referenced by operator=().

◆ connection_string()

std::string pqxx::connection::connection_string ( ) const

Return a connection string encapsulating this connection's options.

The connection must be currently open for this to work.

Returns a reconstruction of this connection's connection string. It may not exactly match the connection string you passed in when creating this connection.

◆ dbname()

char const * pqxx::connection::dbname ( ) const

Name of database we're connected to, if any.

◆ encoding_id()

int pqxx::connection::encoding_id ( ) const

Get the connection's encoding, as a PostgreSQL-defined code.

References pqxx::check_cast(), get_notifs(), and is_open().

Referenced by esc_like(), get_client_encoding(), and operator=().

◆ encrypt_password() [1/2]

std::string pqxx::connection::encrypt_password ( char const  user[],
char const  password[],
char const *  algorithm = nullptr 
)

Encrypt a password for a given user.

Use this when setting a new password for the user if password encryption is enabled. Inputs are the SQL name for the user for whom you with to encrypt a password; the plaintext password; and the hash algorithm.

The algorithm must be one of "md5", "scram-sha-256" (introduced in PostgreSQL 10), or nullptr. If the pointer is null, this will query the password_encryption setting from the server, and use the default algorithm as defined there.

Returns
encrypted version of the password, suitable for encrypted PostgreSQL authentication.

Thus the password for a user can be changed with:

void setpw(transaction_base &t, string const &user, string const &pw)
{
t.exec0("ALTER USER " + user + " "
"PASSWORD '" + t.conn().encrypt_password(user,pw) + "'");
}

When building this against a libpq older than version 10, this will use an older function which only supports md5. In that case, requesting a different algorithm than md5 will result in a feature_not_supported exception.

References pqxx::encrypt_password().

◆ encrypt_password() [2/2]

std::string pqxx::connection::encrypt_password ( zview  user,
zview  password,
zview  algorithm 
)

◆ get_client_encoding()

std::string pqxx::connection::get_client_encoding ( ) const

Get client-side character encoding, by name.

Each connection is governed by a "client encoding," which dictates how strings and other text is represented in bytes. The database server will send text data to you in this encoding, and you should use it for the queries and data which you send to the server.

Search the PostgreSQL documentation for "character set encodings" to find out more about the available encodings, how to extend them, and how to use them. Not all server-side encodings are compatible with all client-side encodings or vice versa.

Encoding names are case-insensitive, so e.g. "UTF8" is equivalent to "utf8".

You can change the client encoding, but this may not work when the connection is in a special state, such as when streaming a table. It's not clear what happens if you change the encoding during a transaction, and then abort the transaction.

References encoding_id(), and pqxx::internal::name_encoding().

◆ get_errorhandlers()

std::vector< pqxx::errorhandler * > pqxx::connection::get_errorhandlers ( ) const

Return pointers to the active errorhandlers.

The entries are ordered from oldest to newest handler.

You may use this to find errorhandlers that your application wants to delete when destroying the connection. Be aware, however, that libpqxx may also add errorhandlers of its own, and those will be included in the list. If this is a problem for you, derive your errorhandlers from a custom base class derived from pqxx::errorhandler. Then use dynamic_cast to find which of the error handlers are yours.

The pointers point to the real errorhandlers. The container it returns however is a copy of the one internal to the connection, not a reference.

References get_notifs().

◆ get_notifs()

int pqxx::connection::get_notifs ( )

Check for pending notifications and take appropriate action.

All notifications found pending at call time are processed by finding any matching receivers and invoking those. If no receivers matched the notification string, none are invoked but the notification is considered processed.

Exceptions thrown by client-registered receivers are reported using the connection's errorhandlers, but the exceptions themselves are not passed on outside this function.

Returns
Number of notifications processed.

References process_notice().

Referenced by await_notification(), encoding_id(), get_errorhandlers(), and unprepare().

◆ get_variable()

std::string pqxx::connection::get_variable ( std::string_view  var)

Read session variable, using SQL's SHOW command.

Warning
This executes an SQL query, so do not get or set variables while a table stream or pipeline is active on the same connection.

References pqxx::result::at(), protocol_version(), and server_version().

Referenced by pqxx::transaction_base::get_variable().

◆ hostname()

char const * pqxx::connection::hostname ( ) const

Address of server, or nullptr if none specified (i.e. default or local)

◆ is_open()

bool pqxx::connection::is_open ( ) const
noexcept

Is this connection open at the moment?

Warning
This function is not needed in most code. Resist the temptation to check it after opening a connection. Instead, just use the connection and rely on getting a broken_connection exception if it failed.

Referenced by pqxx::transaction_base::commit(), encoding_id(), operator=(), and set_client_encoding().

◆ operator=() [1/2]

pqxx::connection & pqxx::connection::operator= ( connection &&  rhs)

Move assignment.

Neither connection can have an open transaction, registered error handlers, or registered notification receivers.

References close(), pqxx::internal::enc_group(), encoding_id(), and is_open().

◆ operator=() [2/2]

connection& pqxx::connection::operator= ( connection const &  )
delete

◆ port()

char const * pqxx::connection::port ( ) const

Server port number we're connected to.

◆ prepare() [1/5]

void pqxx::connection::prepare ( char const  name[],
char const  definition[] 
)

Define a prepared statement.

The statement's definition can refer to a parameter using the parameter's positional number n in the definition. For example, the first parameter can be used as a variable "$1", the second as "$2" and so on.

Here's an example of how to use prepared statements.

using namespace pqxx;
void foo(connection &c)
{
c.prepare("findtable", "select * from pg_tables where name=$1");
work tx{c};
result r = tx.exec_prepared("findtable", "mytable");
if (std::empty(r)) throw runtime_error{"mytable not found!"};
}
Parameters
nameunique name for the new prepared statement.
definitionSQL statement to prepare.

Referenced by prepare().

◆ prepare() [2/5]

void pqxx::connection::prepare ( std::string const &  name,
std::string const &  definition 
)

◆ prepare() [3/5]

void pqxx::connection::prepare ( zview  name,
zview  definition 
)

References pqxx::zview::c_str().

◆ prepare() [4/5]

void pqxx::connection::prepare ( char const  definition[])

Define a nameless prepared statement.

This can be useful if you merely want to pass large binary parameters to a statement without otherwise wishing to prepare it. If you use this feature, always keep the definition and the use close together to avoid the nameless statement being redefined unexpectedly by code somewhere else.

References prepare().

◆ prepare() [5/5]

void pqxx::connection::prepare ( zview  definition)

References pqxx::zview::c_str(), and prepare().

Referenced by prepare().

◆ process_notice() [1/3]

void pqxx::connection::process_notice ( char const  msg[])
noexcept

◆ process_notice() [2/3]

void pqxx::connection::process_notice ( std::string const &  msg)
noexcept

Invoke notice processor function. Newline at end is recommended.

◆ process_notice() [3/3]

void pqxx::connection::process_notice ( zview  msg)
noexcept

Invoke notice processor function. Newline at end is recommended.

The zview variant, with a message ending in newline, is the most efficient way to call process_notice.

◆ protocol_version()

int pqxx::connection::protocol_version ( ) const
noexcept

What version of the PostgreSQL protocol is this connection using?

The answer can be 0 (when there is no connection); 3 for protocol 3.0; or possibly higher values as newer protocol versions come into use.

Referenced by get_variable().

◆ server_version()

int pqxx::connection::server_version ( ) const
noexcept

What version of the PostgreSQL server are we connected to?

The result is a bit complicated: each of the major, medium, and minor release numbers is written as a two-digit decimal number, and the three are then concatenated. Thus server version 9.4.2 will be returned as the decimal number 90402. If there is no connection to the server, this returns zero.

Warning
When writing version numbers in your code, don't add zero at the beginning! Numbers beginning with zero are interpreted as octal (base-8) in C++. Thus, 070402 is not the same as 70402, and 080000 is not a number at all because there is no digit "8" in octal notation. Use strictly decimal notation when it comes to these version numbers.

Referenced by get_variable().

◆ set_client_encoding() [1/2]

void pqxx::connection::set_client_encoding ( std::string const &  encoding)

Set client-side character encoding, by name.

Parameters
encodingName of the character set encoding to use.

References pqxx::encrypt_password().

◆ set_client_encoding() [2/2]

void pqxx::connection::set_client_encoding ( char const  encoding[])

Set client-side character encoding, by name.

Parameters
encodingName of the character set encoding to use.

References is_open(), and pqxx::to_string().

◆ set_variable()

void pqxx::connection::set_variable ( std::string_view  var,
std::string_view  value 
)

Set session variable, using SQL's SET command.

Set a session variable for this connection. See the PostgreSQL documentation for a list of variables that can be set and their permissible values.

If a transaction is currently in progress, aborting that transaction will normally discard the newly set value. That is not true for nontransaction however, since it does not start a real backend transaction.

Warning
This executes an SQL query, so do not get or set variables while a table stream or pipeline is active on the same connection.
Parameters
varVariable to set.
valueNew value for Var: an identifier, a quoted string, or a number.

Referenced by pqxx::transaction_base::set_variable().

◆ set_verbosity()

void pqxx::connection::set_verbosity ( error_verbosity  verbosity)
noexcept

Set session verbosity.

Set the verbosity of error messages to "terse", "normal" (the default), or "verbose."

If "terse", returned messages include severity, primary text, and position only; this will normally fit on a single line. "normal" produces messages that include the above plus any detail, hint, or context fields (these might span multiple lines). "verbose" includes all available fields.

◆ sock()

int pqxx::connection::sock ( ) const
noexcept

Socket currently used for connection, or -1 for none. Use with care!

Query the current socket number. This is intended for event loops based on functions such as select() or poll(), where multiple file descriptors are watched.

Please try to stay away from this function. It is really only meant for event loops that need to wait on more than one file descriptor. If all you need is to block until a notification arrives, for instance, use await_notification(). If you want to issue queries and retrieve results in nonblocking fashion, check out the pipeline class.

Warning
Don't store this value anywhere, and always be prepared for the possibility that, at any given time, there may not be a socket! The socket may change or even go away during any invocation of libpqxx code on the connection.

◆ trace()

void pqxx::connection::trace ( std::FILE *  )
noexcept

Enable tracing to a given output stream, or nullptr to disable.

References pqxx::notification_receiver::channel(), process_notice(), and quote_name().

◆ unprepare()

void pqxx::connection::unprepare ( std::string_view  name)

Drop prepared statement.

References pqxx::check_cast(), get_notifs(), and quote_name().

◆ username()

char const * pqxx::connection::username ( ) const

Database user ID we're connected under, if any.

Friends And Related Function Documentation

◆ internal::gate::connection_dbtransaction

friend class internal::gate::connection_dbtransaction
friend

◆ internal::gate::connection_errorhandler

friend class internal::gate::connection_errorhandler
friend

◆ internal::gate::connection_largeobject

friend class internal::gate::connection_largeobject
friend

◆ internal::gate::connection_notification_receiver

friend class internal::gate::connection_notification_receiver
friend

◆ internal::gate::connection_pipeline

friend class internal::gate::connection_pipeline
friend

◆ internal::gate::connection_sql_cursor

friend class internal::gate::connection_sql_cursor
friend

◆ internal::gate::connection_stream_from

friend class internal::gate::connection_stream_from
friend

◆ internal::gate::connection_stream_to

friend class internal::gate::connection_stream_to
friend

◆ internal::gate::connection_transaction

friend class internal::gate::connection_transaction
friend

◆ internal::gate::const_connection_largeobject

friend class internal::gate::const_connection_largeobject
friend

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