This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
forked from fnc12/sqlite_orm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction_guard.h
80 lines (68 loc) · 2.83 KB
/
transaction_guard.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#pragma once
#include <functional> // std::function
#include <utility> // std::move
#include "connection_holder.h"
namespace sqlite_orm {
namespace internal {
/**
* Class used as a guard for a transaction. Calls `ROLLBACK` in destructor.
* Has explicit `commit()` and `rollback()` functions. After explicit function is fired
* guard won't do anything in d-tor. Also you can set `commit_on_destroy` to true to
* make it call `COMMIT` on destroy.
*
* Note: The guard's destructor is explicitly marked as potentially throwing,
* so exceptions that occur during commit or rollback are propagated to the caller.
*/
struct transaction_guard_t {
/**
* This is a public lever to tell a guard what it must do in its destructor
* if `gotta_fire` is true
*/
bool commit_on_destroy = false;
transaction_guard_t(connection_ref connection_,
std::function<void()> commit_func_,
std::function<void()> rollback_func_) :
connection(std::move(connection_)),
commit_func(std::move(commit_func_)), rollback_func(std::move(rollback_func_)) {}
transaction_guard_t(transaction_guard_t&& other) :
commit_on_destroy(other.commit_on_destroy), connection(std::move(other.connection)),
commit_func(std::move(other.commit_func)), rollback_func(std::move(other.rollback_func)),
gotta_fire(other.gotta_fire) {
other.gotta_fire = false;
}
~transaction_guard_t() noexcept(false) {
if(this->gotta_fire) {
if(this->commit_on_destroy) {
this->commit_func();
} else {
this->rollback_func();
}
}
}
transaction_guard_t& operator=(transaction_guard_t&&) = delete;
/**
* Call `COMMIT` explicitly. After this call
* guard will not call `COMMIT` or `ROLLBACK`
* in its destructor.
*/
void commit() {
this->gotta_fire = false;
this->commit_func();
}
/**
* Call `ROLLBACK` explicitly. After this call
* guard will not call `COMMIT` or `ROLLBACK`
* in its destructor.
*/
void rollback() {
this->gotta_fire = false;
this->rollback_func();
}
protected:
connection_ref connection;
std::function<void()> commit_func;
std::function<void()> rollback_func;
bool gotta_fire = true;
};
}
}