Skip to content

Commit ab399f7

Browse files
committed
Fix session management
1 parent 2f259e9 commit ab399f7

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

‎src/dialog/db/__init__.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,26 @@
22
from sqlalchemy import create_engine
33
from sqlalchemy.orm import Session, DeclarativeBase
44

5+
from contextlib import contextmanager
6+
57
engine = create_engine(Settings().DATABASE_URL)
68

9+
710
class Base(DeclarativeBase):
811
pass
912

10-
def get_session(): # pragma: no cover
11-
with Session(engine) as session:
12-
yield session
13+
@contextmanager
14+
def session_scope():
15+
with Session(bind=engine) as session:
16+
try:
17+
yield session
18+
session.commit()
19+
except Exception as exc:
20+
session.rollback()
21+
raise exc
22+
finally:
23+
session.close()
1324

25+
def get_session():
26+
with session_scope() as session:
27+
yield session

0 commit comments

Comments
 (0)