uvco 0.1
Loading...
Searching...
No Matches
pqxx.h
Go to the documentation of this file.
1// uvco (c) 2024 Lewin Bormann. See LICENSE for specific terms.
2
3#include "uvco/async_work.h"
4#include "uvco/loop/loop.h"
6
7#include <fmt/core.h>
8#include <optional>
9#include <pqxx/pqxx>
10#include <string>
11#include <utility>
12
13namespace uvco {
14
17
18template <typename R, typename F>
19concept WithTxFn = std::is_invocable_r_v<R, F, pqxx::work &>;
20
23class Pqxx {
24public:
25 explicit Pqxx(const Loop &loop, std::string connectionString)
26 : loop_{loop}, connectionString_{std::move(connectionString)} {}
27
34 template <typename R, typename F>
35 requires WithTxFn<R, F>
36 Promise<R> withTx(F f);
37
40 void close() { conn_.del(); }
41
42private:
43 const Loop &loop_;
45 std::string connectionString_;
46};
47
48template <typename R, typename F>
49 requires WithTxFn<R, F>
51 // We use one connection per thread-pool thread. That's the best balance
52 // between efficiency and safety.
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}
77
79
80} // namespace uvco
Definition loop.h:26
Definition pqxx.h:23
ThreadLocalKey< std::optional< pqxx::connection > > conn_
Definition pqxx.h:44
Pqxx(const Loop &loop, std::string connectionString)
Definition pqxx.h:25
const Loop & loop_
Definition pqxx.h:43
std::string connectionString_
Definition pqxx.h:45
void close()
Definition pqxx.h:40
Definition promise.h:76
Definition async_work.h:53
void del()
Definition async_work.h:64
T & getOrDefault()
Get the stored value, or create a new one if none exists.
Definition async_work.h:73
Definition pqxx.h:19
Promise< R > withTx(F f)
Definition pqxx.h:50
Definition async_work.cc:17