SQLAlchemy ORM Session and Alembic online migration connection interoperability
0 reputation · 26 Dec 2021, 08:43 UTC
In SQLAlchemy 1.4 and 2.0, an ORM Session can be bound to either an Engine or an existing Connection, while Alembic's online migration mode expects a live DBAPI Connection passed to MigrationContext.configure() rather than an ORM object. The goal is to determine whether ORM operations can participate in Alembic's online migration transaction without introducing a separate pooled connection or conflicting transaction state.
Binding a Session to the Engine may defer connection checkout until first ORM use, but whether that produces a second pooled connection alongside Alembic's connection depends on pool state, isolation level, and migration workload. Binding a Session to the connection managed by Alembic's MigrationContext would share the underlying DBAPI connection, yet the transaction boundaries between Alembic's migration context and the ORM Session may still conflict if both attempt to commit or roll back independently, and behavior may vary across Alembic and SQLAlchemy versions.
Under SQLAlchemy 1.4/2.0 and current Alembic releases, is binding an ORM Session to the MigrationContext connection the supported way to share Alembic's transaction during online migrations? Does binding to the Engine reliably avoid a second pooled connection checkout, or is that dependent on pool exhaustion and DDL timing? What specific transaction management conflicts arise when Alembic and the ORM Session both manage transaction state on the same connection?