fix(db): allow a request's SQLite connection to cross threads

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 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 09:55:48 +03:00
co-authored by Claude Opus 5.5
parent 42c7d18207
commit c725b748c7
+4 -1
View File
@@ -53,7 +53,10 @@ CREATE TABLE IF NOT EXISTS meta (
def connect() -> sqlite3.Connection: def connect() -> sqlite3.Connection:
path = get_settings().db_path path = get_settings().db_path
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) 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.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL") conn.execute("PRAGMA synchronous=NORMAL")