In this article
An import can return “failed” after saving half its rows. Review the transaction boundary as carefully as the error message. This SQLite example reproduces the partial write and repairs it by letting the transaction observe the failure before the caller handles it.
Define what an atomic import promises
Suppose an inventory import accepts several product rows. The requirement is all or nothing: either every row is saved, or the database remains as it was before the batch. A friendly error response is a separate requirement. Returning false cannot undo a successful insert that the transaction has already committed.
For this original exercise, product names are unique and quantities must be nonnegative. The database initially contains pear with quantity three. Importing apple followed by another pear must reject the batch and leave only the original pear. This is a stronger assertion than checking that an exception occurred somewhere during the request.
Python’s SQLite connection context commits on successful exit and rolls back when an uncaught exception leaves the block. We explicitly use autocommit=False, available in Python 3.12 and later. With autocommit=True the context manager does not provide this behavior. Python: SQLite connection context manager
Run the failure and the repaired import
Run this complete example with Python 3.12 or newer. Each reproduction uses a fresh in-memory connection. The fixture commits its starting state before either import runs. The repaired function catches the expected constraint failure outside the transaction block, after rollback has occurred. Other exception types remain visible to the caller.
The assertions inspect rows in a fixed order. They first demonstrate the bad persisted result, then check rollback for a duplicate and for a negative quantity, and finally check a successful batch. The iterator failure also verifies that an unrelated exception is propagated after undoing an earlier insert.
import sqlite3
SQL = "INSERT INTO inventory(name, quantity) VALUES (?, ?)"
def database():
con = sqlite3.connect(":memory:", autocommit=False)
con.execute("""CREATE TABLE inventory(
name TEXT NOT NULL UNIQUE,
quantity INTEGER NOT NULL CHECK(quantity >= 0)
)""")
con.execute(SQL, ("pear", 3))
con.commit()
return con
def rows(con):
return con.execute(
"SELECT name, quantity FROM inventory ORDER BY name"
).fetchall()
def broken_import(con, batch):
with con:
try:
con.executemany(SQL, batch)
except sqlite3.IntegrityError:
return False # The context sees a normal exit.
return True
def import_batch(con, batch):
# Owns this connection's transaction: no unrelated pending writes.
try:
with con:
con.executemany(SQL, batch)
except sqlite3.IntegrityError:
return False
return True
bad = database()
try:
assert broken_import(bad, [("apple", 2), ("pear", 9)]) is False
assert rows(bad) == [("apple", 2), ("pear", 3)]
finally:
bad.close()
good = database()
try:
assert import_batch(good, [("apple", 2), ("pear", 9)]) is False
assert rows(good) == [("pear", 3)]
assert import_batch(good, [("apple", 2), ("plum", -1)]) is False
assert rows(good) == [("pear", 3)]
def interrupted_rows():
yield ("apple", 2)
raise RuntimeError("input reader stopped")
try:
import_batch(good, interrupted_rows())
except RuntimeError as error:
assert str(error) == "input reader stopped"
else:
raise AssertionError("unexpected error was swallowed")
assert rows(good) == [("pear", 3)]
assert import_batch(good, [("apple", 2), ("plum", 4)]) is True
assert rows(good) == [("apple", 2), ("pear", 3), ("plum", 4)]
assert import_batch(good, []) is True
print("Atomic import checks passed")
finally:
good.close()Make transaction ownership part of the contract
The repaired helper owns the entire transaction on the supplied connection. Its caller must not have unrelated pending writes. If another operation had inserted a customer before calling this helper, success could commit that customer and failure could roll it back. That would violate the boundary a reader expects from a function named import_batch.
For this small design, give the import a dedicated connection or call it only at the application’s transaction boundary. If a larger workflow needs several operations in one transaction, move ownership to that workflow and make inner helpers propagate failures. Merely nesting connection context blocks does not establish independent nested transactions.
Review cleanup separately. The SQLite connection context manages commit and rollback but does not close the connection, so the example closes it explicitly in finally. Python: SQLite connection context manager Connection lifetime and transaction lifetime can be different; making both visible helps an assistant preserve them when it rearranges error handling.
Ask for evidence about state after failure
A useful review prompt is: “Show the database contents after the second row fails, explain which scope receives the exception, and preserve the all-or-nothing contract.” Supply the connection configuration and the caller. Without those details, an assistant can produce a locally plausible helper with incompatible assumptions about transaction ownership.
Keep the smallest failing batch at two rows. If the first row fails, no earlier write exists to expose the bug. Add a third valid row only when you need to show that execution stops at the failing row. Arrange the duplicate after a successful insert and compare the full resulting state against the committed fixture.
Then inspect the patch for other changes: switching to an ignore-conflicts statement, committing inside the loop, swallowing every Exception, or removing a constraint. Each could make the command finish while changing the promised behavior. The intended repair changes when the expected error is handled, not whether the bad row is acceptable.
The Python with-statement rules also mean cleanup can run while an error continues outward. Handling an error after the transaction exits does not mean skipping rollback. Python language reference: the with statement Use that separation to translate an expected validation failure at the application boundary while preserving unexpected failures for diagnosis.
Common questions about atomic imports
Does a transaction also undo an email or an HTTP request? This example has only database effects. If a loop sends notifications before commit, rolling back rows will not recall those notifications. A real design needs a separately considered delivery strategy; do not infer cross-system atomicity from a successful SQLite test.
Should every IntegrityError become the same user message? The boolean is deliberately small for this exercise. A product may need stable, specific error codes for duplicate names and invalid quantities. Build that mapping after rollback and avoid exposing raw database details. The related API error guide covers that separate response contract.
Is rollback the same as safe retries? No. Rollback restores this failed transaction’s database state. If a complete successful request is delivered twice, the second request still needs a defined policy. Practice atomicity here, then use the related retry guide to examine duplicate delivery and the identity of an operation.
Sources & editorial notes
This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.
- Python: SQLite connection context manager
Python 3.14 SQLite documentation on explicit transaction control and connection context behavior. Checked November 4, 2026.
- Python language reference: the with statement
Python language reference for exception propagation and the with statement. Checked November 4, 2026.
Put the reading into practice
Work through an existing repository, review AI suggestions, and test the decisions behind your changes.
Explore practice problems