Enhance error handling and transaction management in item creation; explicitly commit changes and rollback on exceptions to ensure database integrity.
This commit is contained in:
parent
f52b47f6df
commit
e484c9e9a8
@ -114,10 +114,10 @@ class DatabaseIntegrityError(HTTPException):
|
|||||||
|
|
||||||
class DatabaseTransactionError(HTTPException):
|
class DatabaseTransactionError(HTTPException):
|
||||||
"""Raised when a database transaction fails."""
|
"""Raised when a database transaction fails."""
|
||||||
def __init__(self):
|
def __init__(self, detail: str = settings.DB_TRANSACTION_ERROR):
|
||||||
super().__init__(
|
super().__init__(
|
||||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
detail=settings.DB_TRANSACTION_ERROR
|
detail=detail
|
||||||
)
|
)
|
||||||
|
|
||||||
class DatabaseQueryError(HTTPException):
|
class DatabaseQueryError(HTTPException):
|
||||||
|
@ -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:
|
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."""
|
"""Creates a new item record for a specific list."""
|
||||||
try:
|
try:
|
||||||
async with db.begin():
|
db_item = ItemModel(
|
||||||
db_item = ItemModel(
|
name=item_in.name,
|
||||||
name=item_in.name,
|
quantity=item_in.quantity,
|
||||||
quantity=item_in.quantity,
|
list_id=list_id,
|
||||||
list_id=list_id,
|
added_by_id=user_id,
|
||||||
added_by_id=user_id,
|
is_complete=False # Default on creation
|
||||||
is_complete=False # Default on creation
|
# version is implicitly set to 1 by model default
|
||||||
# version is implicitly set to 1 by model default
|
)
|
||||||
)
|
db.add(db_item)
|
||||||
db.add(db_item)
|
await db.flush()
|
||||||
await db.flush()
|
await db.refresh(db_item)
|
||||||
await db.refresh(db_item)
|
await db.commit() # Explicitly commit here
|
||||||
return db_item
|
return db_item
|
||||||
except IntegrityError as e:
|
except IntegrityError as e:
|
||||||
|
await db.rollback() # Rollback on integrity error
|
||||||
raise DatabaseIntegrityError(f"Failed to create item: {str(e)}")
|
raise DatabaseIntegrityError(f"Failed to create item: {str(e)}")
|
||||||
except OperationalError as e:
|
except OperationalError as e:
|
||||||
|
await db.rollback() # Rollback on operational error
|
||||||
raise DatabaseConnectionError(f"Database connection error: {str(e)}")
|
raise DatabaseConnectionError(f"Database connection error: {str(e)}")
|
||||||
except SQLAlchemyError as e:
|
except SQLAlchemyError as e:
|
||||||
|
await db.rollback() # Rollback on other SQLAlchemy errors
|
||||||
raise DatabaseTransactionError(f"Failed to create item: {str(e)}")
|
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]:
|
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."""
|
"""Gets all items belonging to a specific list, ordered by creation time."""
|
||||||
|
Loading…
Reference in New Issue
Block a user