Files
romm/backend/handler/database/platforms_handler.py
Sam Dornan fd9a33bc35 fix(backend): return identifiers without building an ORM row per id (#4586)
* fix(backend): project the identifier endpoints onto the id column

The `/identifiers` routes for saves, states, firmware, platforms, smart
collections and rom notes each asked their handler for entities with
`only_fields=[Model.id]`. `load_only` narrows the selected columns but does
not cancel an eager relationship, so a `lazy="joined"` join still fired and a
full entity was still built for every row. The platforms route was the worst
of the six: `with_firmware` eager-loads every firmware row and its platform,
and `load_only` does not cancel that either.

Each handler grows a small query builder shared by its existing accessor and a
new `*_ids` accessor that projects onto the id column with
`with_only_columns`, which drops the entity and with it the eager joins. The
firmware accessor already applied `noload`, so its SQL is unchanged; it moves
to the projection only to stop building rows.

`/api/users/identifiers` and the two `/collections` callers that use more than
an id are left alone, because nothing eager fires for them.

The `executed_statements` fixture moves to `tests/conftest.py` so the new
endpoint tests can use it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Update backend/tests/endpoints/test_identifier_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* style(backend): drop the leading blank line black rejects

Removing the module docstring in the GitHub edit left an empty first line,
which is the only thing black wanted to change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(backend): drive the note-identifier test through the endpoint

Greptile flagged the handler-level test for bypassing the route's auth,
404, and visibility checks. It now issues the request the frontend would
and asserts the id-only projection holds among the route's own reads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(backend): fold the duplicate SQL-capture fixtures into the shared one

Step 3 of the PR-ready gauntlet (simplify). The shared
`executed_statements` fixture gains the two roms test files that still
declared byte-identical local copies, and the id-only assertions share one
statement parser instead of two.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(backend): tighten the get_platform_ids docstring to one line

Step 4 of the PR-ready gauntlet (review-polish).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-09-17 11:13:07 -05:00

172 lines
5.2 KiB
Python

import functools
from collections.abc import Sequence
from datetime import datetime
from sqlalchemy import delete, or_, select, update
from sqlalchemy.orm import Query, Session, selectinload
from decorators.database import begin_session
from models.platform import Platform
from models.rom import Rom
from .base_handler import DBBaseHandler
def with_firmware(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs["query"] = select(Platform).options(
selectinload(Platform.firmware),
)
return func(*args, **kwargs)
return wrapper
class DBPlatformsHandler(DBBaseHandler):
@begin_session
@with_firmware
def add_platform(
self,
platform: Platform,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Platform:
platform = session.merge(platform)
session.flush()
return session.scalar(query.filter_by(id=platform.id).limit(1))
@begin_session
def update_platform(
self,
id: int,
data: dict,
session: Session = None, # type: ignore
) -> Platform:
session.execute(
update(Platform)
.where(Platform.id == id)
.values(**data)
.execution_options(synchronize_session="evaluate")
)
return session.query(Platform).filter_by(id=id).one()
@begin_session
@with_firmware
def get_platform(
self,
id: int,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Platform | None:
return session.scalar(query.filter_by(id=id).limit(1))
@begin_session
@with_firmware
def get_platforms(
self,
updated_after: datetime | None = None,
hidden_platform_ids: Sequence[int] | None = None,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Sequence[Platform]:
if updated_after:
query = query.filter(Platform.updated_at > updated_after)
# Admin-driven visibility (opt-out): exclude platforms hidden from the
# caller. Empty/None (e.g. admins) skips filtering.
if hidden_platform_ids:
query = query.filter(Platform.id.not_in(hidden_platform_ids))
return session.scalars(query.order_by(Platform.name.asc())).unique().all()
@begin_session
def get_platform_ids(
self,
hidden_platform_ids: Sequence[int] | None = None,
session: Session = None, # type: ignore
) -> list[int]:
"""Ids only, deliberately off `with_firmware`: its eager load fires anyway."""
query = select(Platform).order_by(Platform.name.asc())
if hidden_platform_ids:
query = query.filter(Platform.id.not_in(hidden_platform_ids))
return list(session.scalars(query.with_only_columns(Platform.id)).all())
@begin_session
@with_firmware
def get_platform_by_fs_slug(
self,
fs_slug: str,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Platform | None:
return session.scalar(query.filter_by(fs_slug=fs_slug).limit(1))
@begin_session
@with_firmware
def get_platform_by_slug(
self,
slug: str,
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Platform | None:
return session.scalar(query.filter_by(slug=slug).limit(1))
@begin_session
def delete_platform(
self,
id: int,
session: Session = None, # type: ignore
) -> None:
# Remove all roms from that platforms first
session.execute(
delete(Rom)
.where(Rom.platform_id == id)
.execution_options(synchronize_session="evaluate")
)
session.execute(
delete(Platform)
.where(Platform.id == id)
.execution_options(synchronize_session="evaluate")
)
@begin_session
def mark_missing_platforms(
self,
fs_platforms_to_keep: list[str],
query: Query = None, # type: ignore
session: Session = None, # type: ignore
) -> Sequence[Platform]:
missing_platforms = (
session.scalars(
select(Platform)
.order_by(Platform.name.asc())
.where(
or_(
Platform.fs_slug.not_in(fs_platforms_to_keep),
Platform.slug.is_(None),
)
)
) # type: ignore[attr-defined]
.unique()
.all()
)
session.execute(
update(Platform)
.where(or_(Platform.fs_slug.not_in(fs_platforms_to_keep), Platform.slug.is_(None))) # type: ignore[attr-defined]
.values(**{"missing_from_fs": True})
.execution_options(synchronize_session="fetch")
)
session.execute(
update(Rom)
.where(Rom.platform_id.in_([p.id for p in missing_platforms])) # type: ignore[attr-defined]
.values(**{"missing_from_fs": True})
.execution_options(synchronize_session="fetch")
)
return missing_platforms