"""Durable calculation history for PostgreSQL, with a local SQLite fallback.""" from __future__ import annotations import json import os import sqlite3 from pathlib import Path from typing import Any class CalculationStore: """Persist successful calculations without coupling the domain to a database.""" def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: self.database_url = database_url or "" self.sqlite_path = Path(sqlite_path) if sqlite_path else None if self.database_url.startswith(("postgres://", "postgresql://")): import psycopg self._psycopg = psycopg self._ensure_postgres_schema() else: self.sqlite_path = self.sqlite_path or Path("data/belki.sqlite3") self.sqlite_path.parent.mkdir(parents=True, exist_ok=True) self._ensure_sqlite_schema() @classmethod def from_environment(cls) -> "CalculationStore": return cls( database_url=os.getenv("BELKI_DATABASE_URL"), sqlite_path=os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"), ) def _ensure_sqlite_schema(self) -> None: with sqlite3.connect(self.sqlite_path) as connection: connection.execute( """CREATE TABLE IF NOT EXISTS calculations ( id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER, source TEXT NOT NULL, mode TEXT NOT NULL, input_json TEXT NOT NULL, result_json TEXT, message TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP )""" ) def _ensure_postgres_schema(self) -> None: with self._psycopg.connect(self.database_url) as connection: connection.execute( """CREATE TABLE IF NOT EXISTS belki_calculations ( id BIGSERIAL PRIMARY KEY, actor_id BIGINT, source TEXT NOT NULL, mode TEXT NOT NULL, input_json JSONB NOT NULL, result_json JSONB, message TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )""" ) def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int: mode = str(payload.get("mode", response.get("mode", "unknown"))) message = str(response["message"]) result = response.get("result") if self.database_url.startswith(("postgres://", "postgresql://")): from psycopg.types.json import Jsonb with self._psycopg.connect(self.database_url) as connection: row = connection.execute( """INSERT INTO belki_calculations (actor_id, source, mode, input_json, result_json, message) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""", (actor_id, source, mode, Jsonb(payload), Jsonb(result) if result is not None else None, message), ).fetchone() return int(row[0]) with sqlite3.connect(self.sqlite_path) as connection: cursor = connection.execute( """INSERT INTO calculations (actor_id, source, mode, input_json, result_json, message) VALUES (?, ?, ?, ?, ?, ?)""", (actor_id, source, mode, json.dumps(payload, ensure_ascii=False), json.dumps(result, ensure_ascii=False) if result is not None else None, message), ) return int(cursor.lastrowid)