feat: handling for integrity errors

Resolves: #7
This commit is contained in:
Chris Milne 2026-05-27 16:26:34 +01:00
parent fc835dc982
commit 1ed0cfb38c
4 changed files with 47 additions and 9 deletions

View file

@ -16,8 +16,10 @@ from typing import Annotated, Optional
from fastapi import APIRouter, status
from fastapi.params import Query
from psycopg.errors import UniqueViolation
from sqlalchemy.exc import IntegrityError
from src.exceptions import UnprocessableContent
from src.exceptions import UnprocessableContent, Conflict
from src.contact.models import Contact
from src.contact.schemas import ContactAddress
from src.contact.exceptions import ContactNotFoundException
@ -66,9 +68,12 @@ async def create_org(db: db_dependency, user_model: user_model_claims_dependency
org_model.status = "partial" # Status is always set to partial at first, see update_questionnaire() doc
db.add(org_model)
db.flush()
try:
db.flush()
except IntegrityError as e:
if isinstance(e.orig, UniqueViolation):
raise Conflict(message="Organisation with this name already exists")
# Adds currently logged-in user to org users list and sets them as root_user
user_model = db.get(User, db_id)
org_model.user_rel.append(user_model)
org_model.root_user_rel = user_model
for contact_type in ["billing_contact_id", "security_contact_id", "owner_contact_id"]:
@ -110,7 +115,7 @@ async def get_users(org_model: org_model_root_claim_query_dependency):
@router.post("/users")
async def add_user_to_org(db: db_dependency, org_model: org_model_root_claim_body_dependency, user_model: user_model_body_dependency, request_model: OrgUserPostRequest):
if user_model in org_model.user_rel:
return
raise Conflict(message="User already a part of this organisation")
org_model.user_rel.append(user_model)
db.commit()