sqlalchemy: Explicit commit in transaction context manager causes error.
Describe the bug
when explicitly committing a transaction in a context manager, it throws an error, this seems to be caused by a _assert_active call in Transaction.__exit__.
this is implied to work via code examples in the docs and it looks like the code following the assert handles a a transaction being already committed and just returns early?
Expected behavior No error
To Reproduce
import sqlalchemy.orm
engine = sqlalchemy.create_engine(
"postgresql://postgres:postgres@db:5432/postgres",
future=True,
)
with sqlalchemy.orm.Session(engine, expire_on_commit=False) as session:
with session.begin():
session.execute("SELECT 1")
session.commit()
Error
Traceback (most recent call last):
File "{snip}/test.py", line 10, in <module>
session.commit()
File "{snip}/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 937, in __exit__
self._assert_active(deactive_ok=True, prepared_ok=True)
File "{snip}/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 617, in _assert_active
raise sa_exc.ResourceClosedError(closed_msg)
sqlalchemy.exc.ResourceClosedError: This transaction is closed
Versions.
- OS: linux
- Python: 3.9
- SQLAlchemy: 1.4.8
- Database: postgres
- DBAPI: psycopg2 or asyncpg
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 3
- Comments: 37 (33 by maintainers)
Mike Bayer has proposed a fix for this issue in the master branch:
unify transactional context managers https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/2800