Remove unnecessary DB queries that performs checks on the DB level if an instance exists (e.g., workspace, domain, app, etc.) for DELETE, CREATE, ...
Code example how to raise http error from DB integrity:
from fastapi import HTTPException
from sqlalchemy.engine.base import Connection
from sqlalchemy.exc import IntegrityError
def handle_db_operation(connection: Connection, db_operation, params):
"""
Handles a database operation, converting SQLAlchemy IntegrityError
to FastAPI HTTPException.
Args:
- connection: The SQLAlchemy connection to use for the operation.
- db_operation: A callable representing the database operation.
Returns:
The result of the db_operation if successful.
Raises:
- HTTPException: If a unique constraint violation occurs.
"""
try:
# Execute the database operation
return connection.execute(db_operation, params)
except IntegrityError as e:
# Check if the error is due to a unique constraint violation
error_info = str(e.orig)
if (
"unique constraint" in error_info.lower()
or "duplicate key" in error_info.lower()
):
raise HTTPException(status_code=409, detail="Unique constraint violation.")
else:
# For other types of IntegrityErrors, you might want to handle them differently
raise HTTPException(status_code=400, detail="Database operation failed.")
Code example how to raise http error from DB integrity: