Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does closing a SQLAlchemy ORM Session roll back uncommitted changes?

For example, is there a difference between the following two?

session = Session() # Session is a session maker
try:
    # do some work
    session.commit()
except:
    session.rollback()
finally:
    session.close()

and

session = Session()
try:
    # do some work
    session.commit()
finally:
    session.close()

The latter is what I used to do, because I assumed closing the session before committing (in case of an error) had the same effect as rolling back. But I saw the first form here.

like image 532
lfk Avatar asked Jan 04 '23 07:01

lfk


1 Answers

Closing a session will implicitly roll back current transactional state:

The close() method issues a expunge_all(), and releases any transactional/connection resources. When connections are returned to the connection pool, transactional state is rolled back as well.

But I'd argue that the first form is still better, since explicit is better than implicit. The author of SQLAlchemy also seems to reflect this sentiment.

like image 111
Ilja Everilä Avatar answered Jan 13 '23 11:01

Ilja Everilä