From c725b748c73aa86da86e38c3fd68e0ab65201597 Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 21 Oct 2026 09:55:48 +0300 Subject: [PATCH] fix(db): allow a request's SQLite connection to cross threads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FastAPI runs a sync dependency's setup, the endpoint and the teardown on whichever threadpool worker is free, so a connection opened on one thread was used/closed on another and sqlite3 raised ProgrammingError — 500s on /api/power, /api/energy/daily and /api/summary under concurrent requests (the dashboard fires three at once). Each request still gets its own connection, used by one thread at a time. Co-Authored-By: Claude Opus 5.5 --- backend/app/db.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/app/db.py b/backend/app/db.py index 6e4c945..c773355 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -53,7 +53,10 @@ CREATE TABLE IF NOT EXISTS meta ( def connect() -> sqlite3.Connection: path = get_settings().db_path os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - conn = sqlite3.connect(path, timeout=30) + # FastAPI may open, use and close a request's connection on different + # worker threads. Each request has its own connection used by one thread + # at a time, so the same-thread check can safely be off. + conn = sqlite3.connect(path, timeout=30, check_same_thread=False) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA synchronous=NORMAL")