libpqxx
|
connection_base abstract base class; represents a connection to a database. More...
#include <connection_base.hxx>
Public Types | |
enum | error_verbosity { terse =0, normal =1, verbose =2 } |
Error verbosity levels. More... | |
Public Member Functions | |
void | disconnect () noexcept |
Explicitly close connection. More... | |
bool PQXX_PURE | is_open () const noexcept |
Is this connection open at the moment? More... | |
void | process_notice (const char[]) noexcept |
Invoke notice processor function. The message should end in newline. More... | |
void | process_notice (const std::string &) 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 (const std::string &Var, const std::string &Value) |
Set session variable. More... | |
std::string | get_variable (const std::string &) |
Read session variable. More... | |
template<typename TRANSACTOR > | |
void | perform (const TRANSACTOR &T, int Attempts) |
template<typename TRANSACTOR > | |
void | perform (const TRANSACTOR &T) |
std::string | adorn_name (const std::string &) |
Suffix unique number to name to make it unique within session context. More... | |
std::string | esc (const char str[]) |
Escape string for use as SQL string literal on this connection. More... | |
std::string | esc (const char str[], size_t maxlen) |
Escape string for use as SQL string literal on this connection. More... | |
std::string | esc (const std::string &str) |
Escape string for use as SQL string literal on this connection. More... | |
std::string | esc_raw (const unsigned char str[], size_t len) |
Escape binary string for use as SQL string literal on this connection. More... | |
std::string | unesc_raw (const std::string &text) |
Unescape binary data, e.g. from a table field or notification payload. More... | |
std::string | unesc_raw (const char *text) |
Unescape binary data, e.g. from a table field or notification payload. More... | |
std::string | quote_raw (const unsigned char str[], size_t len) |
Escape and quote a string of binary data. More... | |
std::string | quote_name (const std::string &identifier) |
Escape and quote an SQL identifier for use in a query. More... | |
template<typename T > | |
std::string | quote (const T &t) |
Represent object as SQL string, including quoting & escaping. More... | |
std::string | quote (const binarystring &) |
std::string | esc_like (const std::string &str, 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... | |
error_verbosity | get_verbosity () const noexcept |
Retrieve current error verbosity. More... | |
std::vector< errorhandler * > | get_errorhandlers () const |
Return pointers to the active errorhandlers. More... | |
Activation | |
Connections can be temporarily deactivated, or they can break because of overly impatient firewalls dropping TCP connections. Where possible, libpqxx will try to re-activate these when resume using them, or you can wake them up explicitly. You probably won't need this feature, but you should be aware of it. | |
void | activate () |
void | deactivate () |
void | inhibit_reactivation (bool inhibit) |
void | simulate_failure () |
Make the connection fail. 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. | |
const char * | dbname () |
Name of database we're connected to, if any. More... | |
const char * | username () |
Database user ID we're connected under, if any. More... | |
const char * | hostname () |
Address of server, or nullptr if none specified (i.e. default or local) More... | |
const char * | port () |
Server port number we're connected to. More... | |
int PQXX_PURE | backendpid () const noexcept |
Process ID for backend process. More... | |
int PQXX_PURE | sock () const noexcept |
Socket currently used for connection, or -1 for none. Use with care! More... | |
Text encoding | |
std::string | get_client_encoding () const |
Get client-side character encoding, by name. More... | |
void | set_client_encoding (const std::string &encoding) |
Set client-side character encoding, by name. More... | |
void | set_client_encoding (const char 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 (long 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, only closing the connection or explicitly "unpreparing" it can make it go away. Use the Never try to prepare, execute, or unprepare a prepared statement manually using direct SQL queries. Always use the functions provided by libpqxx. | |
void | prepare (const std::string &name, const std::string &definition) |
Define a prepared statement. More... | |
void | prepare (const std::string &definition) |
Define a nameless prepared statement. More... | |
void | unprepare (const std::string &name) |
Drop prepared statement. More... | |
void | prepare_now (const std::string &name) |
Request that prepared statement be registered with the server. More... | |
Protected Member Functions | |
connection_base (connectionpolicy &pol) | |
void | init () |
void | close () noexcept |
void | wait_read () const |
void | wait_read (long seconds, long microseconds) const |
void | wait_write () const |
Capabilities | |
Some functionality may only be available in certain versions of the backend, or only when speaking certain versions of the communications protocol that connects us to the backend. | |
enum | capability { cap_end } |
Session capabilities. More... | |
bool | supports (capability c) const noexcept |
Does this connection seem to support the given capability? 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... | |
connection_base abstract base class; represents a connection to a database.
This is the first class to look at when you wish to work with a database through libpqxx. Depending on the implementing concrete child class, a connection can be automatically opened when it is constructed, or when it is first used, or somewhere inbetween. The connection is automatically closed upon destruction (if it hasn't been closed already).
To query or manipulate the database once connected, use one of the transaction classes (see pqxx/transaction_base.hxx) or preferably the transactor framework (see pqxx/transactor.hxx).
If a network connection to the database server fails, the connection will be restored automatically (although any transaction going on at the time will have to be aborted). This also means that any information set in previous transactions that is not stored in the database, such as temp tables or connection-local variables defined with PostgreSQL's SET command, will be lost. Whenever you create such state, either keept it local to one transaction, where possible, or inhibit automatic reactivation of the connection using the inhibit_reactivation() method.
When a connection breaks, you will typically get a broken_connection exception. This can happen at almost any point, and the details may depend on which connection class (all derived from this one) you use.
As a general rule, always avoid raw queries if libpqxx offers a dedicated function for the same purpose. There may be hidden logic to hide certain complications from you, such as reinstating session variables when a broken or disabled connection is reactivated.
|
explicitprotected |
void pqxx::connection_base::activate | ( | ) |
Use of this method is entirely optional. Whenever a connection is used while in a deferred or deactivated state, it will transparently try to bring itself into an activated state. This function is best viewed as an explicit hint to the connection that "if you're not in an active state, now would be a good time to get into one." Whether a connection is currently in an active state or not makes no real difference to its functionality. There is also no particular need to match calls to activate() with calls to deactivate(). A good time to call activate() might be just before you first open a transaction on a lazy connection.
std::string pqxx::connection_base::adorn_name | ( | const std::string & | 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_base::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. Any pending or received notifications are processed as part of the call.
References pqxx::internal::wait_read().
int pqxx::connection_base::await_notification | ( | long | 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. Any pending or received notifications are processed as part of the call.
References pqxx::internal::wait_read().
|
noexcept |
Process ID for backend process.
Use with care: connections may be lost and automatically re-established without your knowledge, in which case this process ID may no longer be correct. You may, however, assume that this number remains constant and reliable within the span of a successful backend transaction. If the transaction fails, which may be due to a lost connection, then this number will have become invalid at some point within the transaction.
Referenced by pqxx::internal::basic_robusttransaction::~basic_robusttransaction().
void pqxx::connection_base::cancel_query | ( | ) |
Attempt to cancel the ongoing query, if any.
|
protectednoexcept |
References pqxx::to_string().
Referenced by pqxx::basic_connection_base< CONNECTPOLICY >::~basic_connection_base().
const char * pqxx::connection_base::dbname | ( | ) |
Name of database we're connected to, if any.
void pqxx::connection_base::deactivate | ( | ) |
Like its counterpart activate(), this method is entirely optional. Calling this function really only makes sense if you won't be using this connection for a while and want to reduce the number of open connections on the database server. There is no particular need to match or pair calls to deactivate() with calls to activate(), but calling deactivate() during a transaction is an error.
Referenced by pqxx::internal::reactivation_avoidance_exemption::~reactivation_avoidance_exemption().
|
noexcept |
Explicitly close connection.
int pqxx::connection_base::encoding_id | ( | ) | const |
Get the connection's encoding, as a PostgreSQL-defined code.
Referenced by pqxx::stream_from::get_raw_line(), and pqxx::pipeline::resume().
std::string pqxx::connection_base::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 pqxx::internal::name_encoding().
std::vector< errorhandler * > pqxx::connection_base::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.
int pqxx::connection_base::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.
Referenced by pqxx::transaction_base::Begin().
std::string pqxx::connection_base::get_variable | ( | const std::string & | Var | ) |
Read session variable.
Will try to read the value locally, from the list of variables set with the set_variable function. If that fails, the database is queried.
|
noexcept |
Retrieve current error verbosity.
const char * pqxx::connection_base::hostname | ( | ) |
Address of server, or nullptr if none specified (i.e. default or local)
void pqxx::connection_base::inhibit_reactivation | ( | bool | inhibit | ) |
A connection whose underlying socket is not currently connected to the server will normally (re-)establish communication with the server whenever needed, or when the client program requests it (although for reasons of integrity, never inside a transaction; but retrying the whole transaction may implicitly cause the connection to be restored). In normal use this is quite a convenient thing to have and presents a simple, safe, predictable interface.
There is at least one situation where this feature is not desirable, however. Although most session state (prepared statements, session variables) is automatically restored to its working state upon connection reactivation, temporary tables and so-called WITH HOLD cursors (which can live outside transactions) are not.
Cursors that live outside transactions are automatically handled, and the library will quietly ignore requests to deactivate or reactivate connections while they exist; it does not want to give you the illusion of being back in your transaction when in reality you just dropped a cursor. With temporary tables this is not so easy: there is no easy way for the library to detect their creation or track their lifetimes.
So if your program uses temporary tables, and any part of this use happens outside of any database transaction (or spans multiple transactions), some of the work you have done on these tables may unexpectedly be undone if the connection is broken or deactivated while any of these tables exists, and then reactivated or implicitly restored before you are finished with it.
If this describes any part of your program, guard it against unexpected reconnections by inhibiting reconnection at the beginning. And if you want to continue doing work on the connection afterwards that no longer requires the temp tables, you can permit it again to get the benefits of connection reactivation for the remainder of the program.
inhibit | should reactivation be inhibited from here on? |
|
protected |
References pqxx::internal::enc_group().
Referenced by pqxx::basic_connection_base< CONNECTPOLICY >::basic_connection_base().
|
noexcept |
Is this connection open at the moment?
Referenced by pqxx::transaction_base::commit().
void pqxx::connection_base::perform | ( | const TRANSACTOR & | T | ) |
pqxx::perform
instead. This has been superseded by the new transactor framework and pqxx::perform
.
T | The transactor to be executed. |
References pqxx::perform().
const char * pqxx::connection_base::port | ( | ) |
Server port number we're connected to.
void pqxx::connection_base::prepare | ( | const std::string & | name, |
const std::string & | 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. Note the unusual syntax for passing parameters: every new argument is a parenthesized expression that is simply tacked onto the end of the statement!
To save time, prepared statements aren't really registered with the backend until they are first used. If this is not what you want, e.g. because you have very specific realtime requirements, you can use the prepare_now()
function to force immediate preparation.
The statement may not be registered with the backend until it is actually used. So if, for example, the statement is syntactically incorrect, you may see a syntax_error here, or later when you try to call the statement, or during a prepare_now()
call.
name | unique name for the new prepared statement. |
definition | SQL statement to prepare. |
void pqxx::connection_base::prepare | ( | const std::string & | 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.
void pqxx::connection_base::prepare_now | ( | const std::string & | name | ) |
Request that prepared statement be registered with the server.
If the statement had already been fully prepared, this will do nothing.
If the connection should break and be transparently restored, then the new connection will again defer registering the statement with the server. Since connections are never restored inside backend transactions, doing this once at the beginning of your transaction ensures that the statement will not be re-registered during that transaction. In most cases, however, it's probably better not to use this and let the connection decide when and whether to register prepared statements that you've defined.
|
noexcept |
Invoke notice processor function. The message should end in newline.
Referenced by pqxx::transaction_base::abort(), pqxx::transaction_base::commit(), pqxx::transaction_base::End(), pqxx::internal::basic_robusttransaction::~basic_robusttransaction(), and pqxx::transaction_base::~transaction_base().
|
noexcept |
Invoke notice processor function. Newline at end is recommended.
|
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 are taken into use.
If the connection is broken and restored, the restored connection could possibly use a different server and protocol version. This would normally happen if the server is upgraded without shutting down the client program, for example.
|
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 pqxx::internal::basic_robusttransaction::~basic_robusttransaction().
void pqxx::connection_base::set_client_encoding | ( | const std::string & | encoding | ) |
Set client-side character encoding, by name.
Encoding | Name of the character set encoding to use. |
void pqxx::connection_base::set_client_encoding | ( | const char | encoding[] | ) |
Set client-side character encoding, by name.
Encoding | Name of the character set encoding to use. |
References pqxx::to_string().
void pqxx::connection_base::set_variable | ( | const std::string & | Var, |
const std::string & | Value | ||
) |
Set session variable.
Set a session variable for this connection, using the SET command. If the connection to the database is lost and recovered, the last-set value will be restored automatically. 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. However nontransaction (which doesn't start a real backend transaction) is an exception.
Var | Variable to set |
Value | Value vor Var to assume: an identifier, a quoted string, or a number. |
|
noexcept |
Set session verbosity.
Set the verbosity of error messages to "terse", "normal" (i.e. 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.
void pqxx::connection_base::simulate_failure | ( | ) |
Make the connection fail.
Do not use this in normal programs. This is only meant for testing.
|
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.
|
noexcept |
Does this connection seem to support the given capability?
Don't try to be smart by caching this information anywhere. Obtaining it is quite fast (especially after the first time) and what's more, a capability may "suddenly" appear or disappear if the connection is broken or deactivated, and then restored. This may happen silently any time no backend transaction is active; if it turns out that the server was upgraded or restored from an older backup, or the new connection goes to a different backend, then the restored session may have different capabilities than were available previously.
Some guesswork is involved in establishing the presence of any capability; try not to rely on this function being exactly right.
References pqxx::perform().
|
noexcept |
Enable tracing to a given output stream, or nullptr to disable.
References pqxx::notification_receiver::channel().
void pqxx::connection_base::unprepare | ( | const std::string & | name | ) |
Drop prepared statement.
const char * pqxx::connection_base::username | ( | ) |
Database user ID we're connected under, if any.
Referenced by pqxx::internal::basic_robusttransaction::~basic_robusttransaction().
|
protected |
References pqxx::internal::wait_read().
|
protected |
References pqxx::internal::wait_read().
|
protected |
References pqxx::internal::wait_write().
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |
|
friend |