diff --git a/src/recordlinker/database/mpi_service.py b/src/recordlinker/database/mpi_service.py index 8852e30b..843c36fe 100644 --- a/src/recordlinker/database/mpi_service.py +++ b/src/recordlinker/database/mpi_service.py @@ -367,3 +367,12 @@ def delete_persons( session.delete(person) if commit: session.commit() + + +def get_orphaned_patients( + session: orm.Session, +) -> typing.Sequence[schemas.PatientRefs]: + """ + Retrieve all the orphaned Patients in the MPI database. + """ + return session.scalars(select(models.Patient).where(models.Patient.person_id.is_(None))).all() diff --git a/src/recordlinker/routes/patient_router.py b/src/recordlinker/routes/patient_router.py index 91dd99a2..7b921462 100644 --- a/src/recordlinker/routes/patient_router.py +++ b/src/recordlinker/routes/patient_router.py @@ -57,6 +57,23 @@ def create_patient( ) +@router.get( + "/orphaned", summary="Retrieve orphaned patients", status_code=fastapi.status.HTTP_200_OK +) +def get_orphaned_patients( + session: orm.Session = fastapi.Depends(get_session), +) -> schemas.PatientRefs | None: + """ + Retrieve patient_reference_id(s) for all Patients that are not linked to a Person. + """ + patients = service.get_orphaned_patients(session) + if not patients: + return None + return schemas.PatientRefs( + patients=[p.reference_id for p in patients if p.reference_id is not None] + ) + + @router.get( "/{patient_reference_id}", summary="Retrieve a patient record",