Reputation: 10867
I want to make an atomic transaction and my database is PostgreSQL.
Here's how I've been making transaction so far:
transaction.set_autocommit(False)
try:
do_stuff()
transaction.commit()
except:
transaction.rollback()
raise
finally:
transaction.set_autocommit(True)
Doc says I could do it like this:
with transaction.atomic():
do_stuff()
Are both code the same?
I have a connection pool CONN_MAX_AGE=60
in my settings.py
.
What happens with the following scenario:
False
True
Will my updates in 2. survive?
Would it be different with transaction.atomic()
?
Upvotes: 1
Views: 5063
Reputation: 48902
I would recommend using transaction.atomic()
, since its purpose is to do exactly the thing you want.
You can see the implementation here. The most obvious difference is that Django's version has support for "nested" transactions using savepoints. You can trust that this code is well-tested and widely used.
Regarding your scenario, your updates in step 2 should survive in either case, since autocommit applies at the database connection level, and the two concurrent requests will be using different database connections.
Upvotes: 3