3
# I've set echo=True when doing create_engine, so I can see all the sql stmt
# DBSession is ScopeSession(thread_local) and autocommit is False
session = DBSession() 
session.add(somemodel)
# 
try:
    session.flush()
    raise Exception()
    session.commit()
except SQLAlchemyError as e:
    session.rollback()
finally:
    session.close()

acording to the SQLAlchemy docs:

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.

I expect to see the log "rollback" when executing "session.close()"

Tallmad
  • 1,951
  • 4
  • 22
  • 29
  • Why? Transactions are not committed unless you explicitly tell the database to commit. Closing the database connection or starting a new transaction thus implicitly rolls back. – Martijn Pieters Jun 09 '13 at 10:07
  • a transaction also implicitly begin, but I can see the log "begin" – Tallmad Jun 09 '13 at 10:15
  • I am talking about the database level, not the SQLAlchemy level. SQLAlchemy is starting the transaction explicitly there, ending any previous transactions. – Martijn Pieters Jun 09 '13 at 10:31

1 Answers1

6

the rollback (or if configured, the commit) that occurs in the Pool is not currently participating in the logging that the Engine normally does for commit/rollback events.

ticket: http://www.sqlalchemy.org/trac/ticket/2752 has been added.

Edit: Took a look at this, and I think this logging should still be part of the pool's logger, not the engine's, otherwise you get a lot of this:

sqlalchemy.Engine: COMMIT
sqlalchemy.Engine: ROLLBACK (via pool)

An application really shouldn't have to worry too much about the pool's rollback of things, because if you're using a Session, you really should be calling commit() or rollback() right before any close() operation.

the pool logging is turned on normally by create_engine("url", echo_pool='debug'), or setting up logging on the sqlalchemy.pool namespace.

zzzeek
  • 72,307
  • 23
  • 193
  • 185