libpqxx
7.8.2
|
Connection to a database. More...
#include <connection.hxx>
Public Member Functions | |
connection () | |
connection (char const options[]) | |
Connect to a database, using options string. More... | |
connection (zview options) | |
Connect to a database, using options string. More... | |
connection (connection &&rhs) | |
Move constructor. More... | |
~connection () | |
connection & | operator= (connection &&rhs) |
Move assignment. More... | |
connection (connection const &)=delete | |
connection & | operator= (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 (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... | |
template<typename TYPE > | |
void | set_session_var (std::string_view var, TYPE const &value) & |
Set one of the session variables to a new value. More... | |
std::string | get_variable (std::string_view) |
Read session variable, using SQL's SHOW command. More... | |
std::string | get_var (std::string_view var) |
Read currently applicable value of a variable. More... | |
template<typename TYPE > | |
TYPE | get_var_as (std::string_view var) |
Read currently applicable value of a variable. More... | |
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 (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::basic_string< std::byte > | unesc_bin (std::string_view 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... | |
std::string | quote_table (std::string_view name) const |
Escape and quote a table name. More... | |
std::string | quote_table (table_path) const |
Escape and quote a table path. More... | |
template<PQXX_CHAR_STRINGS_ARG STRINGS> | |
std::string | quote_columns (STRINGS const &columns) const |
Quote and comma-separate a series of column names. 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 |
Escape and quote binary data for use as a BYTEA value in SQL statement. More... | |
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... | |
internal::pq::PGconn * | release_raw_connection () && |
Release the raw connection without closing it. 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 the database to which we're connected, if any. More... | |
char const * | username () const |
Database user ID under which we are connected, if any. More... | |
char const * | hostname () const |
Database server address, if given. More... | |
char const * | port () const |
Server port number on which we are connected to the database. 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 (zview 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... | |
Password encryption | |
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
Thus you can change a user's password 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. | |
std::string | encrypt_password (zview user, zview password, zview algorithm) |
Encrypt a password for a given user. More... | |
std::string | encrypt_password (char const user[], char const password[], char const *algorithm=nullptr) |
Encrypt a password for a given user. More... | |
Prepared statements | |
PostgreSQL supports prepared SQL statements, i.e. statements that you can register under a name you choose, 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
A statement's definition can refer to its parameters as Here's an example of how to use prepared statements. using namespace pqxx; void foo(connection &c) { work tx{c}; if (std::empty(r)) throw runtime_error{"mytable not found!"}; } | |
void | prepare (zview name, zview definition) & |
Define a prepared statement. More... | |
void | prepare (char const name[], char const 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... | |
Static Public Member Functions | |
static connection | seize_raw_connection (internal::pq::PGconn *raw_conn) |
Seize control of a raw libpq connection. More... | |
Connection to a database.
This is the first class to look at when you wish to work with a database through libpqxx. As per RAII principles, the connection opens during construction, and closes upon destruction. If the connection attempt fails, you will not get a connection object; the constructor will fail with a pqxx::broken_connection exception.
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 you don't, 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, or fails to establish itself in the first place, you will typically get a broken_connection exception. This can happen at almost any point.
pqxx::connection::connection | ( | ) |
Referenced by connection(), and quote_columns().
|
explicit |
Connect to a database, using options
string.
References pqxx::check_version().
|
explicit |
Connect to a database, using options
string.
References pqxx::zview::c_str().
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.
References pqxx::zview::c_str(), connection(), connection_string(), and is_open().
pqxx::connection::~connection | ( | ) |
|
delete |
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().
int pqxx::connection::await_notification | ( | ) |
Wait for a notification to come in.
There are other events that will also terminate the wait, such as the backend failing. It will also wake up periodically.
If a notification comes in, the call will process it, along with any other notifications that may have been pending.
To wait for notifications into your own event loop instead, wait until there is incoming data on the connection's socket to be read, then call get_notifs() repeatedly until it returns zero.
References get_notifs().
int pqxx::connection::await_notification | ( | std::time_t | seconds, |
long | microseconds | ||
) |
Wait for a notification to come in, or for given timeout to pass.
There are other events that will also terminate the wait, such as the backend failing, or timeout expiring.
If a notification comes in, the call will process it, along with any other notifications that may have been pending.
To wait for notifications into your own event loop instead, wait until there is incoming data on the connection's socket to be read, then call get_notifs repeatedly until it returns zero.
References get_notifs().
|
noexcept |
Process ID for backend process, or 0 if inactive.
void PQXX_COLD 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.
References pqxx::internal::error_string(), and sock().
void pqxx::connection::close | ( | ) |
Explicitly close the connection.
The destructor will do this for you automatically. Still, there is a reason to close()
objects explicitly where possible: if an error should occur while closing, close()
can throw an exception. A destructor cannot.
Closing a connection is idempotent. Closing a connection that's already closed does nothing.
References pqxx::check_cast(), pqxx::internal::check_unique_register(), pqxx::internal::check_unique_unregister(), pqxx::internal::describe_object(), pqxx::transaction_base::name(), pqxx::internal::pq::pqfreemem(), process_notice(), pqxx::internal::ssize(), and pqxx::text.
Referenced by operator=().
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.
References pqxx::connecting::connecting(), pqxx::connecting::process(), and pqxx::connecting::produce().
Referenced by pqxx::internal::basic_robusttransaction::basic_robusttransaction(), and connection().
char const *PQXX_COLD pqxx::connection::dbname | ( | ) | const |
Name of the database to which we're connected, if any.
Returns nullptr when not connected.
int pqxx::connection::encoding_id | ( | ) | const |
Get the connection's encoding, as a PostgreSQL-defined code.
References pqxx::check_cast(), get_notifs(), is_open(), and pqxx::text.
Referenced by pqxx::array< ELEMENT, DIMENSIONS, SEPARATOR >::array(), esc_like(), get_client_encoding(), pqxx::stream_to::operator<<(), and operator=().
Encrypt a password for a given user.
References pqxx::zview::c_str(), and pqxx::encrypt_password().
std::string pqxx::connection::encrypt_password | ( | char const | user[], |
char const | password[], | ||
char const * | algorithm = nullptr |
||
) |
Encrypt a password for a given user.
References pqxx::internal::pq::pqfreemem().
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().
std::vector< pqxx::errorhandler * > PQXX_COLD 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().
int pqxx::connection::get_notifs | ( | ) |
Check for pending notifications and take appropriate action.
This does not block. To wait for incoming notifications, either call await_notification() (it calls this function); or wait for incoming data on the connection's socket (i.e. wait to read), and then call this function repeatedly until it returns zero. After that, there are no more pending notifications so you may want to wait again.
If any notifications are pending when you call this function, it processes them by finding any receivers that match the notification string and invoking those. If no receivers match, there is nothing to invoke but we do consider the notification processed.
If any of the client-registered receivers throws an exception, the function will report it using the connection's errorhandlers. It does not re-throw the exceptions.
References process_notice().
Referenced by await_notification(), encoding_id(), get_errorhandlers(), and unprepare().
std::string pqxx::connection::get_var | ( | std::string_view | var | ) |
Read currently applicable value of a variable.
This function executes an SQL statement, so it won't work while a pipeline or query stream is active on the connection.
std::optional
if the variable's value is null, or its string value otherwise. References protocol_version(), quote_name(), and server_version().
TYPE pqxx::connection::get_var_as | ( | std::string_view | var | ) |
Read currently applicable value of a variable.
This function executes an SQL statement, so it won't work while a pipeline or query stream is active on the connection.
If there is any possibility that the variable is null, ensure that TYPE
can represent null values.
std::string pqxx::connection::get_variable | ( | std::string_view | var | ) |
Read session variable, using SQL's SHOW
command.
References pqxx::field::as(), pqxx::row::at(), pqxx::result::at(), and quote_name().
Referenced by pqxx::transaction_base::get_variable().
char const *PQXX_COLD pqxx::connection::hostname | ( | ) | const |
Database server address, if given.
This may be an IP address, or a hostname, or (for a Unix domain socket) a socket path. Returns nullptr when not connected.
|
noexcept |
Is this connection open at the moment?
Referenced by pqxx::transaction_base::commit(), connection(), encoding_id(), operator=(), and set_client_encoding().
pqxx::connection & pqxx::connection::operator= | ( | connection && | rhs | ) |
Move assignment.
Neither connection can have an open transaction, registered error handlers, or registered notification receivers.
References pqxx::internal::clear_result(), close(), pqxx::internal::enc_group(), encoding_id(), and is_open().
|
delete |
char const *PQXX_COLD pqxx::connection::port | ( | ) | const |
Server port number on which we are connected to the database.
Define a prepared statement.
name | unique name for the new prepared statement. |
definition | SQL statement to prepare. |
Referenced by prepare().
void pqxx::connection::prepare | ( | char const | name[], |
char const | definition[] | ||
) | & |
name | unique name for the new prepared statement. |
definition | SQL statement to prepare. |
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().
|
noexcept |
Invoke notice processor function. The message should end in newline.
Referenced by pqxx::transaction_base::abort(), close(), pqxx::transaction_base::commit(), pqxx::blob::from_buf(), get_notifs(), trace(), pqxx::blob::~blob(), and pqxx::transaction_base::~transaction_base().
|
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.
|
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_var().
internal::pq::PGconn* pqxx::connection::release_raw_connection | ( | ) | && |
Release the raw connection without closing it.
The connection
object becomes unusable after this.
|
static |
Seize control of a raw libpq connection.
raw_conn | a raw libpq PQconn pointer. |
|
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.
Referenced by get_var().
void pqxx::connection::set_client_encoding | ( | zview | encoding | ) | & |
Set client-side character encoding, by name.
encoding | Name of the character set encoding to use. |
void PQXX_COLD pqxx::connection::set_client_encoding | ( | char const | encoding[] | ) | & |
Set client-side character encoding, by name.
encoding | Name of the character set encoding to use. |
References is_open().
void pqxx::connection::set_session_var | ( | std::string_view | var, |
TYPE const & | value | ||
) | & |
Set one of the session variables to a new value.
This executes SQL, so do not do it while a pipeline or stream is active on the connection.
The value you set here will last for the rest of the connection's duration, or until you set a new value.
If you set the value while in a dbtransaction (i.e. any transaction that is not a nontransaction), then rolling back the transaction will undo the change.
All applies to setting session variables. You can also set the same variables as local variables, in which case they will always revert to their previous value when the transaction ends (or when you overwrite them of course). To set a local variable, simply execute an SQL statement along the lines of "`SET LOCAL var = 'value'`" inside your transaction.
var | The variable to set. |
value | The new value for the variable. |
void pqxx::connection::set_variable | ( | std::string_view | var, |
std::string_view | value | ||
) | & |
Set session variable, using SQL's SET
command.
SET
command.var | Variable to set. |
value | New value for Var. This can be any SQL expression. If it's a string, be sure that it's properly escaped and quoted. |
References quote_name().
Referenced by pqxx::transaction_base::set_variable().
|
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.
References pqxx::internal::pq::pqfreemem().
|
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 you're waiting for any of multiple file descriptors to become ready for communication.
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.
Referenced by cancel_query().
|
noexcept |
Enable tracing to a given output stream, or nullptr to disable.
References pqxx::notification_receiver::channel(), process_notice(), and quote_name().
void pqxx::connection::unprepare | ( | std::string_view | name | ) |
Drop prepared statement.
References pqxx::check_cast(), get_notifs(), quote_name(), and pqxx::text.
char const *PQXX_COLD pqxx::connection::username | ( | ) | const |
Database user ID under which we are connected, if any.
Returns nullptr when not connected.
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |