"""Optional SQLAlchemy client for Neon PostgreSQL analytics storage.""" from __future__ import annotations from pathlib import Path from typing import Any try: from sqlalchemy import create_engine, text from sqlalchemy.exc import SQLAlchemyError except ImportError: create_engine = text = None # type: ignore[assignment] class SQLAlchemyError(Exception): pass from src.config import Settings, get_settings class NeonClient: def __init__( self, settings: Settings | None = None, engine: Any | None = None ) -> None: self.settings = settings or get_settings() self.engine = engine @staticmethod def _statement(query: str) -> Any: return text(query) if text is not None else query def is_configured(self) -> bool: return bool(self.settings.neon_configured and create_engine is not None) def connect(self) -> bool: if self.engine is not None: return True if not self.is_configured(): return False try: self.engine = create_engine(self.settings.database_url, pool_pre_ping=True) return True except (SQLAlchemyError, ValueError, TypeError): self.engine = None return False def close(self) -> None: if self.engine is not None: try: self.engine.dispose() finally: self.engine = None def test_connection(self) -> bool: if not self.connect(): return False try: with self.engine.connect() as connection: connection.execute(self._statement("SELECT 1")) return True except (SQLAlchemyError, RuntimeError): return False def execute(self, query: str, params: dict[str, Any] | None = None) -> bool: if not self.connect() or not query.strip(): return False try: with self.engine.begin() as connection: connection.execute(self._statement(query), params or {}) return True except (SQLAlchemyError, RuntimeError): return False def fetch_all( self, query: str, params: dict[str, Any] | None = None ) -> list[dict[str, Any]]: if not self.connect() or not query.strip(): return [] try: with self.engine.connect() as connection: return [ dict(row) for row in connection.execute( self._statement(query), params or {} ).mappings() ] except (SQLAlchemyError, RuntimeError): return [] def execute_schema(self, schema_path: str = "schema/neon_schema.sql") -> bool: path = Path(schema_path) if not path.is_file() or not self.connect(): return False try: with self.engine.begin() as connection: for statement in ( item.strip() for item in path.read_text(encoding="utf-8").split(";") if item.strip() ): connection.execute(self._statement(statement)) return True except (SQLAlchemyError, RuntimeError, OSError): return False