transaction_base.hxx
/* Common code and definitions for the transaction classes.
*
* pqxx::transaction_base defines the interface for any abstract class that
* represents a database transaction.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/transaction_base instead.
*
* Copyright (c) 2000-2023, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this
* mistake, or contact the author.
*/
#ifndef PQXX_H_TRANSACTION_BASE
#define PQXX_H_TRANSACTION_BASE
#if !defined(PQXX_HEADER_PRE)
# error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
#endif
#include <string_view>
/* End-user programs need not include this file, unless they define their own
* transaction classes. This is not something the typical program should want
* to do.
*
* However, reading this file is worthwhile because it defines the public
* interface for the available transaction classes such as transaction and
* nontransaction.
*/
#include "pqxx/connection.hxx"
#include "pqxx/internal/concat.hxx"
#include "pqxx/internal/encoding_group.hxx"
#include "pqxx/internal/stream_query.hxx"
#include "pqxx/isolation.hxx"
#include "pqxx/result.hxx"
#include "pqxx/row.hxx"
#include "pqxx/util.hxx"
namespace pqxx::internal::gate
{
class transaction_subtransaction;
class transaction_sql_cursor;
class transaction_stream_to;
class transaction_transaction_focus;
} // namespace pqxx::internal::gate
namespace pqxx
{
using namespace std::literals;
class transaction_focus;
class PQXX_LIBEXPORT PQXX_NOVTABLE transaction_base
{
public:
transaction_base() = delete;
transaction_base(transaction_base const &) = delete;
transaction_base(transaction_base &&) = delete;
transaction_base &operator=(transaction_base const &) = delete;
transaction_base &operator=(transaction_base &&) = delete;
virtual ~transaction_base() = 0;
void commit();
void abort();
template<typename... ARGS> [[nodiscard]] auto esc(ARGS &&...args) const
{
return conn().esc(std::forward<ARGS>(args)...);
}
template<typename... ARGS> [[nodiscard]] auto esc_raw(ARGS &&...args) const
{
return conn().esc_raw(std::forward<ARGS>(args)...);
}
[[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
unesc_raw(zview text) const
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return conn().unesc_raw(text);
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
[[nodiscard]] std::basic_string<std::byte> unesc_bin(zview text)
{
return conn().unesc_bin(text);
}
[[nodiscard, deprecated("Use unesc_bin() instead.")]] std::string
unesc_raw(char const *text) const
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return conn().unesc_raw(text);
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
[[nodiscard]] std::basic_string<std::byte> unesc_bin(char const text[])
{
return conn().unesc_bin(text);
}
template<typename T> [[nodiscard]] std::string quote(T const &t) const
{
return conn().quote(t);
}
[[deprecated(
"Use std::basic_string<std::byte> instead of binarystring.")]] std::string
quote(binarystring const &t) const
{
return conn().quote(t.bytes_view());
}
[[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
quote_raw(unsigned char const bin[], std::size_t len) const
{
return quote(binary_cast(bin, len));
}
[[deprecated("Use quote(std::basic_string_view<std::byte>).")]] std::string
quote_raw(zview bin) const;
#if defined(PQXX_HAVE_CONCEPTS)
template<binary DATA>
[[nodiscard]] std::string quote_raw(DATA const &data) const
{
return conn().quote_raw(data);
}
#endif
[[nodiscard]] std::string quote_name(std::string_view identifier) const
{
return conn().quote_name(identifier);
}
[[nodiscard]] std::string
esc_like(std::string_view bin, char escape_char = '\\') const
{
return conn().esc_like(bin, escape_char);
}
[[deprecated("The desc parameter is going away.")]] result
exec(std::string_view query, std::string_view desc);
result exec(std::string_view query)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return exec(query, std::string_view{});
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
[[deprecated(
"Pass your query as a std::string_view, not stringstream.")]] result
exec(std::stringstream const &query, std::string_view desc)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return exec(query.str(), desc);
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
[[deprecated("The desc parameter is going away.")]] result
exec0(zview query, std::string_view desc)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return exec_n(0, query, desc);
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
result exec0(zview query) { return exec_n(0, query); }
[[deprecated("The desc parameter is going away.")]] row
exec1(zview query, std::string_view desc)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return exec_n(1, query, desc).front();
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
row exec1(zview query) { return exec_n(1, query).front(); }
[[deprecated("The desc parameter is going away.")]] result
exec_n(result::size_type rows, zview query, std::string_view desc);
result exec_n(result::size_type rows, zview query)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
return exec_n(rows, query, std::string_view{});
#include "pqxx/internal/ignore-deprecated-post.hxx"
}
template<typename TYPE>
[[deprecated("The desc parameter is going away.")]] TYPE
query_value(zview query, std::string_view desc)
{
#include "pqxx/internal/ignore-deprecated-pre.hxx"
row const r{exec1(query, desc)};
#include "pqxx/internal/ignore-deprecated-post.hxx"
if (std::size(r) != 1)
throw usage_error{internal::concat(
"Queried single value from result with ", std::size(r), " columns.")};
return r[0].as<TYPE>();
}
template<typename TYPE> TYPE query_value(zview query)
{
row const r{exec1(query)};
if (std::size(r) != 1)
throw usage_error{internal::concat(
"Queried single value from result with ", std::size(r), " columns.")};
return r[0].as<TYPE>();
}
template<typename... TYPE>
[[nodiscard]] std::tuple<TYPE...> query1(zview query)
{
return exec1(query).as<TYPE...>();
}
template<typename... TYPE>
[[nodiscard]] std::optional<std::tuple<TYPE...>> query01(zview query)
{
result res{exec(query)};
auto const rows{std::size(res)};
switch (rows)
{
case 0: return {};
case 1: return {res[0].as<TYPE...>()};
default:
throw unexpected_rows{internal::concat(
"Expected at most one row of data, got "sv, rows, "."sv)};
}
}
template<typename... TYPE>
[[nodiscard]] auto stream(std::string_view query) &
{
return pqxx::internal::stream_query<TYPE...>{*this, query};
}
// C++20: Concept like std::invocable, but without specifying param types.
template<typename CALLABLE>
auto for_stream(std::string_view query, CALLABLE &&func)
{
using param_types =
pqxx::internal::strip_types_t<pqxx::internal::args_t<CALLABLE>>;
param_types const *const sample{nullptr};
auto data_stream{stream_like(query, sample)};
for (auto const &fields : data_stream) std::apply(func, fields);
}
template<typename CALLABLE>
[[deprecated(
"pqxx::transaction_base::for_each is now called for_stream.")]] auto
for_each(std::string_view query, CALLABLE &&func)
{
return for_stream(query, std::forward<CALLABLE>(func));
}
template<typename... TYPE> auto query(zview query)
{
return exec(query).iter<TYPE...>();
}
template<typename... TYPE> auto query_n(result::size_type rows, zview query)
{
return exec_n(rows, query).iter<TYPE...>();
}
// C++20: Concept like std::invocable, but without specifying param types.
template<typename CALLABLE> void for_query(zview query, CALLABLE &&func)
{
exec(query).for_each(std::forward<CALLABLE>(func));
}
template<typename... Args> result exec_params(zview query, Args &&...args)
{
params pp(args...);
return internal_exec_params(query, pp.make_c_params());
}
// Execute parameterised statement, expect a single-row result.
template<typename... Args> row exec_params1(zview query, Args &&...args)
{
return exec_params_n(1, query, std::forward<Args>(args)...).front();
}
// Execute parameterised statement, expect a result with zero rows.
template<typename... Args> result exec_params0(zview query, Args &&...args)
{
return exec_params_n(0, query, std::forward<Args>(args)...);
}
// Execute parameterised statement, expect exactly a given number of rows.
template<typename... Args>
result exec_params_n(std::size_t rows, zview query, Args &&...args)
{
auto const r{exec_params(query, std::forward<Args>(args)...)};
check_rowcount_params(rows, std::size(r));
return r;
}
template<typename... Args>
result exec_prepared(zview statement, Args &&...args)
{
params pp(args...);
return internal_exec_prepared(statement, pp.make_c_params());
}
template<typename... Args>
row exec_prepared1(zview statement, Args &&...args)
{
return exec_prepared_n(1, statement, std::forward<Args>(args)...).front();
}
template<typename... Args>
result exec_prepared0(zview statement, Args &&...args)
{
return exec_prepared_n(0, statement, std::forward<Args>(args)...);
}
template<typename... Args>
result
exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
{
auto const r{exec_prepared(statement, std::forward<Args>(args)...)};
check_rowcount_prepared(statement, rows, std::size(r));
return r;
}
void process_notice(char const msg[]) const { m_conn.process_notice(msg); }
void process_notice(zview msg) const { m_conn.process_notice(msg); }
[[nodiscard]] constexpr connection &conn() const noexcept { return m_conn; }
[[deprecated(
"Set transaction-local variables using SQL SET statements.")]] void
set_variable(std::string_view var, std::string_view value);
[[deprecated("Read variables using SQL SHOW statements.")]] std::string
get_variable(std::string_view);
// C++20: constexpr.
[[nodiscard]] std::string_view name() const &noexcept { return m_name; }
protected:
transaction_base(
connection &c, std::string_view tname,
std::shared_ptr<std::string> rollback_cmd) :
m_conn{c}, m_name{tname}, m_rollback_cmd{rollback_cmd}
{}
transaction_base(connection &c, std::string_view tname);
explicit transaction_base(connection &c);
void register_transaction();
void close() noexcept;
virtual void do_commit() = 0;
virtual void do_abort();
void set_rollback_cmd(std::shared_ptr<std::string> cmd)
{
m_rollback_cmd = cmd;
}
result direct_exec(std::string_view, std::string_view desc = ""sv);
result
direct_exec(std::shared_ptr<std::string>, std::string_view desc = ""sv);
private:
enum class status
{
active,
aborted,
committed,
in_doubt
};
PQXX_PRIVATE void check_pending_error();
result
internal_exec_prepared(zview statement, internal::c_params const &args);
result internal_exec_params(zview query, internal::c_params const &args);
void check_rowcount_prepared(
zview statement, result::size_type expected_rows,
result::size_type actual_rows);
void
check_rowcount_params(std::size_t expected_rows, std::size_t actual_rows);
[[nodiscard]] std::string description() const;
friend class pqxx::internal::gate::transaction_transaction_focus;
PQXX_PRIVATE void register_focus(transaction_focus *);
PQXX_PRIVATE void unregister_focus(transaction_focus *) noexcept;
PQXX_PRIVATE void register_pending_error(zview) noexcept;
PQXX_PRIVATE void register_pending_error(std::string &&) noexcept;
template<typename... ARGS>
auto stream_like(std::string_view query, std::tuple<ARGS...> const *)
{
return stream<ARGS...>(query);
}
connection &m_conn;
transaction_focus const *m_focus = nullptr;
status m_status = status::active;
bool m_registered = false;
std::string m_name;
std::string m_pending_error;
std::shared_ptr<std::string> m_rollback_cmd;
static constexpr std::string_view s_type_name{"transaction"sv};
};
// C++20: Can borrowed_range help?
template<>
std::string_view transaction_base::query_value<std::string_view>(
zview query, std::string_view desc) = delete;
template<>
zview transaction_base::query_value<zview>(
zview query, std::string_view desc) = delete;
} // namespace pqxx
namespace pqxx::internal
{
template<pqxx::isolation_level isolation, pqxx::write_policy rw>
extern const zview begin_cmd;
// These are not static members, so "constexpr" does not imply "inline".
template<>
inline constexpr zview begin_cmd<read_committed, write_policy::read_write>{
"BEGIN"_zv};
template<>
inline constexpr zview begin_cmd<read_committed, write_policy::read_only>{
"BEGIN READ ONLY"_zv};
template<>
inline constexpr zview begin_cmd<repeatable_read, write_policy::read_write>{
"BEGIN ISOLATION LEVEL REPEATABLE READ"_zv};
template<>
inline constexpr zview begin_cmd<repeatable_read, write_policy::read_only>{
"BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"_zv};
template<>
inline constexpr zview begin_cmd<serializable, write_policy::read_write>{
"BEGIN ISOLATION LEVEL SERIALIZABLE"_zv};
template<>
inline constexpr zview begin_cmd<serializable, write_policy::read_only>{
"BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY"_zv};
} // namespace pqxx::internal
#include "pqxx/internal/stream_query_impl.hxx"
#endif
pqxx::transaction_base::esc
auto esc(ARGS &&...args) const
Escape string for use as SQL string literal in this transaction.
Definition transaction_base.hxx:131
pqxx
The home of all libpqxx classes, functions, templates, etc.
Definition array.hxx:33
pqxx::binary_cast
std::basic_string_view< std::byte > binary_cast(TYPE const &data)
Cast binary data to a type that libpqxx will recognise as binary.
Definition util.hxx:303
pqxx::format::text
@ text
pqxx::internal
Internal items for libpqxx' own use. Do not use these yourself.
Definition composite.hxx:84
pqxx::internal::strip_types_t
decltype(strip_types(std::declval< TYPES... >())) strip_types_t
Take a tuple type and apply strip_t to its component types.
Definition util.hxx:527
pqxx::internal::gate
Definition connection.hxx:112
pqxx::binarystring
Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
Definition binarystring.hxx:59
pqxx::binarystring::bytes_view
std::basic_string_view< std::byte > bytes_view() const
Read data as a std::basic_string_view<std::byte>.
Definition binarystring.hxx:178
pqxx::connection
Connection to a database.
Definition connection.hxx:253
pqxx::usage_error
Error in usage of libpqxx library, similar to std::logic_error.
Definition except.hxx:249
pqxx::unexpected_rows
Query returned an unexpected number of rows.
Definition except.hxx:343
pqxx::params
Build a parameter list for a parameterised or prepared statement.
Definition params.hxx:220
pqxx::params::make_c_params
pqxx::internal::c_params make_c_params() const
For internal use: Generate a params object for use in calls.
Definition params.cxx:96
pqxx::result
Result set containing data returned by a query or command.
Definition result.hxx:73
pqxx::result::size_type
result_size_type size_type
Definition result.hxx:75
pqxx::row
Reference to one row in a result.
Definition row.hxx:47
pqxx::row::front
reference front() const noexcept
Definition row.cxx:60
pqxx::transaction_base
Interface definition (and common code) for "transaction" classes.
Definition transaction_base.hxx:88
pqxx::transaction_base::exec_prepared
result exec_prepared(zview statement, Args &&...args)
Execute a prepared statement, with optional arguments.
Definition transaction_base.hxx:730
pqxx::transaction_base::unesc_bin
std::basic_string< std::byte > unesc_bin(zview text)
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:169
pqxx::transaction_base::exec0
result exec0(zview query, std::string_view desc)
Execute command, which should return zero rows of data.
Definition transaction_base.hxx:329
pqxx::transaction_base::conn
constexpr connection & conn() const noexcept
The connection in which this transaction lives.
Definition transaction_base.hxx:780
pqxx::transaction_base::for_each
auto for_each(std::string_view query, CALLABLE &&func)
Definition transaction_base.hxx:550
pqxx::transaction_base::query
auto query(zview query)
Execute query, read full results, then iterate rows of data.
Definition transaction_base.hxx:587
pqxx::transaction_base::process_notice
void process_notice(zview msg) const
Have connection process a warning message.
Definition transaction_base.hxx:776
pqxx::transaction_base::exec0
result exec0(zview query)
Execute command, which should return zero rows of data.
Definition transaction_base.hxx:342
pqxx::transaction_base::query_n
auto query_n(result::size_type rows, zview query)
Perform query, expect given number of rows, iterate results.
Definition transaction_base.hxx:601
pqxx::transaction_base::unesc_raw
std::string unesc_raw(char const *text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:179
pqxx::transaction_base::query_value
TYPE query_value(zview query, std::string_view desc)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition transaction_base.hxx:396
pqxx::transaction_base::exec_prepared_n
result exec_prepared_n(result::size_type rows, zview statement, Args &&...args)
Execute a prepared statement, expect a result with given number of rows.
Definition transaction_base.hxx:760
pqxx::transaction_base::transaction_base
transaction_base(transaction_base const &)=delete
pqxx::transaction_base::transaction_base
transaction_base(connection &c, std::string_view tname, std::shared_ptr< std::string > rollback_cmd)
Create a transaction (to be called by implementation classes only).
Definition transaction_base.hxx:818
pqxx::transaction_base::quote
std::string quote(T const &t) const
Represent object as SQL string, including quoting & escaping.
Definition transaction_base.hxx:197
pqxx::transaction_base::exec_params1
row exec_params1(zview query, Args &&...args)
Definition transaction_base.hxx:660
pqxx::transaction_base::query_value
TYPE query_value(zview query)
Perform query, expecting exactly 1 row with 1 field, and convert it.
Definition transaction_base.hxx:414
pqxx::transaction_base::operator=
transaction_base & operator=(transaction_base const &)=delete
pqxx::transaction_base::esc_raw
auto esc_raw(ARGS &&...args) const
Escape binary data for use as SQL string literal in this transaction.
Definition transaction_base.hxx:148
pqxx::transaction_base::exec
result exec(std::stringstream const &query, std::string_view desc)
Execute a command.
Definition transaction_base.hxx:315
pqxx::transaction_base::quote
std::string quote(binarystring const &t) const
Definition transaction_base.hxx:204
pqxx::transaction_base::exec1
row exec1(zview query)
Execute command returning a single row of data.
Definition transaction_base.hxx:366
pqxx::transaction_base::exec1
row exec1(zview query, std::string_view desc)
Execute command returning a single row of data.
Definition transaction_base.hxx:352
pqxx::transaction_base::transaction_base
transaction_base(transaction_base &&)=delete
pqxx::transaction_base::exec_params
result exec_params(zview query, Args &&...args)
Execute an SQL statement with parameters.
Definition transaction_base.hxx:651
pqxx::transaction_base::query01
std::optional< std::tuple< TYPE... > > query01(zview query)
Query at most one row of data, and if there is one, convert it.
Definition transaction_base.hxx:446
pqxx::transaction_base::transaction_base
transaction_base()=delete
pqxx::transaction_base::exec_params0
result exec_params0(zview query, Args &&...args)
Definition transaction_base.hxx:668
pqxx::transaction_base::for_stream
auto for_stream(std::string_view query, CALLABLE &&func)
Perform a streaming query, and for each result row, call func.
Definition transaction_base.hxx:538
pqxx::transaction_base::unesc_raw
std::string unesc_raw(zview text) const
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:158
pqxx::transaction_base::exec_prepared0
result exec_prepared0(zview statement, Args &&...args)
Execute a prepared statement, and expect a result with zero rows.
Definition transaction_base.hxx:749
pqxx::transaction_base::esc_like
std::string esc_like(std::string_view bin, char escape_char='\\') const
Escape string for literal LIKE match.
Definition transaction_base.hxx:238
pqxx::transaction_base::unesc_bin
std::basic_string< std::byte > unesc_bin(char const text[])
Unescape binary data, e.g. from a table field or notification payload.
Definition transaction_base.hxx:190
pqxx::transaction_base::operator=
transaction_base & operator=(transaction_base &&)=delete
pqxx::transaction_base::exec_n
result exec_n(result::size_type rows, zview query)
Execute command, expect given number of rows.
Definition transaction_base.hxx:383
pqxx::transaction_base::query1
std::tuple< TYPE... > query1(zview query)
Perform query returning exactly one row, and convert its fields.
Definition transaction_base.hxx:432
pqxx::transaction_base::exec
result exec(std::string_view query)
Execute a command.
Definition transaction_base.hxx:300
pqxx::transaction_base::exec_prepared1
row exec_prepared1(zview statement, Args &&...args)
Execute a prepared statement, and expect a single-row result.
Definition transaction_base.hxx:740
pqxx::transaction_base::quote_name
std::string quote_name(std::string_view identifier) const
Escape an SQL identifier for use in a query.
Definition transaction_base.hxx:231
pqxx::transaction_base::quote_raw
std::string quote_raw(unsigned char const bin[], std::size_t len) const
Binary-escape and quote a binary string for use as an SQL constant.
Definition transaction_base.hxx:211
pqxx::transaction_base::name
std::string_view name() const &noexcept
Transaction name, if you passed one to the constructor; or empty string.
Definition transaction_base.hxx:811
pqxx::transaction_base::exec_params_n
result exec_params_n(std::size_t rows, zview query, Args &&...args)
Definition transaction_base.hxx:677
pqxx::transaction_base::stream
auto stream(std::string_view query) &
Execute a query, and loop over the results row by row.
Definition transaction_base.hxx:506
pqxx::transaction_base::for_query
void for_query(zview query, CALLABLE &&func)
Execute a query, load the full result, and perform func for each row.
Definition transaction_base.hxx:616
pqxx::transaction_base::process_notice
void process_notice(char const msg[]) const
Have connection process a warning message.
Definition transaction_base.hxx:774
pqxx::transaction_focus
Base class for things that monopolise a transaction's attention.
Definition transaction_focus.hxx:29
pqxx::zview
Marker-type wrapper: zero-terminated std::string_view.
Definition zview.hxx:38