Files
romm/backend/handler/database/firmware_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

160 lines
4.8 KiB
Python

from collections.abc import Sequence
from sqlalchemy import Select, and_, delete, select, update
from sqlalchemy.orm import Session, noload
from decorators.database import begin_session
from models.firmware import Firmware
from .base_handler import DBBaseHandler
class DBFirmwareHandler(DBBaseHandler):
@begin_session
def add_firmware(
self,
firmware: Firmware,
session: Session = None, # type: ignore
) -> Firmware:
return session.merge(firmware)
@begin_session
def get_firmware(
self,
id: int,
*,
session: Session = None, # type: ignore
) -> Firmware | None:
return session.scalar(select(Firmware).filter_by(id=id).limit(1))
def _firmware_query(
self,
*,
platform_ids: Sequence[int] | None = None,
missing: bool | None = None,
hidden_platform_ids: Sequence[int] | None = None,
) -> Select[tuple[Firmware]]:
query = select(Firmware).order_by(Firmware.file_name.asc())
if platform_ids:
query = query.filter(Firmware.platform_id.in_(platform_ids))
if missing is not None:
query = query.filter(Firmware.missing_from_fs == missing)
# Firmware inherits its platform's visibility: hide firmware whose
# platform an admin has hidden from the caller.
if hidden_platform_ids:
query = query.filter(Firmware.platform_id.not_in(hidden_platform_ids))
return query
@begin_session
def list_firmware(
self,
*,
platform_ids: Sequence[int] | None = None,
missing: bool | None = None,
hidden_platform_ids: Sequence[int] | None = None,
session: Session = None, # type: ignore
) -> Sequence[Firmware]:
query = self._firmware_query(
platform_ids=platform_ids,
missing=missing,
hidden_platform_ids=hidden_platform_ids,
)
# `Firmware.platform` is lazy="joined", which drags in Platform's
# rom_count and fs_size_bytes subqueries. No caller here reads it.
return session.scalars(query.options(noload(Firmware.platform))).all()
@begin_session
def list_firmware_ids(
self,
*,
platform_ids: Sequence[int] | None = None,
missing: bool | None = None,
hidden_platform_ids: Sequence[int] | None = None,
session: Session = None, # type: ignore
) -> list[int]:
"""Ids only, so no `Firmware` is built and no eager platform join fires."""
query = self._firmware_query(
platform_ids=platform_ids,
missing=missing,
hidden_platform_ids=hidden_platform_ids,
)
return list(session.scalars(query.with_only_columns(Firmware.id)).all())
@begin_session
def get_firmware_by_filename(
self,
platform_id: int,
file_name: str,
session: Session = None, # type: ignore
):
return session.scalar(
select(Firmware)
.filter_by(platform_id=platform_id, file_name=file_name)
.limit(1)
)
@begin_session
def update_firmware(
self,
id: int,
data: dict,
session: Session = None, # type: ignore
) -> Firmware:
session.execute(
update(Firmware)
.where(Firmware.id == id)
.values(**data)
.execution_options(synchronize_session="evaluate")
)
return session.query(Firmware).filter_by(id=id).one()
@begin_session
def delete_firmware(
self,
id: int,
session: Session = None, # type: ignore
) -> None:
session.execute(
delete(Firmware)
.where(Firmware.id == id)
.execution_options(synchronize_session="evaluate")
)
@begin_session
def mark_missing_firmware(
self,
platform_id: int,
fs_firmwares_to_keep: list[str],
session: Session = None, # type: ignore
) -> Sequence[Firmware]:
missing_firmware = (
session.scalars(
select(Firmware)
.order_by(Firmware.file_name.asc())
.where(
and_(
Firmware.platform_id == platform_id,
Firmware.file_name.not_in(fs_firmwares_to_keep),
)
)
) # type: ignore[attr-defined]
.unique()
.all()
)
session.execute(
update(Firmware)
.where(
and_(
Firmware.platform_id == platform_id,
Firmware.file_name.not_in(fs_firmwares_to_keep),
)
)
.values(**{"missing_from_fs": True})
.execution_options(synchronize_session="evaluate")
)
return missing_firmware