"""The one persistent store: SQLite (stdlib) in backend.db next to this module. sessions — one row per transaction: cp, connector, idTag, resolved "who", start/end timestamps (charger-reported), meter readings, Wh, reason samples — per-minute MeterValues while charging (energy/power/SoC) for later charts settings — the app state sections (users, allowlist, relays, chargers, learn_mode, session_secret) as JSON blobs, one row per section. Always whole-section reads/writes, so blobs beat normalized tables here. Managed through config.py — see there. The events.jsonl journal (journal.py) stays the raw ground truth; this is the queryable view. Transaction ids come from MAX(tx)+1 here, so they survive backend restarts. sqlite3 connections are cheap at household scale — one per call, no pooling. BACKEND_DB env var overrides the path (used by tests to stay off the real db). """ import json import os import sqlite3 from contextlib import closing from pathlib import Path from typing import Optional HERE = Path(__file__).resolve().parent DB_PATH = Path(os.environ.get("BACKEND_DB", HERE / "backend.db")) _SCHEMA = """ CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS sessions ( tx INTEGER PRIMARY KEY, cp TEXT NOT NULL, connector INTEGER NOT NULL, id_tag TEXT NOT NULL, who TEXT, started TEXT NOT NULL, ended TEXT, meter_start REAL NOT NULL, meter_stop REAL, wh REAL, reason TEXT, method TEXT ); CREATE TABLE IF NOT EXISTS samples ( tx INTEGER NOT NULL, time TEXT NOT NULL, energy_wh REAL, power_w REAL, soc REAL ); CREATE INDEX IF NOT EXISTS idx_samples_tx ON samples (tx); CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions (started); """ def _db(): """Context manager: commits on success AND closes (a bare `with sqlite3 .connect(...)` only commits — the handle would leak).""" con = sqlite3.connect(DB_PATH) con.row_factory = sqlite3.Row con.executescript(_SCHEMA) # migration for dbs created before the audit column existed cols = [row[1] for row in con.execute("PRAGMA table_info(sessions)")] if "method" not in cols: con.execute("ALTER TABLE sessions ADD COLUMN method TEXT") return closing(con) def load_settings() -> dict: with _db() as con, con: return { row["key"]: json.loads(row["value"]) for row in con.execute("SELECT key, value FROM settings") } def save_settings(sections: dict) -> None: with _db() as con, con: con.executemany( "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", [(key, json.dumps(value, ensure_ascii=False)) for key, value in sections.items()], ) def max_tx() -> int: with _db() as con, con: row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone() return row["m"] or 0 def start_session(tx: int, cp: str, connector: int, id_tag: str, who: str, started: str, meter_start: float, method: str = "unknown") -> None: with _db() as con, con: con.execute( "INSERT OR REPLACE INTO sessions" " (tx, cp, connector, id_tag, who, started, meter_start, method)" " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (tx, cp, connector, id_tag, who, started, meter_start, method), ) def end_session(tx: int, ended: str, meter_stop: float, reason: Optional[str] = None) -> None: with _db() as con, con: con.execute( "UPDATE sessions SET ended = ?, meter_stop = ?, reason = ?," " wh = ? - meter_start WHERE tx = ?", (ended, meter_stop, reason, meter_stop, tx), ) def add_sample(tx: int, time: str, energy_wh: Optional[float], power_w: Optional[float], soc: Optional[float]) -> None: with _db() as con, con: con.execute( "INSERT INTO samples (tx, time, energy_wh, power_w, soc) VALUES (?, ?, ?, ?, ?)", (tx, time, energy_wh, power_w, soc), ) def get_session(tx: int) -> Optional[dict]: with _db() as con, con: row = con.execute("SELECT * FROM sessions WHERE tx = ?", (tx,)).fetchone() return dict(row) if row else None def open_session(tx: int) -> Optional[dict]: """An unfinished session (e.g. still running after a backend restart).""" with _db() as con, con: row = con.execute( "SELECT * FROM sessions WHERE tx = ? AND ended IS NULL", (tx,) ).fetchone() return dict(row) if row else None def query_sessions(limit: int = 50, cp: Optional[str] = None, connector: Optional[int] = None) -> list: sql, args = "SELECT * FROM sessions", [] where = [] if cp is not None: where.append("cp = ?") args.append(cp) if connector is not None: where.append("connector = ?") args.append(connector) if where: sql += " WHERE " + " AND ".join(where) sql += " ORDER BY tx DESC LIMIT ?" args.append(limit) with _db() as con, con: return [dict(row) for row in con.execute(sql, args)] def samples_for(tx: int) -> list: with _db() as con, con: return [ dict(row) for row in con.execute("SELECT * FROM samples WHERE tx = ? ORDER BY time", (tx,)) ]