Skip to content

Commit

Permalink
⚡️(api) improve database session usage
Browse files Browse the repository at this point in the history
We should rollback and properly close the session on server restart or
database-related failures.
  • Loading branch information
jmaupetit committed May 20, 2024
1 parent 6e90e50 commit e70c0be
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
24 changes: 20 additions & 4 deletions src/api/qualicharge/api/v1/routers/static.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,15 @@ async def update(
try:
update = update_statique(session, id_pdc_itinerance, statique)
except IntegrityError as err:
session.rollback()
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail="id_pdc_itinerance does not match request body",
) from err
except ObjectDoesNotExist as err:
session.rollback()
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Statique to update does not exist",
status_code=status.HTTP_404_NOT_FOUND, detail=str(err)
) from err
return update

Expand All @@ -158,15 +159,30 @@ async def create(
statique: Statique, session: Session = Depends(get_session)
) -> StatiqueItemsCreatedResponse:
"""Create a statique item."""
return StatiqueItemsCreatedResponse(items=[save_statique(session, statique)])
try:
db_statique = save_statique(session, statique)
except ObjectDoesNotExist as err:
session.rollback()
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(err)
) from err

return StatiqueItemsCreatedResponse(items=[db_statique])


@router.post("/bulk", status_code=status.HTTP_201_CREATED)
async def bulk(
statiques: BulkStatiqueList, session: Session = Depends(get_session)
) -> StatiqueItemsCreatedResponse:
"""Create a set of statique items."""
statiques = [statique for statique in save_statiques(session, statiques)]
try:
statiques = [statique for statique in save_statiques(session, statiques)]
except ObjectDoesNotExist as err:
session.rollback()
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(err)
) from err

if not len(statiques):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
Expand Down
11 changes: 7 additions & 4 deletions src/api/qualicharge/db.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""QualiCharge database connection."""

import logging
from typing import Optional
from typing import Generator, Optional

from pydantic import PostgresDsn
from sqlalchemy import Engine as SAEngine
Expand Down Expand Up @@ -86,16 +86,19 @@ def get_engine() -> SAEngine:
return Engine().get_engine(url=settings.DATABASE_URL, echo=settings.DEBUG)


def get_session() -> SMSession:
def get_session() -> Generator[SMSession, None, None]:
"""Get database session."""
session = Session().get_session(get_engine())
logger.debug("Getting session %s", session)
return session
try:
yield session
finally:
session.close()


def is_alive() -> bool:
"""Check if database connection is alive."""
session = get_session()
session = next(get_session())
try:
session.execute(text("SELECT 1 as is_alive"))
return True
Expand Down

0 comments on commit e70c0be

Please sign in to comment.