From b9e97cc9c8c57268273ab152897b990944758a5e Mon Sep 17 00:00:00 2001 From: Johngreen Date: Tue, 10 Feb 2026 17:04:42 +0900 Subject: [PATCH] fix: resolve machine deletion failure after parts removal by nullifying orphaned FK references --- src/api/machines.py | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/api/machines.py b/src/api/machines.py index 1925a6a..cb2ef2a 100644 --- a/src/api/machines.py +++ b/src/api/machines.py @@ -3,12 +3,18 @@ from uuid import UUID from fastapi import APIRouter, HTTPException, Depends, Path from pydantic import BaseModel -from sqlalchemy import select, func +from sqlalchemy import select, func, update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import selectinload from src.database.config import get_db -from src.database.models import Machine, EquipmentPart +from src.database.models import ( + Machine, + EquipmentPart, + InspectionTemplate, + InspectionTemplateItem, + Alarm, +) from src.auth.models import TokenData from src.auth.dependencies import require_auth, verify_tenant_access @@ -288,6 +294,29 @@ async def delete_machine( detail=f"활성 부품이 {parts_count}개 있어 삭제할 수 없습니다. 먼저 부품을 제거해주세요.", ) + # Null out FKs in tables without cascade before deleting machine + part_ids_stmt = select(EquipmentPart.id).where( + EquipmentPart.machine_id == machine_id + ) + await db.execute( + update(InspectionTemplateItem) + .where(InspectionTemplateItem.equipment_part_id.in_(part_ids_stmt)) + .values(equipment_part_id=None) + ) + await db.execute( + update(Alarm) + .where(Alarm.equipment_part_id.in_(part_ids_stmt)) + .values(equipment_part_id=None) + ) + await db.execute( + update(InspectionTemplate) + .where(InspectionTemplate.machine_id == machine_id) + .values(machine_id=None) + ) + await db.execute( + update(Alarm).where(Alarm.machine_id == machine_id).values(machine_id=None) + ) + await db.delete(machine) await db.commit()