Cppgres
Build Postgres extensions in C++
Loading...
Searching...
No Matches
xact.hpp
Go to the documentation of this file.
1
4#pragma once
5
6#include <stack>
7
8extern "C" {
9#include <access/xact.h>
10}
11
12namespace cppgres {
13
15 internal_subtransaction(bool commit = true)
16 : owner(::CurrentResourceOwner), commit(commit), name("") {
17 if (txns.empty()) {
18 ffi_guard{::BeginInternalSubTransaction}(nullptr);
19 txns.push(this);
20 } else {
21 throw std::runtime_error("internal subtransaction already started");
22 }
23 }
24
25 internal_subtransaction(std::string_view name, bool commit = true)
26 : owner(::CurrentResourceOwner), commit(commit), name(name) {
27 if (txns.empty()) {
28 ffi_guard{::BeginInternalSubTransaction}(this->name.c_str());
29 txns.push(this);
30 } else {
31 throw std::runtime_error("internal subtransaction already started");
32 }
33 }
34
36 txns.pop();
37 if (commit) {
38 ffi_guard{::ReleaseCurrentSubTransaction}();
39 } else {
40 ffi_guard{::RollbackAndReleaseCurrentSubTransaction}();
41 }
42 ::CurrentResourceOwner = owner;
43 }
44
45private:
46 ::ResourceOwner owner;
47 bool commit;
48 std::string name;
49 static inline std::stack<internal_subtransaction *> txns;
50};
51
53 transaction(bool commit = true) : should_commit(commit), released(false) {
54 ffi_guard([]() {
55 if (!::IsTransactionState()) {
56 ::SetCurrentStatementStartTimestamp();
57 ::StartTransactionCommand();
58 ::PushActiveSnapshot(::GetTransactionSnapshot());
59 }
60 })();
61 }
62
63 ~transaction() {
64 if (!released) {
65 ffi_guard([this]() {
66 ::PopActiveSnapshot();
67 if (should_commit) {
68 ::CommitTransactionCommand();
69 } else {
70 ::AbortCurrentTransaction();
71 }
72 })();
73 }
74 }
75
76 void commit() {
77 ffi_guard([]() {
78 ::PopActiveSnapshot();
79 ::CommitTransactionCommand();
80 })();
81 released = true;
82 }
83
84 void rollback() {
85 ffi_guard([]() {
86 ::PopActiveSnapshot();
87 ::AbortCurrentTransaction();
88 })();
89 released = true;
90 }
91
92private:
93 bool should_commit;
94 bool released;
95};
96
97} // namespace cppgres
Definition: guard.hpp:19
Definition: xact.hpp:14
Definition: name.hpp:7
Definition: xact.hpp:52