userver: storages::mongo::Transaction Class Reference
Loading...
Searching...
No Matches
storages::mongo::Transaction Class Reference

#include <userver/storages/mongo/transaction.hpp>

Detailed Description

MongoDB transaction handle that provides ACID guarantees.

Transactions group multiple operations within logical units of work and provide ACID guarantees. All operations in a transaction either succeed completely or fail completely.

A transaction pins exactly one connection from the pool starting from the first call to storages::mongo::Transaction::GetCollection and holds it until the transaction completes, storages::mongo::Transaction::Abort is called, or the transaction is destroyed. An unknown commit result retains the connection for another commit attempt.

Usage example:

auto txn = GetDefaultPool().BeginTransaction();
auto collection = txn.GetCollection(kCollectionName);
// Insert multiple documents
static constexpr std::size_t kDocCount = 5;
std::vector<formats::bson::Document> docs;
docs.reserve(kDocCount);
for (std::size_t i = 0; i < kDocCount; ++i) {
docs.push_back(bson::MakeDoc("name", fmt::format("user_{}", i), "age", 20 + i));
}
auto insert_result = collection.InsertMany(docs);
EXPECT_EQ(insert_result.InsertedCount(), 5);
// Update one document
auto filter = bson::MakeDoc("name", "user_2");
auto update = bson::MakeDoc(operators::kSet, bson::MakeDoc("age", 100));
auto update_result = collection.UpdateOne(filter, update);
EXPECT_EQ(update_result.ModifiedCount(), 1);
// Delete one document
auto delete_filter = bson::MakeDoc("name", "user_4");
auto delete_result = collection.DeleteOne(delete_filter);
EXPECT_EQ(delete_result.DeletedCount(), 1);
// Commit all operations
txn.Commit();
Note
Transactions require MongoDB replica sets or sharded clusters.
A transient transaction error requires retrying the whole transaction. An unknown commit result requires retrying commit on the same transaction.

Definition at line 39 of file transaction.hpp.

Public Types

enum class  State {
  kNone ,
  kInProgress ,
  kCommitted ,
  kAborted ,
  kCommitUnknown
}
 Get the transaction state. More...

Public Member Functions

 Transaction ()
 Creates invalid transaction.
 Transaction (Transaction &&) noexcept
 Move constructor.
Transaction & operator= (Transaction &&) noexcept
 Move assignment operator.
 ~Transaction ()
 Aborts an active transaction or releases an unresolved commit session.
Collection GetCollection (std::string name)
 Get a collection handle within the transaction context.
void Commit ()
 Commit the transaction.
void Abort () noexcept
 Abort the transaction.
bool IsActive () const noexcept
 Check whether the transaction is in progress.
State GetState () const noexcept
 Get current transaction state.

Member Enumeration Documentation

◆ State

Get the transaction state.

Enumerator
kNone 

Transaction not started.

kInProgress 

Transaction is active.

kCommitted 

Transaction has been committed.

kAborted 

Transaction has been aborted.

kCommitUnknown 

Commit outcome is unknown; collection operations are forbidden.

Definition at line 92 of file transaction.hpp.

Member Function Documentation

◆ Abort()

void storages::mongo::Transaction::Abort ( )
noexcept

Abort the transaction.

Discards all changes made within the transaction. This method is idempotent and safe to call multiple times. If the commit result is unknown, releases the session without reporting a rollback or changing storages::mongo::Transaction::State::kCommitUnknown. Commit cannot be retried after the session has been released.

◆ Commit()

void storages::mongo::Transaction::Commit ( )

Commit the transaction.

Makes all changes within the transaction permanent and visible to other operations. If the transaction fails to commit, an exception will be thrown.

Exceptions
MongoExceptionon commit failure
storages::mongo::TransactionExceptionwith storages::mongo::TransactionException::Type::kUnknownCommitResult if the outcome is unknown. Retains the session for another commit attempt; collection operations are forbidden until the outcome is resolved.

◆ GetCollection()

Collection storages::mongo::Transaction::GetCollection ( std::string name)

Get a collection handle within the transaction context.

Parameters
namecollection name
Returns
Collection handle that operates within this transaction

◆ IsActive()

bool storages::mongo::Transaction::IsActive ( ) const
noexcept

Check whether the transaction is in progress.

Returns
true only in storages::mongo::Transaction::State::kInProgress.
Note
Returns false when the commit outcome is unknown. Commit may still be retried while the session is retained.

The documentation for this class was generated from the following file: