Files
romm/backend/models/collection.py
Spinnich f4ac78c46b perf(collections): serve smart collections from a composed query
A smart collection re-ran its filters across the whole library on every
request, loaded every match into memory with its joined metadata, wrote
the membership back, and only then asked for the page being displayed.
The cost tracked library size rather than collection size, was paid twice
on first load and again on every scroll, and the write bumped updated_at,
which the covers embed as a ?ts= cache-buster.

Translate the stored filter_criteria into filter_roms keyword arguments
and apply them to a bare Rom.id select instead, so membership stays in
SQL and the database returns just the rows being rendered. The criteria
vocabulary is filter_roms' own, so this composes with the gallery's
filters. smart_collection_id is dropped from the criteria: the v2 create
dialog records the route it was opened from, so a collection built while
viewing another one carries its id, which would nest and could cycle.

Bind parameters for the MATCH clauses are now named after the term they
carry. A statement can hold two of them (the collection's search term and
the gallery's), and SQLAlchemy does not uniquify explicitly named text()
parameters, so a fixed name let one term overwrite the other.

The cached rom_ids / rom_count / path_covers_* columns still back the
collections list and the ROM detail page, so refresh them on write --
smart collection create and update, after a scan, and after ROMs are
deleted -- rather than as a side effect of browsing. They are computed
for the owner: the row is shared, so a per-user criterion like favorite
would otherwise describe whoever opened the collection last.

Regular collections and the favorites filter get the smaller half of the
same treatment: an indexed subquery over collections_roms instead of an
IN list built in Python. An unknown collection or smart collection now
returns nothing rather than falling through to the entire library.

Fixes #4029

AI assistance: implemented with Claude Code (Opus 5), tests first, then
reviewed and verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 20:23:31 +00:00

249 lines
7.5 KiB
Python

from __future__ import annotations
import base64
import json
from typing import TYPE_CHECKING, Any
from sqlalchemy import ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from config import FRONTEND_RESOURCES_PATH
from models.base import BaseModel
from utils.database import CustomJSON
if TYPE_CHECKING:
from models.rom import Rom
from models.user import User
class Collection(BaseModel):
__tablename__ = "collections"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(length=400))
description: Mapped[str | None] = mapped_column(Text)
is_public: Mapped[bool] = mapped_column(default=False)
is_favorite: Mapped[bool] = mapped_column(default=False)
path_cover_l: Mapped[str | None] = mapped_column(Text, default="")
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
url_cover: Mapped[str | None] = mapped_column(
Text, default="", doc="URL of cover pulled from metadata providers"
)
roms: Mapped[list["Rom"]] = relationship(
"Rom",
secondary="collections_roms",
collection_class=set,
back_populates="collections",
lazy="raise",
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
user: Mapped["User"] = relationship(lazy="joined", back_populates="collections")
@property
def owner_username(self) -> str:
return self.user.username
@property
def rom_ids(self) -> list[int]:
return [r.id for r in self.roms]
@property
def rom_count(self) -> int:
return len(self.roms)
@property
def fs_resources_path(self) -> str:
return f"collections/{str(self.id)}"
@property
def path_cover_small(self) -> str | None:
return (
f"{FRONTEND_RESOURCES_PATH}/{self.path_cover_s}?ts={self.updated_at}"
if self.path_cover_s
else None
)
@property
def path_cover_large(self) -> str | None:
return (
f"{FRONTEND_RESOURCES_PATH}/{self.path_cover_l}?ts={self.updated_at}"
if self.path_cover_l
else None
)
@property
def path_covers_small(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{r.path_cover_s}?ts={self.updated_at}"
for r in self.roms
if r.path_cover_s
]
@property
def path_covers_large(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{r.path_cover_l}?ts={self.updated_at}"
for r in self.roms
if r.path_cover_l
]
def __repr__(self) -> str:
return self.name
class CollectionRom(BaseModel):
__tablename__ = "collections_roms"
collection_id: Mapped[int] = mapped_column(
ForeignKey("collections.id", ondelete="CASCADE"), primary_key=True
)
rom_id: Mapped[int] = mapped_column(
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
)
__table_args__ = (
UniqueConstraint("collection_id", "rom_id", name="unique_collection_rom"),
)
class VirtualCollectionRom(BaseModel):
"""Membership of a rom in a virtual collection, one row per (rom, tag).
Maintained entirely by database triggers on ``roms``, which unnest the
``generated_*`` metadata columns. Reading it is a plain indexed lookup, so
neither the collection list nor a single collection has to re-derive
anything from raw provider metadata.
"""
__tablename__ = "virtual_collection_roms"
type: Mapped[str] = mapped_column(String(length=50), primary_key=True)
name: Mapped[str] = mapped_column(String(length=400), primary_key=True)
rom_id: Mapped[int] = mapped_column(
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
)
# Denormalized so the collection list never has to touch the roms table.
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
path_cover_l: Mapped[str | None] = mapped_column(Text, default="")
class VirtualCollection(BaseModel):
__tablename__ = "virtual_collections"
# path_covers_* below are plain attributes, not columns of the view.
__allow_unmapped__ = True
name: Mapped[str] = mapped_column(String(length=400), primary_key=True)
type: Mapped[str] = mapped_column(String(length=50), primary_key=True)
description: Mapped[str | None] = mapped_column(Text)
rom_ids: Mapped[set[int]] = mapped_column(
CustomJSON(), default=[], doc="Rom IDs that belong to this collection"
)
# Resolved by the collections handler, capped at MAX_VIRTUAL_COLLECTION_COVERS.
# Aggregating every member's cover in the view costs megabytes per request on
# a large library, and the UI only ever renders a handful.
path_covers_s: list[str] = []
path_covers_l: list[str] = []
@property
def id(self) -> str:
# Create a reversible encoded ID
data = json.dumps({"name": self.name, "type": self.type})
return base64.urlsafe_b64encode(data.encode()).decode()
@classmethod
def from_id(cls, id_: str):
data = json.loads(base64.urlsafe_b64decode(id_).decode())
return data["name"], data["type"]
@property
def rom_count(self) -> int:
return len(self.rom_ids)
@property
def path_cover_small(self) -> str | None:
return None
@property
def path_cover_large(self) -> str | None:
return None
@property
def path_covers_small(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{cover}?ts={self.updated_at}"
for cover in self.path_covers_s
if cover
]
@property
def path_covers_large(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{cover}?ts={self.updated_at}"
for cover in self.path_covers_l
if cover
]
__table_args__ = (
UniqueConstraint(
"name",
"type",
name="unique_virtual_collection_name_type",
),
)
SMART_COLLECTION_MAX_COVERS = 5
class SmartCollection(BaseModel):
__tablename__ = "smart_collections"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(length=400))
description: Mapped[str | None] = mapped_column(Text)
is_public: Mapped[bool] = mapped_column(default=False)
rom_count: Mapped[int] = mapped_column(default=0)
rom_ids: Mapped[list[int]] = mapped_column(
CustomJSON(), default=[], doc="Rom IDs that belong to this smart collection"
)
path_covers_small: Mapped[list[str]] = mapped_column(CustomJSON(), default=[])
path_covers_large: Mapped[list[str]] = mapped_column(CustomJSON(), default=[])
filter_criteria: Mapped[dict[str, Any]] = mapped_column(
CustomJSON(),
default=dict,
doc="JSON object containing all filter criteria for the smart collection",
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
user: Mapped["User"] = relationship(
lazy="joined", back_populates="smart_collections"
)
@property
def owner_username(self) -> str:
return self.user.username
@property
def path_cover_small(self) -> str | None:
return None
@property
def path_cover_large(self) -> str | None:
return None
@property
def filter_summary(self) -> str:
return json.dumps(self.filter_criteria)
def __repr__(self) -> str:
return self.name