Skip to content

Commit

Permalink
Only roll-back in outermost @transaction decorator/ctx manager.
Browse files Browse the repository at this point in the history
See #2767 for discussion.
  • Loading branch information
coleifer committed Aug 17, 2023
1 parent 2c954f2 commit 278c24d
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
7 changes: 5 additions & 2 deletions docs/peewee/database.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1656,8 +1656,11 @@ block. When this happens, a new transaction will be started.
.. note::
If you attempt to nest transactions with peewee using the
:py:meth:`~Database.transaction` context manager, only the outer-most
transaction will be used. However if an exception occurs in a nested block,
this can lead to unpredictable behavior, so it is strongly recommended that
transaction will be used. If an exception occurs in a nested block, the
transaction will NOT be rolled-back -- only exceptions that bubble-up to
the outer-most transaction will trigger a rollback.

As this can may lead to unpredictable behavior, it is recommended that
you use :py:meth:`~Database.atomic`.

Explicit Savepoints
Expand Down
5 changes: 3 additions & 2 deletions peewee.py
Original file line number Diff line number Diff line change
Expand Up @@ -4405,10 +4405,11 @@ def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
depth = self.db.transaction_depth()
try:
if exc_type:
if exc_type and depth == 1:
self.rollback(False)
elif self.db.transaction_depth() == 1:
elif depth == 1:
try:
self.commit(False)
except:
Expand Down
11 changes: 11 additions & 0 deletions tests/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ def test_nesting_transaction_obj(self):

self.assertRegister([3, 4, 5])

with db.transaction() as txn:
self._save(6)
try:
with db.transaction() as txn2:
self._save(7)
raise ValueError()
except ValueError:
pass

self.assertRegister([3, 4, 5, 6, 7])

@requires_nested
def test_savepoint_commit(self):
with db.atomic() as txn:
Expand Down

0 comments on commit 278c24d

Please sign in to comment.