Benjamin Toueg
Benjamin Toueg

Reputation: 10867

Django db transaction set_autocommit and CONN_MAX_AGE

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:

  1. first request sets autocommit to False
  2. second request makes db updates
  3. first request raises and exception, rollbacks, and sets autocommit back to True

Will my updates in 2. survive?

Would it be different with transaction.atomic()?

Upvotes: 1

Views: 5063

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

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

Related Questions