Saturday, March 10, 2012

Transaction management in django

ACID refers to an acronym in the database transactions.Which in full means.Atomic, Consistent, Independent, Durable(or atomicity, consistency, independency and durability).

Atomicity here refers to the idea that a transaction commits(goes through) as a whole or does not commit at all(all or nothing).Various scenarios necessitate the need to maintain atomicity in a transaction.

For instance if you are creating objects which require foreign key relationships with other objects.
It may be necessary to create the object it is related to on the fly and save it just to make sure the foreign key attribute is satisfied.

when controlling transaction management in views the best approach is to use decorators

from django.db import transaction

@transaction.commit_on_success
def viewfunc(request):
    # ...
    # this code executes inside a transaction
    # ...

There are three types of decorators, autocommit, commit_on_success and commit_manually.
autocommit does django's default commit behaviour
commit_on_success does a single transaction for all the work done in a function, this can be the view function.
commit_manually lets you control transactions manually by calling commit() and rollback().

Care should be taken when using commit manually() because some transactions may occur in unexpected places which require a commit.This raises an exception in django.

A point to note is that some databases do not support transaction management.It is surprising to note that SQLite db supports transactions while MySQL db does not.

No comments:

Post a Comment