"""事务:成功提交、异常回滚。""" from __future__ import annotations from contextlib import suppress from sqlalchemy import ( Column, Engine, Integer, MetaData, Table, create_engine, insert, select, update, ) def build() -> tuple[Engine, Table]: engine = create_engine("sqlite:///:memory:") metadata = MetaData() accounts = Table( "accounts", metadata, Column("id", Integer, primary_key=True), Column("balance", Integer, nullable=False), ) metadata.create_all(engine) with engine.begin() as connection: connection.execute(insert(accounts), [{"id": 1, "balance": 100}, {"id": 2, "balance": 50}]) return engine, accounts def transfer( engine: Engine, accounts: Table, amount: int, fail: bool = False, ) -> None: with engine.begin() as connection: connection.execute( update(accounts).where(accounts.c.id == 1).values(balance=accounts.c.balance - amount) ) if fail: raise RuntimeError("simulated failure") connection.execute( update(accounts).where(accounts.c.id == 2).values(balance=accounts.c.balance + amount) ) def balances(engine: Engine, accounts: Table) -> list[int]: with engine.connect() as connection: rows = connection.execute(select(accounts.c.balance).order_by(accounts.c.id)).all() return [row[0] for row in rows] def main() -> None: engine, accounts = build() transfer(engine, accounts, 10) print(f"after ok: {balances(engine, accounts)}") with suppress(RuntimeError): transfer(engine, accounts, 20, fail=True) print(f"after fail: {balances(engine, accounts)}") if __name__ == "__main__": main()