postgresql when it's not your job

11:32

‘Rollback’ exception added to Xact

23 June 2013

I often find that I’m in the middle of a loop or something and discover an error. I want to exit the loop in a way that causes the database work I’ve done within it to be rolled back, but I don’t want that exception to propagate further.

This usually looks like:

try:
   with xact():
      for thing in things:
         (etc. etc.)
 except Rollback:
     pass

Having noticed this pattern a lot, I’ve added it as a feature to Xact. Xact defines a Rollback exception. It processes it like any other exception, but then swallows it and normally exits the function or with clause. If you feel motivated, you can subclass Rollback, although the utility of that escapes me at the moment.

When Django 1.6 is released, Xact will be deprecated in favor of new functionality there… but for now, have fun with it!

Aymeric Augustin at 13:27, 27 June 2013:

I just added to Django a feature that may help solve this problem, albeit with a different API. From Django 1.6 beta 1 onwards, you can force a rollback of the innermost enclosing atomic block by calling transaction.set_rollback(True).

Unlike an exception, this doesn’t break through the code until the exit of the decorator / context manager. Depending on the context, that can make the code easier or harder to express; it’s hard to tell at this point.