some clenaup

This commit is contained in:
Georges-Antoine Assi
2026-08-01 14:49:58 -04:00
parent 7399c19479
commit c951b6eb46
5 changed files with 56 additions and 70 deletions

View File

@@ -629,8 +629,8 @@ def get_roms(
query = db_rom_handler.filter_roms(
query=unfiltered_query,
user_id=request.user.id,
hidden_platform_ids=perms.hidden_platform_ids,
hidden_rom_ids=perms.hidden_rom_ids,
hidden_platform_ids=perms.hidden_platform_ids, # type: ignore
hidden_rom_ids=perms.hidden_rom_ids, # type: ignore
platform_ids=platform_ids,
collection_id=collection_id,
virtual_collection_id=virtual_collection_id,

View File

@@ -423,6 +423,6 @@ async def delete_states(
error = f"Screenshot file {hl(state.screenshot.file_name)} not found for state {hl(state.file_name)}[{hl(state.rom.platform_slug)}]"
log.error(error)
refresh_affected_smart_collections(sorted(affected_rom_ids), membership_only=True)
refresh_affected_smart_collections(list(affected_rom_ids), membership_only=True)
return states

View File

@@ -45,10 +45,6 @@ MAX_VIRTUAL_COLLECTION_COVERS = 5
COVERS_BATCH_SIZE = 100
def _strip_cache_buster(urls: Sequence[str]) -> list[str]:
return [url.split("?", 1)[0] for url in urls]
def with_roms(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
@@ -534,6 +530,34 @@ class DBCollectionsHandler(DBBaseHandler):
"tags_logic": criteria.get("tags_logic", "any"),
}
def build_smart_collection_query(
self,
*,
query: Query,
smart_collection: SmartCollection,
user_id: int | None,
session: Session,
) -> Query:
"""Apply a smart collection's stored criteria to a ROM query.
The criteria are `filter_roms`'s own vocabulary, so membership composes
into SQL and the database can return just the page being viewed, rather
than the whole matching library being assembled in Python first (#4029).
Relationships are not eager-loaded, so the result is for filtering, not
for serializing ROMs. The caller owns the query's joins, including
`RomUser` for the per-user criteria (favorite, statuses, saves, states).
"""
from handler.database import db_rom_handler
return db_rom_handler.filter_roms(
query=query,
user_id=user_id,
include_related=False,
session=session,
**self.get_smart_collection_criteria(smart_collection),
)
@begin_session
def get_smart_collection_members(
self,
@@ -556,12 +580,14 @@ class DBCollectionsHandler(DBBaseHandler):
user_id=user_id,
session=session,
)
query = db_rom_handler.build_smart_collection_query(
query = self.build_smart_collection_query(
query=query,
smart_collection=smart_collection,
user_id=user_id,
session=session,
).with_only_columns(Rom.id, Rom.path_cover_s, Rom.path_cover_l)
).with_only_columns( # type: ignore
Rom.id, Rom.path_cover_s, Rom.path_cover_l
)
return session.execute(query).all()
@@ -604,8 +630,10 @@ class DBCollectionsHandler(DBBaseHandler):
# timestamp and comparing whole URLs would rewrite on every refresh.
if (
smart_collection.rom_ids == rom_ids
and _strip_cache_buster(smart_collection.path_covers_small) == covers_small
and _strip_cache_buster(smart_collection.path_covers_large) == covers_large
and [u.split("?", 1)[0] for u in smart_collection.path_covers_small]
== covers_small
and [u.split("?", 1)[0] for u in smart_collection.path_covers_large]
== covers_large
):
return smart_collection
@@ -639,7 +667,7 @@ class DBCollectionsHandler(DBBaseHandler):
rom_ids: Sequence[int],
membership_only: bool = False,
session: Session = None, # type: ignore
) -> int:
):
"""Refresh the collections a handful of changed ROMs touch.
Editing one ROM rarely moves any collection, and asking whether given
@@ -656,10 +684,9 @@ class DBCollectionsHandler(DBBaseHandler):
from handler.database import db_rom_handler
if not rom_ids:
return 0
return
candidates = set(rom_ids)
refreshed = 0
for smart_collection in session.scalars(select(SmartCollection)).all():
matching = db_rom_handler.get_smart_collection_matches(
smart_collection=smart_collection,
@@ -671,6 +698,3 @@ class DBCollectionsHandler(DBBaseHandler):
moved = matching != cached if membership_only else bool(matching or cached)
if moved:
self.refresh_smart_collection(smart_collection.id, session=session)
refreshed += 1
return refreshed

View File

@@ -574,8 +574,8 @@ class DBRomsHandler(DBBaseHandler):
member_ids = self._join_rom_user(select(Rom.id), user_id)
return query.filter(
Rom.id.in_(
self.build_smart_collection_query(
query=member_ids,
db_collection_handler.build_smart_collection_query(
query=member_ids, # type: ignore
smart_collection=smart_collection,
user_id=user_id,
session=session,
@@ -583,41 +583,14 @@ class DBRomsHandler(DBBaseHandler):
)
)
def _join_rom_user(self, query: Query, user_id: int | None) -> Query:
def _join_rom_user(self, query: Select, user_id: int | None) -> Select:
if not user_id:
return query
return query.outerjoin(
RomUser, and_(RomUser.rom_id == Rom.id, RomUser.user_id == user_id)
)
def build_smart_collection_query(
self,
*,
query: Query,
smart_collection: SmartCollection,
user_id: int | None,
session: Session,
) -> Query:
"""Apply a smart collection's stored criteria to a ROM query.
The criteria are `filter_roms`'s own vocabulary, so membership composes
into SQL and the database can return just the page being viewed, rather
than the whole matching library being assembled in Python first (#4029).
Relationships are not eager-loaded, so the result is for filtering, not
for serializing ROMs. The caller owns the query's joins, including
`RomUser` for the per-user criteria (favorite, statuses, saves, states).
"""
from . import db_collection_handler
return self.filter_roms(
query=query,
user_id=user_id,
include_related=False,
session=session,
**db_collection_handler.get_smart_collection_criteria(smart_collection),
)
@begin_session
def get_smart_collection_matches(
self,
@@ -632,11 +605,13 @@ class DBRomsHandler(DBBaseHandler):
Restricting the criteria to a few ids keeps this an indexed lookup, so a
caller can ask whether one ROM moved without scanning the library.
"""
from . import db_collection_handler
query = self._join_rom_user(select(Rom.id), user_id).filter(Rom.id.in_(rom_ids))
return set(
session.scalars(
self.build_smart_collection_query(
query=query,
db_collection_handler.build_smart_collection_query(
query=query, # type: ignore
smart_collection=smart_collection,
user_id=user_id,
session=session,
@@ -650,18 +625,6 @@ class DBRomsHandler(DBBaseHandler):
return None
return " ".join(f"+{word}*" for word in words)
def _fulltext_param_name(self, term: str, idx: int) -> str:
"""Name the bind parameter after the term it carries.
A statement can hold more than one MATCH clause (a smart collection's
own search term composes with the gallery's), and `text()` parameters
aren't uniquified by SQLAlchemy, so a fixed name would let one term
overwrite the other. Deriving the name from the term keeps it stable
per term, so compiled statements still cache.
"""
digest = hashlib.blake2s(term.encode(), digest_size=4).hexdigest()
return f"fulltext_search_{digest}_{idx}"
def _build_fulltext_relevance(self, search_term: str) -> str | None:
parts: list[str] = []
for term in search_term.split("|"):
@@ -683,7 +646,9 @@ class DBRomsHandler(DBBaseHandler):
if boolean_query is None:
match_clauses = []
break
param = self._fulltext_param_name(term, idx)
digest = hashlib.blake2s(term.encode(), digest_size=4).hexdigest()
param = f"fulltext_search_{digest}_{idx}"
match_clauses.append(
text(
f"MATCH(roms.name, roms.fs_name) "
@@ -1198,7 +1163,7 @@ class DBRomsHandler(DBBaseHandler):
# drop the carried-over ORDER BY the window doesn't use.
base_subquery = (
query.order_by(None)
.with_only_columns(
.with_only_columns( # type: ignore
Rom.id,
Rom.fs_name_no_ext,
Rom.platform_id,

View File

@@ -285,9 +285,8 @@ def test_refresh_for_roms_updates_the_collections_the_rom_moved_between(
db_collection_handler.refresh_smart_collections()
db_rom_handler.update_rom(mover.id, {"manual_metadata": {"genres": ["Racing"]}})
refreshed = db_collection_handler.refresh_smart_collections_for_roms([mover.id])
db_collection_handler.refresh_smart_collections_for_roms([mover.id])
assert refreshed == 2
racing_after = db_collection_handler.get_smart_collection(racing.id)
puzzle_after = db_collection_handler.get_smart_collection(puzzle.id)
assert racing_after is not None and racing_after.rom_count == 2
@@ -305,9 +304,8 @@ def test_refresh_for_roms_leaves_untouched_collections_alone(
bystander = _add_rom(platform, "Puzzler", manual_metadata={"genres": ["Puzzle"]})
refresh = mocker.spy(db_collection_handler, "refresh_smart_collection")
moved = db_collection_handler.refresh_smart_collections_for_roms([bystander.id])
db_collection_handler.refresh_smart_collections_for_roms([bystander.id])
assert moved == 0
assert refresh.call_count == 0
@@ -357,11 +355,10 @@ def test_refresh_for_roms_membership_only_skips_a_member_that_stayed(
_add_save(rom, admin_user, "second.sav")
refresh = mocker.spy(db_collection_handler, "refresh_smart_collection")
moved = db_collection_handler.refresh_smart_collections_for_roms(
db_collection_handler.refresh_smart_collections_for_roms(
[rom.id], membership_only=True
)
assert moved == 0
assert refresh.call_count == 0