userver: userver/storages/mongo/transaction.hpp Source File
Loading...
Searching...
No Matches
transaction.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/mongo/transaction.hpp
4/// @brief @copybrief storages::mongo::Transaction
5
6#include <memory>
7#include <string>
8
9#include <userver/storages/mongo/collection.hpp>
10#include <userver/storages/mongo/options.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace storages::mongo {
15
16namespace impl {
17class TransactionImpl;
18} // namespace impl
19
20/// @brief MongoDB transaction handle that provides ACID guarantees.
21///
22/// Transactions group multiple operations within logical units of work
23/// and provide ACID guarantees. All operations in a transaction either
24/// succeed completely or fail completely.
25///
26/// ## Usage example:
27///
28/// @snippet mongo/src/storages/mongo/transaction_mongotest.cpp transaction
29///
30/// @note Transactions require MongoDB replica sets or sharded clusters.
31/// @note Operations within a transaction are automatically retried according
32/// to MongoDB transaction retry semantics.
34public:
35 /// @brief Creates invalid transaction
37
38 /// @cond
39 // For internal use only.
40 explicit Transaction(std::unique_ptr<impl::TransactionImpl>);
41 /// @endcond
42
43 /// @brief Move constructor
45
46 /// @brief Move assignment operator
48
49 /// @brief Destructor. Aborts transaction if not committed.
51
52 /// @brief Get a collection handle within the transaction context
53 /// @param name collection name
54 /// @return Collection handle that operates within this transaction
55 Collection GetCollection(std::string name);
56
57 /// @brief Commit the transaction
58 ///
59 /// Makes all changes within the transaction permanent and visible
60 /// to other operations. If the transaction fails to commit,
61 /// an exception will be thrown.
62 ///
63 /// @throws MongoException on commit failure
64 void Commit();
65
66 /// @brief Abort the transaction
67 ///
68 /// Discards all changes made within the transaction.
69 /// This method is idempotent and safe to call multiple times.
70 void Abort() noexcept;
71
72 /// @brief Check if transaction is active
73 /// @return true if transaction is active (not committed or aborted)
74 bool IsActive() const noexcept;
75
76 /// @brief Get the transaction state
77 enum class State {
78 kNone, ///< Transaction not started
79 kInProgress, ///< Transaction is active
80 kCommitted, ///< Transaction has been committed
81 kAborted ///< Transaction has been aborted
82 };
83
84 /// @brief Get current transaction state
85 State GetState() const noexcept;
86
87private:
88 std::unique_ptr<impl::TransactionImpl> impl_;
89};
90
91} // namespace storages::mongo
92
93USERVER_NAMESPACE_END