| 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 | |
| 7 | using namespace duckdb; |
| 8 | using namespace std; |
| 9 | |
| 10 | TransactionContext::~TransactionContext() { |
| 11 | if (is_invalidated) { |
| 12 | return; |
| 13 | } |
| 14 | if (current_transaction) { |
| 15 | try { |
| 16 | Rollback(); |
| 17 | } catch (...) { |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | void TransactionContext::BeginTransaction() { |
| 23 | assert(!current_transaction); // cannot start a transaction within a transaction |
| 24 | current_transaction = transaction_manager.StartTransaction(); |
| 25 | } |
| 26 | |
| 27 | void 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 | |
| 38 | void 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 |