The library now has its own errors, and save() and save_all() are written
against a transaction() that doesn't exist yet. Sixteen tests describe it.
The checkpoint
Day 4 checkpoint: all or nothing
transactions.py gives you three helpers — _rollback, _finish and
_translate — and an empty transaction. Write it so the whole suite passes,
including the tests that are about tidiness rather than correctness: the
driver's error must survive as __cause__, _depth must be empty once the
outermost transaction ends, a failure during commit must roll back too, and a
rollback that fails on its own must not replace the error that caused it.
When the supplied tests pass, add one test of your own to test_models.py, at the end of the Transactions class: save a batch of three posts whose last one repeats a title that's already taken. Check that none of the three new rows survive, and that a save right afterwards works. The rows can come back in any order, so compare sorted lists. It should pass. Then commit after each write instead of once at the end, check that your test fails, and undo the change. A sample test is at the end of the solution.
Hint 1: the idea
The shape from All or Nothing: begin (or a savepoint, when nested), yield,
finish; on any exception, roll back, translate, re-raise; and in a finally,
restore the depth. The helpers do each step — your job is where each one goes.
One placement matters above the rest: a commit can fail too, so it belongs
inside the try.
Hint 2: a first step
Start without nesting: begin, yield connection, _finish(...), and on
BaseException, _rollback(...) then raise. Get the plain commit and
rollback tests passing, then add the depth bookkeeping for savepoints, then
_translate, then the guard around the rollback that the TODO describes.
Show one solution
@contextmanager
def transaction(connection: Connection) -> Iterator[Connection]:
depth = _depth.get(connection, 0)
savepoint = f"orm_{depth}"
connection.execute("begin" if depth == 0 else f"savepoint {savepoint}")
_depth[connection] = depth + 1
try:
try:
yield connection
_finish(connection, depth, savepoint) # commit/release can fail
except BaseException as error:
try:
_rollback(connection, depth, savepoint)
except Exception as cleanup_error:
error.add_note( # keep it, don't raise it
f"rollback after this error also failed: {cleanup_error!r}")
_translate(error) # raises ours, or returns
raise
finally:
if depth:
_depth[connection] = depth
else:
_depth.pop(connection, None)The structure carries the whole lesson. _finish — the commit, or a savepoint
release — is inside the try, because a commit is exactly when a database
checks deferred constraints, so it can fail. A commit that raises is caught
here, rolled back, and translated like any other failure. Put _finish after
the try (in an else) and a failed commit escapes untranslated, leaving the
connection stuck in a transaction nobody can end. There is a whole test for that.
Inside the handler the order is roll back first, translate second. If the translation raised before the rollback, the transaction would stay open and the next statement on that connection would join a transaction nobody owns.
The rollback is guarded, and its failure becomes a note. The rollback can
fail for a dull reason: SQLite's INSERT OR ROLLBACK ends the transaction
itself, so by the time we try, there is nothing to roll back and we get
OperationalError: cannot rollback - no transaction is active. Let that
propagate and the caller sees the cleanup's complaint instead of the unique-
constraint violation that actually happened — the exact failure mode "Testing the Paths
That Fail" warns about. But swallowing it with a bare pass goes too far the other way: a
rollback that fails for a real reason means the connection may be unusable,
and that is worth knowing. add_note is the middle path. It attaches the
secondary error to the primary one, so the traceback shows both and the caller
still catches the error they expected.
sqlite3.IntegrityError: UNIQUE constraint failed: post.title
rollback after this error also failed: OperationalError('cannot rollback - no transaction is active')One consequence is easy to miss: because _translate raises a new exception,
it has to copy the notes across, or the one you just attached is lost at the
moment of translation. Remove the add_note, or drop the copy, and a test
turns red: try it.
_translate uses isinstance(error, errors.DRIVER_INTEGRITY_ERRORS) rather
than an except errors.DRIVER_INTEGRITY_ERRORS clause. Not because of when
the tuple is read — Python evaluates an except expression each time the clause
is reached, so an except clause would see the registered value too — but
because the tuple starts empty (except () would be dead until a driver
registers), and one broad handler that checks the current tuple reads more
plainly than a clause whose meaning depends on import order.
finally restores the previous depth rather than decrementing: after an
exception, "what it was before" is the only value that is definitely right.
A test of your own. One that does the job, inside Transactions:
def test_a_failure_at_the_end_undoes_the_whole_batch(self) -> None:
Post(title="taken", views=1).save(self.connection)
with self.assertRaises(IntegrityError):
Post.save_all(self.connection, [Post(title="a", views=1),
Post(title="b", views=1),
Post(title="taken", views=2)])
self.assertEqual(self.rows(), ["taken"])
Post(title="after", views=1).save(self.connection)
self.assertEqual(sorted(self.rows()), ["after", "taken"])The failure comes after two good writes, not one, and the last line proves the connection isn't left inside a dead transaction.
Bug hunt: a promise that doesn't scale
save() is all-or-nothing. So someone wrote save_all() the obvious way:
# Each save() is already all-or-nothing, so saving them one by one
# gives the same guarantee for the batch.
for obj in objects:
obj.save(connection)Find it, pin it, fix it
Find the cause yourself before you open the hints: read the failure, then add a print or two to narrow it down. Fix it in the playground until every test passes. Then add one regression test of your own to test_models.py, in the Transactions class: check that the good object in a failed batch is not left in Post._instances. Put the bug back for a moment and check that your test fails.
Reproduce. One failure:
AssertionError: Lists differ: ['first', 'second'] != ['first']
: the good row should have been rolled back tooThe test saved a valid post and a duplicate. The duplicate raised, as it
should. 'second' is still in the table.
Hint 1: the idea
Inspect. The comment in the code is the bug, written out in English. Each
save() opens its own transaction and commits it. By the time the second
object fails, the first one's transaction is finished — there is nothing left
to roll back.
Hint 2: a first step
Narrow. "All or nothing" is a property of a unit of work, and the unit here is the batch, not the row. Composing two atomic operations does not give you an atomic operation; it gives you two, and a gap in between.
Show one solution
Pin. test_save_all_is_all_or_nothing is the regression test, and its
message says what the caller is owed: the good row should have been rolled
back too is the behaviour being asserted.
Fix. One transaction around the whole batch:
written = list(objects)
with transaction(connection):
for obj in written:
obj._write(connection)
for obj in written:
obj._remember()Nesting is what makes this possible: _write does the SQL, and save() is
just _write wrapped in a transaction of its own. If save_all called
save() inside its own with, the savepoint machinery would handle it
correctly too — but doing the work once, at the right level, is clearer.
Your regression test. One that fails with the bug and passes after the fix, inside Transactions:
def test_a_failed_batch_caches_nothing(self) -> None:
Post(title="taken", views=1).save(self.connection)
fresh = Post(title="fresh", views=1)
with self.assertRaises(IntegrityError):
Post.save_all(self.connection, [fresh, Post(title="taken", views=2)])
self.assertNotIn(fresh, Post._instances.values())Why list(objects) first
objects is an Iterable, so it might be a generator. Consuming it inside the
with block and then iterating again afterwards to update the cache would find
it empty. Materialising it once, before the transaction opens, also means a
generator that raises does so outside the transaction.
The cache and the commit
Notice where _remember() happens: after the with block, never inside it.
def save(self, connection: Connection) -> Self:
with transaction(connection):
self._write(connection)
self._remember() # only once the write is committed
return selfPut it inside, and a rolled-back object stays in the identity map — so
Post.get(connection, 1) returns an object that doesn't exist in the database,
from memory, without ever running a query. That's the worst kind of bug: no
exception, no bad data on disk, just a library confidently answering with
something imaginary.
The test:
def test_a_failed_save_is_not_cached(self) -> None:
Post(title="first", views=1).save(self.connection)
doomed = Post(title="first", views=2)
with self.assertRaises(IntegrityError):
doomed.save(self.connection)
self.assertNotIn(doomed, Post._instances.values())There is a deeper version of this problem that the library does not solve: an object saved successfully inside an outer transaction that later rolls back is cached, wrongly. Fixing that means the cache has to participate in the transaction — deferring its updates until the outermost commit. It's a good exercise, and it's the sort of thing Day 7's write-up should name as a known limitation rather than leave for a user to discover.
Where Day 4 leaves the library
Working on your own machine? Download the Day 4 files.
One test in there is worth reading before you go, because it tests the test setup as much as the library:
def test_a_commit_really_reaches_the_file(self) -> None:
"""An in-memory database can't tell a commit from an open transaction."""Every other test uses :memory:, where an uncommitted transaction looks exactly
like a committed one from the same connection. One test with a real file, a
close and a re-open is what proves the commit happened at all.
What you learned
- Atomic operations don't compose: the unit of work is the batch, and it needs a transaction of its own.
- Roll back before translating an exception, or you leave the transaction open.
- Cache after the commit, never before — an identity map that remembers a rolled-back object answers from memory with something that never existed.
- In-memory databases hide commit bugs; one file-based test covers that.
Tomorrow is a day away from the ORM: asyncio, where "clean up on the way out" gets much harder because the way out might be a cancellation.