1#include "duckdb/transaction/transaction_context.hpp"
2
3#include "duckdb/common/exception.hpp"
4#include "duckdb/transaction/transaction.hpp"
5#include "duckdb/transaction/transaction_manager.hpp"
6
7using namespace duckdb;
8using namespace std;
9
10TransactionContext::~TransactionContext() {
11 if (is_invalidated) {
12 return;
13 }
14 if (current_transaction) {
15 try {
16 Rollback();
17 } catch (...) {
18 }
19 }
20}
21
22void TransactionContext::BeginTransaction() {
23 assert(!current_transaction); // cannot start a transaction within a transaction
24 current_transaction = transaction_manager.StartTransaction();
25}
26
27void TransactionContext::Commit() {
28 assert(current_transaction); // cannot commit if there is no active transaction
29 auto transaction = current_transaction;
30 SetAutoCommit(true);
31 current_transaction = nullptr;
32 string error = transaction_manager.CommitTransaction(transaction);
33 if (!error.empty()) {
34 throw TransactionException("Failed to commit: %s", error.c_str());
35 }
36}
37
38void TransactionContext::Rollback() {
39 assert(current_transaction); // cannot rollback if there is no active transaction
40 auto transaction = current_transaction;
41 SetAutoCommit(true);
42 current_transaction = nullptr;
43 transaction_manager.RollbackTransaction(transaction);
44}
45