示例工程 31-io-files-struct-socket-sqlite

31-io-files-struct-socket-sqlite/06-sqlite-transaction/sqlite_transaction.py

python · 1.4 KB

"""用 with conn 演示事务提交/回滚。"""
 
from __future__ import annotations
 
import sqlite3
from contextlib import suppress
 
 
def setup() -> sqlite3.Connection:
    connection = sqlite3.connect(":memory:")
    connection.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)")
    connection.executemany(
        "INSERT INTO accounts VALUES (?, ?)",
        [(1, 100), (2, 50)],
    )
    connection.commit()
    return connection
 
 
def transfer(connection: sqlite3.Connection, amount: int, fail: bool = False) -> None:
    with connection:
        connection.execute(
            "UPDATE accounts SET balance = balance - ? WHERE id = 1",
            (amount,),
        )
        if fail:
            raise RuntimeError("simulated failure")
        connection.execute(
            "UPDATE accounts SET balance = balance + ? WHERE id = 2",
            (amount,),
        )
 
 
def balances(connection: sqlite3.Connection) -> list[int]:
    return [row[0] for row in connection.execute("SELECT balance FROM accounts ORDER BY id")]
 
 
def main() -> None:
    connection = setup()
    try:
        transfer(connection, 10)
        print(f"after ok: {balances(connection)}")
        with suppress(RuntimeError):
            transfer(connection, 20, fail=True)
        print(f"after fail: {balances(connection)}")
    finally:
        connection.close()
 
 
if __name__ == "__main__":
    main()