Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django nested transactions - “with transaction.atomic()”

I would like to know if I have something like this:

def functionA():     with transaction.atomic():         #save something         functionB()  def functionB():     with transaction.atomic():         #save another thing 

Someone knows what will happen? If functionB fails, functionA will rollback too?

Thank you!

like image 406
Lara Avatar asked Feb 25 '14 10:02

Lara


People also ask

What is transaction atomic () in Django?

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Can transaction be nested?

A nested transaction is used to provide a transactional guarantee for a subset of operations performed within the scope of a larger transaction. Doing this allows you to commit and abort the subset of operations independently of the larger transaction.

Can nested transaction be distributed?

A flat or nested transaction that accesses objects handled by different servers is referred to as a distributed transaction.

Is SQL transaction Atomic?

In SQL databases transaction atomicity is implemented most frequently using write-ahead logging (meaning that the transaction log entries are written before the actual tables and indexes are updated).


1 Answers

Yes, it will. Regardless of nesting, if an atomic block is exited by an exception it will roll back:

If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Note also that an exception in an outer block will cause the inner block to roll back, and that an exception in an inner block can be caught to prevent the outer block from rolling back. The documentation addresses these issues. (Or see here for a more comprehensive follow-up question on nested transactions).

like image 180
Kevin Christopher Henry Avatar answered Oct 12 '22 16:10

Kevin Christopher Henry