Skip to content

Commit b1568f0

Browse files
committed
Refactor DbContextManager
1 parent 1d6b3ba commit b1568f0

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/db_config.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,21 @@ class DbContextManager:
8787
"""Context manager para manipulação de sessões do banco de dados.
8888
"""
8989
def __init__(self):
90-
self.db = async_session_maker()
90+
self.async_session_maker = async_session_maker
91+
self.db = None
9192

9293
async def __aenter__(self):
94+
self.db = self.async_session_maker()
9395
return self.db
9496

9597
async def __aexit__(self, exc_type, exc_value, traceback):
96-
await self.db.close()
98+
try:
99+
if exc_type is None:
100+
# 2. If NO exception occurred, commit the transaction.
101+
await self.db.commit()
102+
else:
103+
# 3. If an exception DID occur, roll back the transaction.
104+
await self.db.rollback()
105+
finally:
106+
# 4. ALWAYS close the session.
107+
await self.db.close()

0 commit comments

Comments
 (0)