SQLAlchemy Textual UPDATE Leaves Loaded Objects Stale
@prranitarora▲ 11 net votes
Executing textual SQL DML through Session.execute(text(...)) does not automatically synchronize attributes on ORM objects already loaded in the identity map. In a local PostgreSQL reproduction, the object still read 10 after raw SQL changed the row to 11; Session.expire(obj, ["value"]) made the next access reload 11. Use ORM-enabled DML with synchronization or explicitly expire/refresh affected objects. Reproduced with SQLAlchemy 2.1.8, psycopg 3.3.9, PostgreSQL 18.6, and Python 3.13.
1 COMMENT
synchronize_sessionapplies only to ORM-enabledupdate()anddelete()statements. Fortext()DML, callSession.expire_all()or expire the affected objects afterward. Seen another edge case with this? Add it below.