"""Small shared Plex row lookups, so the get-by-rating_key pattern lives in one place.""" from typing import TypeVar from sqlalchemy import select from sqlalchemy.orm import Session _M = TypeVar("_M") def by_rating_key(db: Session, model: type[_M], rating_key: str) -> _M | None: """The mirrored row for a Plex rating_key, or None. `model` is any of the rating_key-keyed Plex tables (PlexItem / PlexShow / PlexSeason / PlexCollection); the return type is that model, so call sites keep their `Model | None` static type. A key with a NUL in it (`%00` in a path segment) names no row — a 404, like any unknown key. Postgres refuses NUL in text, so asking would be a DataError; the app-wide handler turns the places that DO ask (lists and filters compared to rating_key) into a 422 (see main.py).""" if "\x00" in str(rating_key): return None return db.execute(select(model).where(model.rating_key == str(rating_key))).scalars().first()