"""SQLAlchemy engine and session construction for the Hub database only.""" from __future__ import annotations from collections.abc import Callable from datetime import UTC, datetime from typing import Any from sqlalchemy import Engine, create_engine, event from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker class Base(DeclarativeBase): """Declarative root for Hub-owned tables; ContextForge is never imported.""" def utc_now() -> datetime: return datetime.now(UTC) def create_engine_from_url(database_url: str, **kwargs: Any) -> Engine: """Create an engine with safe SQLite test defaults and explicit pool settings.""" options: dict[str, Any] = {"future": True, "pool_pre_ping": True, **kwargs} if database_url.startswith("sqlite"): options.setdefault("connect_args", {"check_same_thread": False}) engine = create_engine(database_url, **options) if database_url.startswith("sqlite"): def enable_sqlite_foreign_keys(dbapi_connection: Any, _: Any) -> None: dbapi_connection.execute("PRAGMA foreign_keys=ON") event.listen(engine, "connect", enable_sqlite_foreign_keys) return engine def session_factory(engine: Engine) -> Callable[[], Session]: """Return an explicit session factory; no hidden global session is used.""" return sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, class_=Session)