CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tortoise-orm

Easy async ORM for Python, built with relations in mind

Overview
Eval results
Files

transactions.mddocs/

Transaction Management

Database transaction support for ensuring data consistency across multiple operations. Provides both context manager and decorator approaches for transaction handling.

Capabilities

Transaction Context Manager

Context manager for running code within a database transaction.

from tortoise.transactions import in_transaction

def in_transaction(connection_name=None):
    """
    Transaction context manager.
    
    Run code inside async with in_transaction() to execute within one transaction.
    If error occurs, transaction will rollback.
    
    Args:
        connection_name (str, optional): Name of connection to use.
                                       Required if multiple databases configured.
    
    Returns:
        TransactionContext: Context manager for transaction
    """

Transaction Decorator

Decorator for wrapping functions in database transactions.

from tortoise.transactions import atomic

def atomic(connection_name=None):
    """
    Transaction decorator.
    
    Wrap functions with this decorator to run them within one transaction.
    If function raises exception, transaction will rollback.
    
    Args:
        connection_name (str, optional): Name of connection to use.
                                       Required if multiple databases configured.
    
    Returns:
        Function decorator for transaction handling
    """

Usage Examples

Context Manager Usage

from tortoise.transactions import in_transaction
from myapp.models import User, Profile

async def create_user_with_profile():
    async with in_transaction():
        # All operations within this block run in same transaction
        user = await User.create(name="Alice", email="alice@example.com")
        profile = await Profile.create(user=user, bio="Software Engineer")
        
        # If any operation fails, entire transaction rolls back
        return user

Decorator Usage

from tortoise.transactions import atomic
from myapp.models import User, Order

@atomic()
async def process_order(user_id, items):
    """Process order atomically."""
    user = await User.get(id=user_id)
    
    # Deduct balance
    total_cost = sum(item.price for item in items)
    if user.balance < total_cost:
        raise ValueError("Insufficient balance")
    
    user.balance -= total_cost
    await user.save()
    
    # Create order
    order = await Order.create(user=user, total=total_cost)
    
    # If any step fails, all changes are rolled back
    return order

Multiple Database Connections

from tortoise.transactions import in_transaction, atomic

# Specify connection for multiple database setup
async def multi_db_operation():
    async with in_transaction("users_db"):
        await User.create(name="Alice")
    
    async with in_transaction("orders_db"):  
        await Order.create(total=100)

@atomic("analytics_db")
async def update_analytics():
    # Transaction on specific database
    await AnalyticsRecord.create(event="user_signup")

Transaction Behavior

Rollback Conditions

Transactions automatically rollback when:

  • Any unhandled exception is raised within the transaction
  • Database constraint violations occur
  • Connection errors happen during the transaction

Nested Transactions

Tortoise ORM handles nested transactions using database savepoints:

async with in_transaction():
    await User.create(name="Alice")
    
    try:
        async with in_transaction():  # Nested transaction (savepoint)
            await User.create(name="Bob")
            raise Exception("Something went wrong")
    except:
        pass  # Inner transaction rolled back to savepoint
    
    # Outer transaction continues
    await User.create(name="Charlie")  # This will still be committed

Connection Management

  • If no connection_name specified, uses default connection
  • With single database, automatically uses that connection
  • With multiple databases, connection_name is required
  • Raises ParamsError if connection specification is ambiguous

Install with Tessl CLI

npx tessl i tessl/pypi-tortoise-orm

docs

database.md

exceptions.md

functions.md

index.md

integration.md

models.md

querying.md

signals.md

transactions.md

validators.md

tile.json