Files
refusol-datalogging/backend/app/db.py
T
bonaminandClaude Opus 5.5 c725b748c7 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>
2026-10-21 09:55:48 +03:00

108 lines
3.4 KiB
Python

import os
import sqlite3
from collections.abc import Iterator
from contextlib import contextmanager
from .config import get_settings
from .fields import FIELDS
SCHEMA = """
CREATE TABLE IF NOT EXISTS inverters (
id TEXT PRIMARY KEY,
name TEXT,
capacity_kwp REAL,
mppt_count INTEGER NOT NULL DEFAULT 2,
sort_order INTEGER NOT NULL DEFAULT 0,
notes TEXT,
first_seen INTEGER,
last_seen INTEGER
);
-- One row per inverter per poll cycle. ts = unix seconds, UTC.
-- The per-parameter columns are added from fields.py by migrate().
CREATE TABLE IF NOT EXISTS readings (
inverter_id TEXT NOT NULL,
ts INTEGER NOT NULL,
extra TEXT,
PRIMARY KEY (inverter_id, ts)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS readings_ts ON readings (ts);
-- Daily rollup, kept forever (readings are purged after the retention
-- period). day is the local date at the site (SITE_TIMEZONE).
CREATE TABLE IF NOT EXISTS daily_energy (
inverter_id TEXT NOT NULL,
day TEXT NOT NULL,
daily_energy_wh INTEGER,
total_min_wh INTEGER,
total_max_wh INTEGER,
peak_power_w INTEGER,
-- AC power integrated over time: the fallback while the inverter's
-- own energy counters aren't decoded
integrated_wh REAL,
PRIMARY KEY (inverter_id, day)
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value TEXT
);
"""
def connect() -> sqlite3.Connection:
path = get_settings().db_path
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
# 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")
return conn
@contextmanager
def session() -> Iterator[sqlite3.Connection]:
conn = connect()
try:
with conn:
yield conn
finally:
conn.close()
def get_db() -> Iterator[sqlite3.Connection]:
with session() as conn:
yield conn
def migrate() -> bool:
"""Create/upgrade the schema. Returns True when the integrated-energy
column was just added and has to be rebuilt from existing readings."""
with session() as conn:
conn.executescript(SCHEMA)
existing = {r["name"] for r in conn.execute("PRAGMA table_info(readings)")}
for f in FIELDS:
if f.key not in existing:
conn.execute(f"ALTER TABLE readings ADD COLUMN {f.key} {f.sql_type}")
daily_cols = {r["name"] for r in conn.execute("PRAGMA table_info(daily_energy)")}
if "integrated_wh" not in daily_cols:
conn.execute("ALTER TABLE daily_energy ADD COLUMN integrated_wh REAL")
return True
return False
def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
return row["value"] if row else None
def set_meta(conn: sqlite3.Connection, key: str, value: str) -> None:
conn.execute(
"INSERT INTO meta (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, value),
)