Skip to content

Commit c6a9713

Browse files
committed
add: delete sensor on cascade measurements
1 parent 23c5295 commit c6a9713

3 files changed

Lines changed: 52 additions & 2 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""add cascade delete to measurements.sensorid foreign key
2+
3+
Revision ID: 778a9dbdeb5e
4+
Revises: add_unique_constraint_to_values
5+
Create Date: 2025-08-02 15:47:56.175249
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = '778a9dbdeb5e'
16+
down_revision: Union[str, None] = 'add_unique_constraint_to_values'
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade() -> None:
22+
"""Upgrade schema."""
23+
# Drop the existing foreign key constraint
24+
op.drop_constraint('measurements_sensorid_fkey', 'measurements', type_='foreignkey')
25+
26+
# Add the new foreign key constraint with CASCADE delete
27+
op.create_foreign_key(
28+
'measurements_sensorid_fkey',
29+
'measurements',
30+
'sensors',
31+
['sensorid'],
32+
['sensorid'],
33+
ondelete='CASCADE'
34+
)
35+
36+
37+
def downgrade() -> None:
38+
"""Downgrade schema."""
39+
# Drop the CASCADE foreign key constraint
40+
op.drop_constraint('measurements_sensorid_fkey', 'measurements', type_='foreignkey')
41+
42+
# Recreate the original foreign key constraint without CASCADE
43+
op.create_foreign_key(
44+
'measurements_sensorid_fkey',
45+
'measurements',
46+
'sensors',
47+
['sensorid'],
48+
['sensorid']
49+
)

app/db/models/measurement.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class Measurement(Base):
1212
__tablename__ = "measurements"
1313

1414
measurementid: Mapped[int] = mapped_column(primary_key=True, index=True)
15-
sensorid: Mapped[int] = mapped_column(ForeignKey("sensors.sensorid"))
15+
sensorid: Mapped[int] = mapped_column(ForeignKey("sensors.sensorid", ondelete="CASCADE"))
1616
stationid: Mapped[int] = mapped_column()
1717
collectiontime: Mapped[datetime] = mapped_column()
1818
measurementvalue: Mapped[float] = mapped_column()

app/db/repositories/sensor_repository.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,9 @@ def get_sensors(
257257
return result, total_count
258258

259259
def delete_sensor(self, sensor_id: int) -> bool:
260-
db_sensor = self.get_sensor(sensor_id)
260+
db_sensor = self.db.query(Sensor).filter(Sensor.sensorid == sensor_id).first()
261261
if db_sensor:
262+
# Database CASCADE will automatically delete measurements and statistics
262263
self.db.delete(db_sensor)
263264
self.db.commit()
264265
return True

0 commit comments

Comments
 (0)