From 613c8b8c5aabb7292b3c3cf720d69084dae5f111 Mon Sep 17 00:00:00 2001 From: malmert Date: Sun, 1 Mar 2026 17:57:24 +0100 Subject: [PATCH] test clear package api --- backend/src/api/packet_api.py | 25 +++++++++++++++++++++++++ backend/src/utilities/database.py | 23 +++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/backend/src/api/packet_api.py b/backend/src/api/packet_api.py index 42e5f6a..2a02f5f 100644 --- a/backend/src/api/packet_api.py +++ b/backend/src/api/packet_api.py @@ -142,3 +142,28 @@ async def websocket_packets(ws: WebSocket): except Exception: pass logger.debug("WebSocket connection closed and cleaned up for client %s", ws.client) + + +@router.delete("/packets") +async def clear_packets(reset_id: bool = Query(True)): + """ + Clear all packet logs from the database. + Uses TRUNCATE internally for high performance. + """ + db = shared.db + if db is None: + raise HTTPException(status_code=503, detail="Database not available") + + success = await db.clear_all_packets(reset_identity=reset_id) + + if not success: + raise HTTPException(status_code=500, detail="Failed to clear packet table") + + logger.info("User initiated clear_packets (reset_id=%s)", reset_id) + return JSONResponse( + content={ + "status": "success", + "message": "All packets have been cleared", + "reset_id": reset_id + } + ) diff --git a/backend/src/utilities/database.py b/backend/src/utilities/database.py index fec4c74..3534602 100644 --- a/backend/src/utilities/database.py +++ b/backend/src/utilities/database.py @@ -156,3 +156,26 @@ class DatabasePool: out.append(d) logger.exception(d) return out + + async def clear_all_packets(self, reset_identity: bool = True) -> bool: + """ + Deletes all rows from the `packets` table. + + If reset_identity is True, the auto-increment ID counter is reset to 1. + Returns True if successful, False otherwise. + """ + if self._pool is None: + await self.init_pool() + + # TRUNCATE is faster than DELETE and resets the identity counter + restart_clause = "RESTART IDENTITY" if reset_identity else "" + query = f"TRUNCATE TABLE packets {restart_clause};" + + try: + async with self._pool.acquire() as conn: + await conn.execute(query) + logger.info("Successfully cleared all packets from the database (reset_id=%s)", reset_identity) + return True + except Exception: + logger.exception("Failed to clear packets table") + return False