In Django nested transactions - “with transaction.atomic()” the question is, given this...
def functionA():
with transaction.atomic():
#save something
functionB()
def functionB():
with transaction.atomic():
#save another thing
If functionB
fails and rolls back, does functionA
roll back too?
Kevin Christopher Henry replies with, "Yes, if an exception happens in either function they will both be rolled back." He then quotes the docs, which state:
atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point.
This documentation quote doesn't seem to address the original question. The doc is saying that when the INNER BLOCK (which is functionB
) completes successfully, its effects can still be rolled back if the OUTER block (which is functionA) raises an exception. But the question refers to the opposite scenario. The question asks, if the INNER block (functionB
) FAILS, is the OUTER block (functionA
) rolled back? This doc quote doesn't address that scenario.
However, further down in the doc we see this example...
from django.db import IntegrityError, transaction
@transaction.atomic
def viewfunc(request):
create_parent()
try:
with transaction.atomic():
generate_relationships()
except IntegrityError:
handle_exception()
add_children()
...followed by this commentary...
In this example, even if
generate_relationships()
causes a database error by breaking an integrity constraint, you can execute queries inadd_children()
, and the changes fromcreate_parent()
are still there.
If I'm reading the doc correctly it's saying the call to generate_relationships()
(which is analogous to the call to functionB
in the original question) can FAIL and the changes made in create_parent()
and add_children()
will be committed to the database. This seems to contradict Kevin Christopher Henry's answer.
What's puzzling to me is that I see the same question/answer in Django nested Transaction.atomic.
I'm new to both Django and stackoverflow, so I don't have a lot of confidence in my reading of the doc, but it seems to contradict both of these responses. I'm looking for some clarification from someone more experienced. Thanks you so much.