Transaction Documentation Clarification

23 views
Skip to first unread message

Silvio

unread,
Feb 17, 2011, 11:33:00 AM2/17/11
to Django developers
Hello all,

I recently switched to using transactions, and found Django's offering
to be excellent. I was just wondering if we could clarify a small bit
of the documentation - or whether I simply misunderstood it.

When using @transaction.commit_manually, one needs to ROLLBACK or
COMMIT, otherwise the transaction handler will raise the
TransactionManagementError error. That much is clear. But does this
mean the *entire* view needs to be wrapped in a massive "try/except/
else" block? I ask because, if any kind of exception occurs after the
transaction has started, I'll be presented with
TransactionManagementError rather than the exception. This makes
debugging a bit hard.

So basically, the following code:

@transaction.commit_manually
def some_view(request):
SomeModel.objects.all() # To trigger the start of a transaction.
some_function_that_could_raise_an_exception()
transaction.commit()

will always show the TransactionManagementError if an exception occurs
unless we do:

@transaction.commit_manually
def some_view(request):
try:
SomeModel.objects.all() # To trigger the start of a
transaction.
some_function_that_could_raise_an_exception()
# Rest of view body. This could be tons of lines.
except Exception as e:
transaction.rollback()
raise e
else:
transaction.commit()

return HttpResponse("Made it through the view with no errors")


The documentation *does* show a try/except/else block[1], but I found
it a bit unclear that any and all exceptions need to be caught, the
transaction rolled back, and the exception raised again.

Let me know your thoughts. As always, thanks a lot for the hard work.
Just tried class-based views in 1.3, and they're awesome.

Silvio

[1] http://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.commit_manually

Christophe Pettus

unread,
Feb 17, 2011, 11:58:42 AM2/17/11
to django-d...@googlegroups.com

On Feb 17, 2011, at 8:33 AM, Silvio wrote:
> When using @transaction.commit_manually, one needs to ROLLBACK or
> COMMIT, otherwise the transaction handler will raise the
> TransactionManagementError error. That much is clear. But does this
> mean the *entire* view needs to be wrapped in a massive "try/except/
> else" block?

Essentially, yes. You've diagnosed it exactly: If an exception escapes a view function with manual transaction management, and a transaction is left open, the exception that escaped will be discarded, and a TransactionManagementError exception thrown instead.

--
-- Christophe Pettus
x...@thebuild.com

Reply all
Reply to author
Forward
0 new messages