fix(devices): device deletion detaches reading history instead of 500ing

Deleting any device whose stats rows still referenced it failed with
500: reading_history.device_id is a NO-ACTION FK by design (the rows
are real captured reading stats — Users reads them), so a blind DELETE
violated the constraint. Surfaced by the Android app's new logout
deregister call, but the admin Devices page Deletes hit the same stone.

Fix: DetachReadingHistoryFromDevice — NULL the device association on
the user's history rows before the device DELETE (single handler
pass). device_id is nullable; the stats survive, the device frees its
identifier. sqlc regenerated.
This commit is contained in:
John O'Keefe committed 2026-10-29 11:57:20 -04:00
1 parent 313268a7ae
commit d49a9e6ca2
4 files changed
+34

No files matched your search

+6
View File
@@ -433,6 +433,12 @@ func (h *DeviceHandler) DeleteDevice(c *echo.Context) error {
return c.JSON(http.StatusForbidden, map[string]string{"error": "access denied"})
}
// Detach reading history first: the history FK to devices is NO
// ACTION on purpose (rows are real captured stats); NULLing the
// device association keeps the stats while freeing the device.
if err := h.db.DetachReadingHistoryFromDevice(c.Request().Context(), pgDeviceID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to detach device history"})
}
if err := h.db.DeleteDevice(c.Request().Context(), pgDeviceID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to delete device"})
}