Implement milestone M2 (backend setup):
- FastAPI app factory (core/app.py) with CORS, lifespan table
creation, and global error handlers using a standardized
{detail, code, errors?} envelope
- Endpoints: GET /health, GET /api/v1/health, GET /api/v1/version
- SQLAlchemy 2.0 ORM: Article, Author, Category models with
relationships, unique constraints, and FK pragma for SQLite
- Pydantic v2 schemas (create/update/read) for all models
- Env-driven config (DATABASE_URL, CORS_ORIGINS) + .env.example
- pytest suite (19 tests, ~95% coverage) with per-test SQLite
databases via fixtures
- Dockerfile (python:3.11-slim) and docker-compose.yml with a
persistent ./data/db volume and healthcheck
65 lines
1.9 KiB
Python
65 lines
1.9 KiB
Python
"""SQLAlchemy engine and session management.
|
|
|
|
The engine is created once at import time from ``config.get_settings()``.
|
|
For SQLite, the parent directory of the database file is created when it
|
|
does not exist yet (the Docker volume mount provides it in containers),
|
|
and the ``foreign_keys`` pragma is enabled on every connection because
|
|
SQLite has it disabled by default.
|
|
"""
|
|
|
|
from collections.abc import Generator
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.engine import Engine
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
|
|
def _ensure_sqlite_dir(database_url: str) -> None:
|
|
"""Create the parent directory of a file-based SQLite database."""
|
|
prefix = "sqlite:///"
|
|
if not database_url.startswith(prefix):
|
|
return
|
|
db_path = Path(database_url.removeprefix(prefix))
|
|
if not db_path.parts or db_path.name == ":memory:":
|
|
return
|
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
if settings.is_sqlite:
|
|
_ensure_sqlite_dir(settings.database_url)
|
|
connect_args: dict = {"check_same_thread": False}
|
|
else:
|
|
connect_args = {}
|
|
|
|
engine: Engine = create_engine(
|
|
settings.database_url,
|
|
connect_args=connect_args,
|
|
echo=False,
|
|
)
|
|
|
|
if settings.is_sqlite:
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None: # pragma: no cover
|
|
"""Enforce foreign key constraints (OFF by default in SQLite)."""
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
cursor.close()
|
|
|
|
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
"""FastAPI dependency that yields a database session and always closes it."""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|