Run a query on the database. The supplied function MUST be thread-safe, for example, by owning all the data it interacts with.
50 {
51
52
53 ThreadLocalKey<std::optional<pqxx::connection>> threadLocalConn{
conn_};
55
56 auto work = [threadLocalConn = std::move(threadLocalConn),
57 connectionString = std::move(connectionString),
58 f = std::forward<F>(f)]() mutable -> R {
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