SQLAlchemy Session and Alembic Migrations: Can rollback() Safely Recover After a Failed Schema Change?
0 reputation · 06 Dec 2022, 23:40 UTC
0 reputation · 06 Dec 2022, 23:40 UTC
An application runs Alembic migrations and ordinary ORM work through SQLAlchemy 2.x Sessions against both PostgreSQL and MySQL. When a migration fails partway through, the recovery code calls session.rollback() and continues using the same Session and its mapped objects.
PostgreSQL supports transactional DDL, so a failed ALTER TABLE can be undone by rollback. MySQL implicitly commits around most DDL, so the same rollback leaves the schema change in place. Alembic exposes a transactional_ddl flag per dialect, which suggests the tool itself treats safe rollback as backend-dependent rather than guaranteed.
Separately, SQLAlchemy requires rollback() after any DBAPI error before the connection is usable again (otherwise a PendingRollbackError is raised), and ORM objects cached in the identity map are not revalidated against the altered schema. It is unclear whether expiring or expunging mapped instances is sufficient, or whether the whole Session must be discarded.
transactional_ddl value for the active dialect a reliable way to decide whether in-place rollback is even meaningful?A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.