- pyproject.toml con FastAPI, SQLAlchemy 2.x, Alembic, Pydantic v2, openpyxl, rapidfuzz, Faker; dev: pytest, httpx, ruff - app/: config desde entorno, engine SQLite con WAL y sesión sin borrado físico, stubs por fase - seed/ y tests/fixtures/ con README; .gitignore excluye *.xlsx fuera de seed/ y tests/fixtures/ - test de /api/health con cliente de prueba y SQLite en memoria
61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
"""Engine SQLite (WAL activado), fábrica de sesiones y dependencia `get_db` para FastAPI.
|
|
|
|
Las sesiones rechazan borrados físicos: el historial es append-only (sección 3 del brief).
|
|
"""
|
|
|
|
from collections.abc import Iterator
|
|
|
|
from sqlalchemy import Engine, create_engine, event
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from app.config import get_settings
|
|
|
|
|
|
class BorradoProhibidoError(RuntimeError):
|
|
"""Ninguna tabla admite DELETE a nivel aplicación."""
|
|
|
|
|
|
def crear_engine(database_url: str) -> Engine:
|
|
"""Crea el engine. Para SQLite activa WAL y claves foráneas en cada conexión."""
|
|
kwargs: dict = {}
|
|
if database_url.startswith("sqlite"):
|
|
kwargs["connect_args"] = {"check_same_thread": False}
|
|
if database_url in ("sqlite://", "sqlite:///:memory:"):
|
|
kwargs["poolclass"] = StaticPool
|
|
|
|
engine = create_engine(database_url, **kwargs)
|
|
|
|
if database_url.startswith("sqlite"):
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def _pragmas(dbapi_connection, _record) -> None:
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA journal_mode=WAL")
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
cursor.execute("PRAGMA busy_timeout=5000")
|
|
cursor.close()
|
|
|
|
return engine
|
|
|
|
|
|
def crear_session_factory(engine: Engine) -> sessionmaker[Session]:
|
|
factory = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
|
|
|
@event.listens_for(factory, "before_flush")
|
|
def _sin_borrado_fisico(session: Session, _ctx, _instances) -> None:
|
|
if session.deleted:
|
|
entidades = ", ".join(type(obj).__name__ for obj in session.deleted)
|
|
raise BorradoProhibidoError(f"Borrado físico prohibido: {entidades}")
|
|
|
|
return factory
|
|
|
|
|
|
engine = crear_engine(get_settings().database_url)
|
|
SessionLocal = crear_session_factory(engine)
|
|
|
|
|
|
def get_db() -> Iterator[Session]:
|
|
with SessionLocal() as session:
|
|
yield session
|