|
3 | 3 | from fastapi import HTTPException, status |
4 | 4 | from lims_utils.logging import app_logger |
5 | 5 | from lims_utils.models import Paged, ProposalReference |
| 6 | +from psycopg.errors import ForeignKeyViolation |
6 | 7 | from sqlalchemy import and_, insert, select |
| 8 | +from sqlalchemy.exc import IntegrityError |
7 | 9 |
|
8 | 10 | from ..models.inner_db.tables import Container, Sample, SampleParentChild, Shipment |
9 | 11 | from ..models.samples import OptionalSample, SampleIn, SampleOut |
10 | 12 | from ..utils.config import Config |
11 | | -from ..utils.crud import assert_not_booked, edit_item |
| 13 | +from ..utils.crud import assert_not_booked, delete_item, edit_item |
12 | 14 | from ..utils.database import inner_db |
13 | 15 | from ..utils.external import Expeye, ExternalRequest |
14 | 16 | from ..utils.session import retry_if_exists |
@@ -189,3 +191,16 @@ def get_samples( |
189 | 191 | pass |
190 | 192 |
|
191 | 193 | return validated_samples |
| 194 | + |
| 195 | + |
| 196 | +def delete_sample(sample_id: int): |
| 197 | + try: |
| 198 | + delete_item(table=Sample, item_id=sample_id) |
| 199 | + except IntegrityError as e: |
| 200 | + if isinstance(e.__cause__, ForeignKeyViolation): |
| 201 | + # If a foreign key violation occurs, that's because the sample is in SampleParentChild |
| 202 | + raise HTTPException( |
| 203 | + status_code=status.HTTP_409_CONFLICT, |
| 204 | + detail="Sample is linked to a different session and cannot be deleted", |
| 205 | + ) |
| 206 | + raise |
0 commit comments