diff --git a/be/app/core/exceptions.py b/be/app/core/exceptions.py index 7d34b38..14911ac 100644 --- a/be/app/core/exceptions.py +++ b/be/app/core/exceptions.py @@ -114,10 +114,10 @@ class DatabaseIntegrityError(HTTPException): class DatabaseTransactionError(HTTPException): """Raised when a database transaction fails.""" - def __init__(self): + def __init__(self, detail: str = settings.DB_TRANSACTION_ERROR): super().__init__( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=settings.DB_TRANSACTION_ERROR + detail=detail ) class DatabaseQueryError(HTTPException): diff --git a/be/app/crud/item.py b/be/app/crud/item.py index 19b6969..9bd8726 100644 --- a/be/app/crud/item.py +++ b/be/app/crud/item.py @@ -20,25 +20,31 @@ from app.core.exceptions import ( async def create_item(db: AsyncSession, item_in: ItemCreate, list_id: int, user_id: int) -> ItemModel: """Creates a new item record for a specific list.""" try: - async with db.begin(): - db_item = ItemModel( - name=item_in.name, - quantity=item_in.quantity, - list_id=list_id, - added_by_id=user_id, - is_complete=False # Default on creation - # version is implicitly set to 1 by model default - ) - db.add(db_item) - await db.flush() - await db.refresh(db_item) - return db_item + db_item = ItemModel( + name=item_in.name, + quantity=item_in.quantity, + list_id=list_id, + added_by_id=user_id, + is_complete=False # Default on creation + # version is implicitly set to 1 by model default + ) + db.add(db_item) + await db.flush() + await db.refresh(db_item) + await db.commit() # Explicitly commit here + return db_item except IntegrityError as e: + await db.rollback() # Rollback on integrity error raise DatabaseIntegrityError(f"Failed to create item: {str(e)}") except OperationalError as e: + await db.rollback() # Rollback on operational error raise DatabaseConnectionError(f"Database connection error: {str(e)}") except SQLAlchemyError as e: + await db.rollback() # Rollback on other SQLAlchemy errors raise DatabaseTransactionError(f"Failed to create item: {str(e)}") + except Exception as e: # Catch any other exception and attempt rollback + await db.rollback() + raise # Re-raise the original exception async def get_items_by_list_id(db: AsyncSession, list_id: int) -> PyList[ItemModel]: """Gets all items belonging to a specific list, ordered by creation time."""