Recipe 17.3 · Python
One Transaction for a Multi-Table Insert Procedure
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
Saving an incident in CFATS Manager touches several tables: the incident row, a row linking the incident to its facility, and a person row for "reported to" (found or created by name). The work is spread across a chain of procedures, and none of them uses a transaction. If any step fails after the first insert, you get an orphaned incident that belongs to no facility and never appears on any screen.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
From CFATS Manager, re-wrapped. The USE line is removed and the parameter names are as they were.
-- From CFATS Manager: CFATSDatabase\StoredProcedure\
-- dbo.InsertFacilityIncidentDefault.StoredProcedure.sql
-- (re-wrapped, abridged)
CREATE PROCEDURE [dbo].[InsertFacilityIncidentDefault]
@IncidentID int output, @FacilityID int,
@II_rblIncidentTypeNo int, @II_txtIncidentName varchar(100),
@II_txtOccurenceDate datetime, @II_txtLocation varchar(200),
@II_txtReportedTo varchar(200),
@II_txtDescription varchar (500),
@II_txtResponse varchar(500),
@II_propFileGUID uniqueidentifier
AS
BEGIN
-- Usage: Called from IncidentInput.aspx, abbreviation
-- prefix is II for page controls
-- Format: PageName_ControlName_Function
SET NOCOUNT ON
SET ANSI_NULLS ON
DECLARE @Result int,@Nothing int
EXECUTE @Result = InsertIncidentDefault @IncidentID OUTPUT,
@II_rblIncidentTypeNo, @II_txtIncidentName,
-- ...
@II_propFileGUID
INSERT INTO tblFacilityIncident(FacilityID,IncidentID)
VALUES(@FacilityID,@IncidentID)
END
InsertIncidentDefault in turn calls InsertIncidentBasic to insert the row, FindPersonID to find or create the person, and then runs an UPDATE to fill in the remaining columns. That's four procedures and four separate commits for one save. The parameter names carry the page prefix and the control type (II_txt, II_rbl), which ties the database to one ASP.NET form. The threat and near-miss forms have their own copies with TI_ and other prefixes.
The improved recipe
T-SQL for SQL Server 2016 or later (CREATE OR ALTER needs 2016 SP1).
CREATE OR ALTER PROCEDURE dbo.Incident_Insert
@FacilityID int,
@IncidentTypeNo int,
@Name varchar(100),
@OccurredAt datetime2(0),
@Location varchar(200) = NULL,
@ReportedTo varchar(200) = NULL,
@Description varchar(500) = NULL,
@Response varchar(500) = NULL,
@FileGUID uniqueidentifier = NULL,
@IncidentID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ReportedToPersonID int = NULL;
BEGIN TRY
BEGIN TRANSACTION;
IF @ReportedTo IS NOT NULL
EXEC dbo.FindPersonID
@PersonID = @ReportedToPersonID OUTPUT,
@Name = @ReportedTo,
@PersonType = 'IncidentReportedTo';
INSERT INTO dbo.tblIncident
(IncidentTypeNo, Name, OccurenceDate, Location,
ReportedToPersonID, Description, Response, FileGUID)
VALUES
(@IncidentTypeNo, @Name, @OccurredAt, @Location,
@ReportedToPersonID, @Description, @Response, @FileGUID);
SET @IncidentID = SCOPE_IDENTITY();
INSERT INTO dbo.tblFacilityIncident (FacilityID, IncidentID)
VALUES (@FacilityID, @IncidentID);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
THROW;
END CATCH;
END;
The C# side implements IIncidentStore from Recipe 17.2. Packages: Microsoft.Data.SqlClient.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Insert an incident through one transactional stored procedure and return its new id
Source: ImproveCode, Chapter 17, Recipe 17.3 "One Transaction for a Multi-Table Insert Procedure"
Section: The improved recipe
Book page: 392-393 -- original C# listing
Converted from C# to Python.
SqlCommand(StoredProcedure) becomes aioodbc; ODBC has no OUTPUT parameters, so the
procedure is called from a T-SQL batch that declares @IncidentID and SELECTs it back.
Parameter lengths (VarChar 100/200/500) are enforced by the procedure's own signature.
"""
from datetime import UTC
from typing import Protocol
from p383_r17_1_parameterized_incident_repository import SqlConnectionFactory
from p387_r17_2_incident_service_result_validation import IncidentKind, NewIncident
_INSERT = """
SET NOCOUNT ON;
DECLARE @IncidentID int;
EXEC dbo.Incident_Insert
@FacilityID = ?,
@IncidentTypeNo = ?,
@Name = ?,
@OccurredAt = ?,
@Location = ?,
@ReportedTo = ?,
@Description = ?,
@Response = ?,
@FileGUID = ?,
@IncidentID = @IncidentID OUTPUT;
SELECT @IncidentID;
"""
class IncidentTypeLookup(Protocol):
def get_type_no(self, kind: IncidentKind) -> int: ...
class SqlIncidentStore:
def __init__(self, db: SqlConnectionFactory, types: IncidentTypeLookup) -> None:
self._db = db
self._types = types
async def insert(self, i: NewIncident) -> int:
params = (
i.facility_id,
self._types.get_type_no(i.kind),
i.name,
i.occurred_at.astimezone(UTC).replace(tzinfo=None), # DateTime2, UTC
self._db_value(i.location),
self._db_value(i.reported_to),
self._db_value(i.description),
self._db_value(i.response),
str(i.file_id) if i.file_id is not None else None,
)
conn = await self._db.create()
try:
async with conn.cursor() as cur:
await cur.execute(_INSERT, params)
row = await cur.fetchone()
await conn.commit()
finally:
await conn.close()
return int(row[0])
@staticmethod
def _db_value(s: str | None) -> str | None:
return None if s is None or not s.strip() else s
How it works
BEGIN TRANSACTION wraps the person lookup and both inserts, so they commit together or not at all. FindPersonID runs inside the same transaction. If the facility link fails, the person it just created is rolled back too. I tested exactly that case against LocalDB by forcing a primary-key violation on the link table: the incident and person counts were unchanged afterwards.
SET XACT_ABORT ON makes any run-time error doom the transaction, including a client timeout that never reaches the CATCH block. THROW with no arguments re-raises the original error number and message, so the C# caller gets a real SqlException instead of a return code nobody checked.
Parameter names describe data, not controls. The same procedure now serves the incident form, a future API and a bulk import. datetime2(0) replaces datetime, and the C# side sends UTC.
The insert happens in one statement instead of an insert followed by an update, so no reader ever sees a half-filled row.
Variations and pitfalls
- Threats and near misses. Add
@CommunicatedByand@IdentifiedByas optional parameters with two moreFindPersonIDcalls, and delete the per-form copies. FindPersonIDis simplified here. The product's version takes six positional parameters, including flags that control usage counts. Call any helper procedure with named parameters, as above, so a signature change fails loudly.- Find-or-create by name is a race. Two saves naming the same new person at once can create two rows. Add a unique index on the natural key and catch error 2627 in the helper, or use
MERGEwithHOLDLOCK(Chapter 2). - Scripts with
USE [DevDatabase]at the top. Every script in the old database project starts withUSEand the development database's name, because they were generated from Management Studio. Deploying one to production runs it against the wrong database or fails. StripUSElines and let the deployment tool pick the database.