Recipe 1.5 · Python
Transactions That Commit or Roll Back
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
An order header and its lines must be saved together. Without a transaction, a failure after the header insert leaves an order with no lines. With a carelessly written transaction, a failure leaves the transaction open, holding locks, until the connection is reset.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
The line command is missing its transaction argument, so SQL Server throws an error saying the command must have a transaction when the connection has a pending one. When that exception escapes, nothing rolls back, and nothing closes the connection.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Transaction with an unenlisted command and no rollback
Source: ImproveCode, Chapter 1, Recipe 1.5 "Transactions That Commit or Roll Back"
Section: The way it's often written
Book page: 29 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
pyodbc has no per-command transaction object, so "not enlisted" is reproduced by running the
line inserts on a second autocommit connection; nothing rolls back or closes on failure.
"""
from typing import Any
import pyodbc
def create_order(conn_str: str, insert_header: str, insert_line: str,
lines: list[Any]) -> int:
# Not to copy: the second command is not enlisted,
# and nothing rolls back on failure.
conn = pyodbc.connect(conn_str, autocommit=False)
tx = conn # BeginTransaction(): pyodbc's implicit transaction
header = conn.cursor()
header.execute(insert_header)
order_id = int(header.fetchone()[0])
other = pyodbc.connect(conn_str, autocommit=True)
for line in lines:
cmd = other.cursor()
# ... add parameters, execute()
tx.commit()
conn.close()
return order_id
The improved recipe
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Insert an order header and lines in one transaction
Source: ImproveCode, Chapter 1, Recipe 1.5 "Transactions That Commit or Roll Back"
Section: The improved recipe
Book page: 29-30 -- original C# listing
Converted from C# to Python.
SqlTransaction -> aioodbc connection with autocommit off plus explicit commit()/rollback();
typed parameters via TypedParams (Recipe 1.2 file); rollback is shielded from cancellation,
mirroring RollbackAsync(CancellationToken.None).
"""
import asyncio
from dataclasses import dataclass
from decimal import Decimal
from p020_r1_2_typed_sql_parameters_lookup import DbConnectionFactory, TypedParams
@dataclass(frozen=True)
class NewOrderLine:
product_id: int
quantity: int
unit_price: Decimal
class OrderWriter:
INSERT_HEADER_SQL = """
INSERT INTO dbo.SalesOrder (CustomerId, OrderedUtc)
OUTPUT INSERTED.OrderId
VALUES (?, SYSUTCDATETIME());
"""
INSERT_LINE_SQL = """
INSERT INTO dbo.SalesOrderLine
(OrderId, ProductId, Quantity, UnitPrice)
VALUES (?, ?, ?, ?);
"""
def __init__(self, db: DbConnectionFactory) -> None:
self._db = db
async def create(self, customer_id: int, lines: list[NewOrderLine]) -> int:
async with await self._db.open() as connection:
await connection.set_autocommit(False) # begin transaction
try:
async with connection.cursor() as header:
p = TypedParams().add_int("@CustomerId", customer_id)
await p.apply(header)
await header.execute(self.INSERT_HEADER_SQL, *p.values)
order_id = int((await header.fetchone())[0])
for line in lines:
async with connection.cursor() as command:
p = (TypedParams()
.add_int("@OrderId", order_id)
.add_int("@ProductId", line.product_id)
.add_int("@Quantity", line.quantity)
.add_decimal("@UnitPrice", 19, 4, line.unit_price))
await p.apply(command)
await command.execute(self.INSERT_LINE_SQL, *p.values)
await connection.commit()
return order_id
except BaseException:
await asyncio.shield(connection.rollback())
raise
How it works
One connection, one transaction, and every command created with both. The try block ends in CommitAsync. Any exception before that point lands in the catch, which rolls back and rethrows the original exception with throw; so the stack trace survives. The rollback deliberately ignores the caller's cancellation token: if the request was cancelled, you still want the rollback to finish.
await using on the transaction is a second safety net. Disposing a transaction that was neither committed nor rolled back rolls it back. OUTPUT INSERTED.OrderId returns the new identity value in the same statement, which avoids the classic @@IDENTITY bug where a trigger's insert returns the wrong ID.
Variations and pitfalls
- Many lines? A loop of inserts is fine for an order with ten lines. For hundreds, pass the lines as a table-valued parameter (Recipe 1.6) and insert them in one statement.
- Keep transactions short. Do not call a web service, send e-mail or wait for user input while a transaction is open. Locks are held until commit.
TransactionScope. It works withMicrosoft.Data.SqlClient, but with async code you must create it asnew TransactionScope(TransactionScopeAsyncFlowOption.Enabled), or the ambient transaction will not flow acrossawait. Opening a second connection inside the scope can promote it to a distributed transaction, which needs MSDTC on .NET Framework and is only partly supported on modern .NET. I use explicitSqlTransactionunless I truly need to span several connections.- Transactions in procedures. If the whole unit of work is in one stored procedure, keep the transaction in the procedure and use
SET XACT_ABORT ON. Chapter 2 has the template.