uvco 0.1
Loading...
Searching...
No Matches
Integrations

Concepts

concept  uvco::WithTxFn

Classes

class  uvco::Pqxx

Functions

template<typename R, typename F>
requires WithTxFn<R, F>
Promise< R > uvco::Pqxx::withTx (F f)

Detailed Description

Function Documentation

◆ withTx()

template<typename R, typename F>
requires WithTxFn<R, F>
Promise< R > uvco::Pqxx::withTx ( F f)

Run a query on the database. The supplied function MUST be thread-safe, for example, by owning all the data it interacts with.

The callable F is expected to take a pqxx::work & as its only argument. Its return value is forwarded to the caller.

50 {
51 // We use one connection per thread-pool thread. That's the best balance
52 // between efficiency and safety.
53 ThreadLocalKey<std::optional<pqxx::connection>> threadLocalConn{conn_};
54 auto connectionString = connectionString_;
55
56 auto work = [threadLocalConn, connectionString = std::move(connectionString),
57 f = std::forward<F>(f)]() mutable -> R {
58 auto &maybeConnection = threadLocalConn.getOrDefault();
59 if (!maybeConnection.has_value()) {
60 maybeConnection = std::make_optional(pqxx::connection{connectionString});
61 }
62 pqxx::work tx{maybeConnection.value()};
63 if constexpr (std::is_void_v<R>) {
64 f(tx);
65 tx.commit();
66 return;
67 } else {
68 R result{f(tx)};
69 tx.commit();
70 return result;
71 }
72 };
73
74 return submitWork<R>(loop_, work);
75}
ThreadLocalKey< std::optional< pqxx::connection > > conn_
Definition pqxx.h:44
const Loop & loop_
Definition pqxx.h:43
std::string connectionString_
Definition pqxx.h:45
Promise< void > submitWork(const Loop &loop, std::function< void()> work)
Definition async_work.cc:113