views:

42

answers:

1

I have an issue with SQLAlchemy apparently committing. A rough sketch of my code:

trans = self.conn.begin()
try:            
    assert not self.conn.execute(my_obj.__table__.select(my_obj.id == id)).first()
    self.conn.execute(my_obj.__table__.insert().values(id=id))
    assert not self.conn.execute(my_obj.__table__.select(my_obj.id == id)).first()
except:
    trans.rollback()
    raise

I don't commit, and the second assert always fails! In other words, it seems the data is getting inserted into the database even though the code is within a transaction! Is this assessment accurate?

+1  A: 

You're right in that changes aren't get commited to DB. But they are auto-flushed by SQLAlchemy when you perform query, in your case flush is performed on lines with asserts. So if you will not explicitly call commit you will never see these changes in DB, within real data. However, you will get them back as long as you use the same conn object.

You can pass autoflush=False to session constructor do disable this behavior.

nailxx