SQLAlchemy Transaction Isolation Level

Set per-session isolation levels in SQLAlchemy, using repeatable read for consistent reports and read committed for regular traffic.

PythonData Integrity

Code

pythonsnippet
42 lines
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session

engine = create_engine(
    'postgresql+psycopg://user:pass@localhost/reporting',
    isolation_level='READ COMMITTED',
    pool_size=10,
    max_overflow=5,
    pool_pre_ping=True,
)

reporting_engine = engine.execution_options(
    isolation_level='REPEATABLE READ'
)


def transfer_funds(session: Session, src: int, dst: int, amount: int) -> None:
    session.execute(
        text('UPDATE accounts SET balance = balance - :amt WHERE id = :id'),
        {'amt': amount, 'id': src},
    )
    row = session.execute(
        text('SELECT balance FROM accounts WHERE id = :id'),
        {'id': src},
    ).scalar_one()
    if row < 0:
        raise ValueError('overdraft rejected')
    session.execute(
        text('UPDATE accounts SET balance = balance + :amt WHERE id = :id'),
        {'amt': amount, 'id': dst},
    )


with Session(engine) as session:
    with session.begin():
        transfer_funds(session, src=1, dst=2, amount=75)

with Session(reporting_engine) as session:
    snapshot = session.execute(
        text('SELECT sum(balance) FROM accounts')
    ).scalar_one()
    print('consistent snapshot total:', snapshot)

What the code does

SQLAlchemy Transaction Isolation Level is built around the function transfer_funds.

The import line is the dependency contract: create_engine, text, Session come from sqlalchemy and nothing else. A guard precedes the ValueError: bad state stops the flow there instead of continuing.

What to watch for

  • Requires sqlalchemy as a package; the snippet will not run without it.
  • The guard row < 0 short-circuits the flow with an early raise when its condition holds.

Using it

The primary signature is def transfer_funds(session: Session, src: int, dst: int, amount: int) -> None

The demo output is labeled (consistent snapshot total:), so every printed line maps back to its originating operation.

Import transfer_funds from the file and call it — the rest of the code is implementation detail.

Key statements

with Session(reporting_engine) as session:
    snapshot = session.execute(
        text('SELECT sum(balance) FROM accounts')
    ).scalar_one()
    print('consistent snapshot total:', snapshot)
with Session(engine) as session:
    with session.begin():
        transfer_funds(session, src=1, dst=2, amount=75)

Interactive Tools for This Topic

FAQ

What happens on invalid input?
`ValueError` is raised at the guard (`row < 0`), so invalid state never reaches the main logic.
Do I need to install anything before running this?
Yes: `sqlalchemy` must be present in the project or the import fails at load time.