Skip to content

Commit 269040d

Browse files
authored
♻️ Refactor models to use cascade delete relationships (#1276)
1 parent d4ae12c commit 269040d

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""Add cascade delete relationships
2+
3+
Revision ID: 1a31ce608336
4+
Revises: d98dd8ec85a3
5+
Create Date: 2024-07-31 22:24:34.447891
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
import sqlmodel.sql.sqltypes
11+
12+
13+
# revision identifiers, used by Alembic.
14+
revision = '1a31ce608336'
15+
down_revision = 'd98dd8ec85a3'
16+
branch_labels = None
17+
depends_on = None
18+
19+
20+
def upgrade():
21+
# ### commands auto generated by Alembic - please adjust! ###
22+
op.alter_column('item', 'owner_id',
23+
existing_type=sa.UUID(),
24+
nullable=False)
25+
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
26+
op.create_foreign_key(None, 'item', 'user', ['owner_id'], ['id'], ondelete='CASCADE')
27+
# ### end Alembic commands ###
28+
29+
30+
def downgrade():
31+
# ### commands auto generated by Alembic - please adjust! ###
32+
op.drop_constraint(None, 'item', type_='foreignkey')
33+
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
34+
op.alter_column('item', 'owner_id',
35+
existing_type=sa.UUID(),
36+
nullable=True)
37+
# ### end Alembic commands ###

backend/app/models.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class UpdatePassword(SQLModel):
4343
class User(UserBase, table=True):
4444
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
4545
hashed_password: str
46-
items: list["Item"] = Relationship(back_populates="owner")
46+
items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)
4747

4848

4949
# Properties to return via API, id is always required
@@ -76,7 +76,9 @@ class ItemUpdate(ItemBase):
7676
class Item(ItemBase, table=True):
7777
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
7878
title: str = Field(max_length=255)
79-
owner_id: uuid.UUID = Field(foreign_key="user.id", nullable=False)
79+
owner_id: uuid.UUID = Field(
80+
foreign_key="user.id", nullable=False, ondelete="CASCADE"
81+
)
8082
owner: User | None = Relationship(back_populates="items")
8183

8284

0 commit comments

Comments
 (0)