Skip to content

Commit 43d496d

Browse files
committed
fix: Fixed a bug where the session failed to close properly due to an exception sent when committed or rolled back
1 parent e3d21d2 commit 43d496d

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

sqlalchemy_database/database.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -303,11 +303,13 @@ def __enter__(self):
303303
return self.db.session
304304

305305
def _close_session(self, session: Session, exc_type):
306-
if exc_type is not None:
307-
session.rollback()
308-
elif self.db.commit_on_exit:
309-
session.commit()
310-
session.close()
306+
try:
307+
if exc_type is not None:
308+
session.rollback()
309+
elif self.db.commit_on_exit:
310+
session.commit()
311+
finally:
312+
session.close()
311313

312314
def __exit__(self, exc_type, exc_value, traceback):
313315
if not (self._scope and isinstance(self._scope, self._SessionCls)):
@@ -341,10 +343,12 @@ async def __aexit__(self, exc_type, exc_value, traceback):
341343
if not (self._scope and isinstance(self._scope, self._SessionCls)):
342344
"""If the scope is a session, it will not be closed."""
343345
session = self.db.session
344-
if exc_type is not None:
345-
await session.rollback()
346-
elif self.db.commit_on_exit:
347-
await session.commit()
348-
await session.close()
346+
try:
347+
if exc_type is not None:
348+
await session.rollback()
349+
elif self.db.commit_on_exit:
350+
await session.commit()
351+
finally:
352+
await session.close()
349353
self.db.scoped_session.registry.clear()
350354
self.db._session_scope.reset(self._token)

0 commit comments

Comments
 (0)