From 1441843a5552bfc3521cd732b30374165cd26d13 Mon Sep 17 00:00:00 2001 From: Felipe Cardoso Date: Wed, 19 Mar 2025 08:16:38 +0100 Subject: [PATCH] Add cascading delete to Gift and Guest relationships Updated the `ondelete="CASCADE"` behavior for foreign key constraints in Alembic migrations and added cascading rules to related models in SQLAlchemy. These changes ensure proper cleanup of dependent records when a parent record is deleted. --- .../alembic/versions/38bf9e7e74b3_add_all_initial_models.py | 4 ++-- backend/app/models/gift.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/app/alembic/versions/38bf9e7e74b3_add_all_initial_models.py b/backend/app/alembic/versions/38bf9e7e74b3_add_all_initial_models.py index 17decad..7068bc6 100644 --- a/backend/app/alembic/versions/38bf9e7e74b3_add_all_initial_models.py +++ b/backend/app/alembic/versions/38bf9e7e74b3_add_all_initial_models.py @@ -317,8 +317,8 @@ def upgrade() -> None: sa.Column('gift_id', sa.UUID(), nullable=False), sa.Column('reserved_at', sa.DateTime(timezone=True), nullable=True), sa.Column('notes', sa.String(), nullable=True), - sa.ForeignKeyConstraint(['gift_id'], ['gift_items.id'], ), - sa.ForeignKeyConstraint(['guest_id'], ['guests.id'], ), + sa.ForeignKeyConstraint(['gift_id'], ['gift_items.id'], ondelete="CASCADE"), + sa.ForeignKeyConstraint(['guest_id'], ['guests.id'], ondelete="CASCADE"), sa.PrimaryKeyConstraint('guest_id', 'gift_id') ) # ### end Alembic commands ### diff --git a/backend/app/models/gift.py b/backend/app/models/gift.py index d167e4b..2e16f71 100644 --- a/backend/app/models/gift.py +++ b/backend/app/models/gift.py @@ -68,10 +68,10 @@ class GiftItem(Base, UUIDMixin, TimestampMixin): category = relationship("GiftCategory", back_populates="gifts") reserved_by = relationship("Guest", secondary="guest_gifts", - back_populates="gifts") + back_populates="gifts", cascade='all') purchase_history = relationship("GiftPurchase", back_populates="gift_item", - order_by="desc(GiftPurchase.purchased_at)") + order_by="desc(GiftPurchase.purchased_at)", cascade='all, delete-orphan') def __repr__(self): return f""