uvco 0.1
Loading...
Searching...
No Matches
Concepts | Classes | Functions
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)

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 = std::move(threadLocalConn),
57 connectionString = std::move(connectionString),
58 f = std::forward<F>(f)]() mutable -> R {
59 auto &maybeConnection = threadLocalConn.getOrDefault();
60 if (!maybeConnection.has_value()) {
61 maybeConnection = std::make_optional(pqxx::connection{connectionString});
62 }
63 pqxx::work tx{maybeConnection.value()};
64 if constexpr (std::is_void_v<R>) {
65 f(tx);
66 tx.commit();
67 return;
68 } else {
69 R result{f(tx)};
70 tx.commit();
71 return result;
72 }
73 };
74
75 return submitWork<R>(loop_, work);
76}
ThreadLocalKey< std::optional< pqxx::connection > > conn_
Definition pqxx.h:44
const Loop & loop_
Definition pqxx.h:43
std::string connectionString_
Definition pqxx.h:45
T & getOrDefault()
Get the stored value, or create a new one if none exists.
Definition async_work.h:73