Is "transaction.atomic" same as "transaction.commit_on_success"?
Solution 1:
Based on the documentation I have read on the subject, there is a significant difference when these decorators are nested.
Nesting two atomic
blocks does not work the same as nesting two commit_on_success
blocks.
The problem is that there are two guarantees that you would like to have from these blocks.
- You would like the content of the block to be atomic, either everything inside the block is committed, or nothing is committed.
- You would like durability, once you have left the block without an exception you are guaranteed, that everything you wrote inside the block is persistent.
It is impossible to provide both guarantees when blocks are nested. If an exception is raised after leaving the innermost block but before leaving the outermost block, you will have to fail in one of two ways:
- Fail to provide durability for the innermost block.
- Fail to provide atomicity for the outermost block.
Here is where you find the difference. Using commit_on_success
would give durability for the innermost block, but no atomicity for the outermost block. Using atomic
would give atomicity for the outermost block, but no durability for the innermost block.
Simply raising an exception in case of nesting could prevent you from running into the problem. The innermost block would always raise an exception, thus it never promises any durability. But this loses some flexibility.
A better solution would be to have more granularity about what you are asking for. If you can separately ask for atomicity and durability, then you can perform nesting. You just have to ensure that every block requesting durability is outside those requesting atomicity. Requesting durability inside a block requesting atomicity would have to raise an exception.
atomic
is supposed to provide the atomicity part. As far as I can tell django 1.6.1 does not have a decorator, which can ask for durability. I tried to write one, and posted it on codereview.
Solution 2:
Yes. You should use atomic
in the places where you previously used commit_on_success
.
Since the new transaction system is designed to be more robust and consistent, though, it's possible that you could see different behavior. For example, if you catch database errors and try to continue on you will see a TransactionManagementError
, whereas the previous behavior was undefined and probably case-dependent.
But, if you're doing things properly, everything should continue to work the same way.