Skip to content

Transactions

mongo_ops.transactions

Summary

Transaction management helpers for MongoDB.

Classes

TransactionManager

Simplified multi-document transaction handling.

This class provides helpers for executing operations within a MongoDB transaction, ensuring ACID compliance for multi-document updates.

Functions
execute_transaction async classmethod
1
2
3
4
5
6
7
8
execute_transaction(
    operations: list[
        Callable[
            [AsyncIOMotorClientSession], Awaitable[Any]
        ]
    ],
    **kwargs: Any
) -> list[Any]

Execute multiple operations within a single transaction.

Parameters:

Name Type Description Default
operations List[Callable[[AsyncIOMotorClientSession], Awaitable[Any]]]

A list of async callables that accept a session parameter and return a result.

required
**kwargs Any

Transaction options.

{}

Returns:

Type Description
list[Any]

List[Any]: A list containing the results of each operation.

Example

results = await TransactionManager.execute_transaction([ lambda s: repo1.create(data1, session=s), lambda s: repo2.update(id, data2, session=s), ])

start_session async classmethod
1
2
3
start_session(
    **kwargs: Any,
) -> AbstractAsyncContextManager[AsyncIOMotorClientSession]

Start a transaction session as an async context manager.

Notes

Yields the active session with a started transaction; callers run their operations against the session inside the with-block.

Usage

async with TransactionManager.start_session() as session: await collection.insert_one(doc, session=session) await other_collection.update_one(filter, update, session=session)