|
| 1 | +""" |
| 2 | +Database Models and Delete Behavior Design Principles |
| 3 | +
|
| 4 | +1. Query-Patient-Location Relationship: |
| 5 | + - Every Query must have both a Patient and a Location associated with it. |
| 6 | + - A Patient can have multiple Queries. |
| 7 | + - A Location can be associated with multiple Queries. |
| 8 | +
|
| 9 | +2. Delete Restrictions: |
| 10 | + - Patient and Location records cannot be deleted if there are any Queries referencing them. |
| 11 | + - This is enforced by the "RESTRICT" ondelete option in the Query model's foreign keys. |
| 12 | +
|
| 13 | +3. Orphan Deletion: |
| 14 | + - A Patient or Location should be deleted only when there are no more Queries referencing it. |
| 15 | + - This is handled by custom event listeners that check for remaining Queries after a Query deletion. |
| 16 | +
|
| 17 | +4. Cascading Behavior: |
| 18 | + - There is no automatic cascading delete from Patient or Location to Query. |
| 19 | + - Queries must be explicitly deleted before their associated Patient or Location can be removed. |
| 20 | +
|
| 21 | +5. Transaction Handling: |
| 22 | + - Delete operations and subsequent orphan checks should occur within the same transaction. |
| 23 | + - Event listeners use the existing database connection to ensure consistency with the main transaction. |
| 24 | +
|
| 25 | +6. Error Handling: |
| 26 | + - Errors during the orphan deletion process should not silently fail. |
| 27 | + - Exceptions in event listeners are logged and re-raised to ensure proper transaction rollback. |
| 28 | +
|
| 29 | +7. Data Integrity: |
| 30 | + - Database-level constraints (foreign keys, unique constraints) are used in conjunction with SQLAlchemy model definitions to ensure data integrity. |
| 31 | +
|
| 32 | +These principles aim to maintain referential integrity while allowing for the cleanup of orphaned Patient and Location records when appropriate. |
| 33 | +""" |
| 34 | + |
| 35 | +from __future__ import annotations |
| 36 | + |
| 37 | +from typing import List |
| 38 | +from sqlmodel import SQLModel, Field, Relationship |
| 39 | +from sqlalchemy import Column, Text, Float, Index |
| 40 | +from sqlalchemy.orm import relationship, Mapped |
| 41 | +import uuid |
| 42 | +from sqlalchemy.dialects.sqlite import TEXT |
| 43 | + |
| 44 | + |
| 45 | +class Patient(SQLModel, table=True): |
| 46 | + patient_id: str = Field( |
| 47 | + sa_column=Column( |
| 48 | + TEXT, unique=True, primary_key=True, default=str(uuid.uuid4()) |
| 49 | + ), |
| 50 | + allow_mutation=False, |
| 51 | + ) |
| 52 | + queries: Mapped[List["Query"]] = Relationship( |
| 53 | + # back_populates="patient", |
| 54 | + passive_deletes="all", |
| 55 | + cascade_delete=True, |
| 56 | + sa_relationship=relationship(back_populates="patient"), |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +class Query(SQLModel, table=True): |
| 61 | + """Every Query must have both a Patient and a Location.""" |
| 62 | + |
| 63 | + query_id: str = Field( |
| 64 | + sa_column=Column( |
| 65 | + TEXT, unique=True, primary_key=True, default=str(uuid.uuid4()) |
| 66 | + ), |
| 67 | + allow_mutation=False, |
| 68 | + ) |
| 69 | + query: str = Field(allow_mutation=False, sa_column=Column(Text)) |
| 70 | + # Restrict deleting Patient record when there is atleast 1 query referencing it |
| 71 | + patient_id: str = Field(foreign_key="patient.patient_id", ondelete="RESTRICT") |
| 72 | + # Restrict deleting Location record when there is atleast 1 query referencing it |
| 73 | + location_id: str = Field(foreign_key="location.location_id", ondelete="RESTRICT") |
| 74 | + location: Location = Relationship(back_populates="queries") |
| 75 | + patient: Patient = Relationship(back_populates="queries") |
| 76 | + |
| 77 | + |
| 78 | +class Location(SQLModel, table=True): |
| 79 | + __table_args__ = ( |
| 80 | + Index("ix_location_composite_lat_lng", "latitude", "longitude", unique=True), |
| 81 | + ) |
| 82 | + location_id: str = Field( |
| 83 | + sa_column=Column( |
| 84 | + TEXT, unique=True, primary_key=True, default=str(uuid.uuid4()) |
| 85 | + ), |
| 86 | + allow_mutation=False, |
| 87 | + ) |
| 88 | + latitude: float = Field(sa_column=Column(Float)) |
| 89 | + longitude: float = Field(sa_column=Column(Float)) |
| 90 | + queries: Mapped[List["Query"]] = Relationship( |
| 91 | + # back_populates="location", |
| 92 | + cascade_delete=True, |
| 93 | + passive_deletes=True, |
| 94 | + sa_relationship=relationship(back_populates="location"), |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +# TODO: Define Provider SQL model fields |
| 99 | +# class Provider(SQLModel, table=True): |
| 100 | +# # TODO: Compare with Github issue, domain model and noccodb |
| 101 | +# ... |
| 102 | + |
| 103 | + |
| 104 | +# TODO: Add Model events for database ops during testing |
| 105 | +# @event.listens_for(Query, "after_delete") |
| 106 | +# def delete_dangling_location(mapper: Mapper, connection: Engine, target: Query): |
| 107 | +# """Deletes orphan Location when no related queries exist.""" |
| 108 | +# local_session = sessionmaker(connection) |
| 109 | +# with local_session() as session: |
| 110 | +# stmt = ( |
| 111 | +# select(func.count()) |
| 112 | +# .select_from(Query) |
| 113 | +# .where(Query.location_id == target.location_id) |
| 114 | +# ) |
| 115 | +# if ( |
| 116 | +# num_queries := session.execute(stmt).scalar_one_or_none() |
| 117 | +# ) and num_queries <= 1: |
| 118 | +# location: Location = session.get(Location, target.location_id) |
| 119 | +# session.delete(location) |
| 120 | +# session.flush() |
| 121 | + |
| 122 | + |
| 123 | +# @event.listens_for(Query, "after_delete") |
| 124 | +# def delete_dangling_patient(mapper: Mapper, connection: Engine, target: Query): |
| 125 | +# """Deletes orphan Patient records when no related queries exist.""" |
| 126 | +# local_session = sessionmaker(connection) |
| 127 | +# with local_session() as session: |
| 128 | +# stmt = ( |
| 129 | +# select(func.count()) |
| 130 | +# .select_from(Query) |
| 131 | +# .where(Query.patient_id == target.patient_id) |
| 132 | +# ) |
| 133 | +# if ( |
| 134 | +# num_queries := session.execute(stmt).scalar_one_or_none() |
| 135 | +# ) and num_queries <= 1: |
| 136 | +# patient: Patient = session.get(Patient, target.patient_id) |
| 137 | +# session.delete(patient) |
| 138 | +# session.flush() |
0 commit comments