transactor.hxx
/* Transactor framework, a wrapper for safely retryable transactions.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/transactor 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_TRANSACTOR
#define PQXX_H_TRANSACTOR
#if !defined(PQXX_HEADER_PRE)
# error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
#endif
#include <functional>
#include <type_traits>
#include "pqxx/connection.hxx"
#include "pqxx/transaction.hxx"
namespace pqxx
{
template<typename TRANSACTION_CALLBACK>
inline auto perform(TRANSACTION_CALLBACK &&callback, int attempts = 3)
-> std::invoke_result_t<TRANSACTION_CALLBACK>
{
if (attempts <= 0)
throw std::invalid_argument{
"Zero or negative number of attempts passed to pqxx::perform()."};
for (; attempts > 0; --attempts)
{
try
{
return std::invoke(callback);
}
catch (in_doubt_error const &)
{
// Not sure whether transaction went through or not. The last thing in
// the world that we should do now is try again!
throw;
}
catch (statement_completion_unknown const &)
{
// Not sure whether our last statement succeeded. Don't risk running it
// again.
throw;
}
catch (protocol_violation const &)
{
// This is a subclass of broken_connection, but it's not one where
// retrying is likely to do us any good.
throw;
}
catch (broken_connection const &)
{
// Connection failed. May be worth retrying, if the transactor opens its
// own connection.
if (attempts <= 1)
throw;
continue;
}
catch (transaction_rollback const &)
{
// Some error that may well be transient, such as serialization failure
// or deadlock. Worth retrying.
if (attempts <= 1)
throw;
continue;
}
}
throw pqxx::internal_error{"No outcome reached on perform()."};
}
} // namespace pqxx
#endif
pqxx
The home of all libpqxx classes, functions, templates, etc.
Definition array.hxx:33
pqxx::perform
auto perform(TRANSACTION_CALLBACK &&callback, int attempts=3) -> std::invoke_result_t< TRANSACTION_CALLBACK >
Simple way to execute a transaction with automatic retry.
Definition transactor.hxx:101
pqxx::broken_connection
Exception class for lost or failed backend connection.
Definition except.hxx:81
pqxx::protocol_violation
Exception class for micommunication with the server.
Definition except.hxx:103
pqxx::in_doubt_error
"Help, I don't know whether transaction was committed successfully!"
Definition except.hxx:165
pqxx::transaction_rollback
The backend saw itself forced to roll back the ongoing transaction.
Definition except.hxx:178
pqxx::statement_completion_unknown
We can't tell whether our last statement succeeded.
Definition except.hxx:214
pqxx::internal_error
Internal error in libpqxx library.
Definition except.hxx:242