fix(roms): keep unplayed games when sorting by a rom_user column

Sorting GET /api/roms by a per-user column (last_played, rating,
status, ...) re-applied the RomUser user filter as a WHERE clause,
collapsing the user-scoped LEFT JOIN into an inner join: every rom the
user had never touched vanished from the results and from the reported
total.

Drop the redundant filter (the join's ON clause already scopes the
rows) and pin NULL sort keys last in both directions with a leading
IS NULL term, which MariaDB, MySQL, and PostgreSQL all support. The
char-index letter walk mirrors the same NULL bucket through a shared
predicate so alpha-strip offsets stay aligned, and enum letter sources
are cast to String so PostgreSQL can take substring() of them.

Fixes #4100

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ND1wfNV3vKwu8Mfinn4WkA
This commit is contained in:
zurdi
2026-09-10 17:12:41 +02:00
parent 2864b44204
commit fb0800a893
3 changed files with 220 additions and 11 deletions

View File

@@ -11,6 +11,7 @@ from typing import Any, NamedTuple
from redis.exceptions import WatchError
from sqlalchemy import (
Enum,
Integer,
String,
Text,
@@ -181,6 +182,13 @@ ROM_METADATA_ORDER_COLUMNS: dict[str, QueryableAttribute] = {
"player_count": Rom.generated_player_count,
}
def _sorts_nulls_last(order_column: Any) -> bool:
"""RomUser sort keys are NULL for roms the user never touched; the query
ordering and the char-index walk must both pin that bucket last."""
return getattr(order_column, "class_", None) is RomUser
# Filter dropdowns read the narrow `roms_facets` mirror instead of `roms`,
# whose rows carry the raw metadata blobs. Column order matches the unpacking
# in `_collect_filter_values`.
@@ -1640,7 +1648,6 @@ class DBRomsHandler(DBBaseHandler):
if user_id and hasattr(RomUser, order_by) and not hasattr(Rom, order_by):
order_attr = getattr(RomUser, order_by)
query = query.filter(RomUser.user_id == user_id)
elif order_by in ROM_METADATA_ORDER_COLUMNS:
order_attr = ROM_METADATA_ORDER_COLUMNS[order_by]
elif hasattr(RomMetadata, order_by) and not hasattr(Rom, order_by):
@@ -1659,6 +1666,14 @@ class DBRomsHandler(DBBaseHandler):
order_attr_column = order_attr
# MariaDB/MySQL have no NULLS LAST, so a leading IS NULL term keeps NULL
# keys (no rom_user row, or an unset field) last in both directions.
nulls_last_clause = (
order_attr_column.is_(None)
if _sorts_nulls_last(order_attr_column)
else None
)
if order_dir.lower() == "desc":
order_attr = order_attr.desc()
else:
@@ -1673,14 +1688,14 @@ class DBRomsHandler(DBBaseHandler):
"AGAINST(:relevance IN BOOLEAN MODE) DESC"
).bindparams(relevance=relevance)
if order_by: # explicit sort wins, relevance breaks ties
order_clauses = [order_attr]
if relevance_clause is not None:
order_clauses.append(relevance_clause)
else: # no sort selected: relevance leads, name is the tiebreaker
order_clauses = [order_attr]
if relevance_clause is not None:
order_clauses.insert(0, relevance_clause)
# An explicit sort wins with relevance breaking ties; with no sort
# selected, relevance leads and name is the tiebreaker.
ordering = (
(nulls_last_clause, order_attr, relevance_clause)
if order_by
else (relevance_clause, order_attr)
)
order_clauses = [clause for clause in ordering if clause is not None]
# The id settles ties, so a page boundary can't repeat or skip a row
# when the sort column holds duplicates.
@@ -1812,13 +1827,23 @@ class DBRomsHandler(DBBaseHandler):
# accumulating those counts avoids row_number() over the whole library,
# which forced a full materialization + filesort on large libraries.
descending = order_dir.lower() == "desc"
letter = func.substring(order_by_attr, 1, 1)
letter_source = order_by_attr
if isinstance(order_by_attr.type, Enum):
# PostgreSQL has no substring() overload for native enums.
letter_source = cast(order_by_attr, String)
letter = func.substring(letter_source, 1, 1)
letter_order: list[ColumnElement[Any]] = []
# A NULLS-pinned sort needs the letter walk to visit that bucket last
# too, or every offset shifts by its size.
if _sorts_nulls_last(order_by_attr):
letter_order.append(letter.is_(None))
letter_order.append(letter.desc() if descending else letter.asc())
counts = (
query.with_only_columns( # type: ignore
letter.label("letter"), func.count().label("count")
)
.group_by(letter)
.order_by(letter.desc() if descending else letter.asc())
.order_by(*letter_order)
)
# Walk the letters in the same direction the client paginates over, so

View File

@@ -1,4 +1,5 @@
import json
from datetime import datetime, timezone
from unittest.mock import AsyncMock, patch
from urllib.parse import unquote
@@ -403,6 +404,47 @@ def test_get_roms_keeps_total_from_the_rom_id_index(
assert body["rom_id_index"] == [rom.id]
def test_get_roms_sorted_by_user_field_keeps_all_roms(
client: TestClient,
access_token: str,
admin_user: User,
rom: Rom,
platform: Platform,
):
rom_user = db_rom_handler.get_rom_user(rom.id, admin_user.id)
assert rom_user is not None
db_rom_handler.update_rom_user(
rom_user.id, {"last_played": datetime(2024, 1, 1, tzinfo=timezone.utc)}
)
never_played = db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name="never_played",
slug="never_played",
fs_name="never_played.zip",
fs_name_no_tags="never_played",
fs_name_no_ext="never_played",
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
response = client.get(
"/api/roms",
headers={"Authorization": f"Bearer {access_token}"},
params={
"platform_ids": [platform.id],
"order_by": "last_played",
"order_dir": "asc",
},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["total"] == 2
assert [item["id"] for item in body["items"]] == [rom.id, never_played.id]
def test_get_roms_filter_by_metadata_providers(
client: TestClient, access_token: str, rom: Rom, platform: Platform
):

View File

@@ -0,0 +1,142 @@
"""Ordering the gallery by a per-user `rom_user` field.
Sorting must keep every rom in the results and the count, with NULL sort
keys (no `rom_user` row, or an unset field) last in both directions.
"""
from datetime import datetime, timezone
import pytest
from handler.database import db_rom_handler
from models.platform import Platform
from models.rom import Rom, RomUser, RomUserStatus
from models.user import User
def _make_rom(platform: Platform, name: str) -> Rom:
return db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
name=name,
slug=name,
fs_name=f"{name}.zip",
fs_name_no_tags=name,
fs_name_no_ext=name,
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
def _set_user_props(rom: Rom, user: User, props: dict[str, object]) -> None:
rom_user = db_rom_handler.add_rom_user(rom_id=rom.id, user_id=user.id)
db_rom_handler.update_rom_user(rom_user.id, props)
def _ordered_names(user: User, order_by: str, order_dir: str) -> list[str]:
return [
rom.name
for rom in db_rom_handler.get_roms_scalar(
order_by=order_by, order_dir=order_dir, user_id=user.id
)
]
class TestRomUserSortQueryShape:
def test_sort_keeps_the_outer_join(self):
query, order_column = db_rom_handler.get_roms_query(
order_by="last_played", user_id=1
)
sql = str(query)
assert "LEFT OUTER JOIN rom_user" in sql
# The user restriction lives only in the join's ON clause; repeating
# it in the WHERE would turn the join into an inner one.
assert sql.count("rom_user.user_id") == 1
assert order_column is RomUser.last_played
@pytest.mark.parametrize("order_dir", ["asc", "desc"])
def test_nulls_lead_the_order_clause(self, order_dir: str):
query, _ = db_rom_handler.get_roms_query(
order_by="last_played", order_dir=order_dir, user_id=1
)
assert (
"ORDER BY rom_user.last_played IS NULL, "
f"rom_user.last_played {order_dir.upper()}"
) in str(query)
class TestRomUserSortResults:
@pytest.fixture
def rated_library(self, admin_user: User, platform: Platform) -> None:
_set_user_props(_make_rom(platform, "low"), admin_user, {"rating": 2})
_set_user_props(_make_rom(platform, "high"), admin_user, {"rating": 9})
_make_rom(platform, "untouched")
@pytest.fixture
def played_library(self, admin_user: User, platform: Platform) -> None:
_set_user_props(
_make_rom(platform, "recent"),
admin_user,
{"last_played": datetime(2024, 6, 1, tzinfo=timezone.utc)},
)
_set_user_props(
_make_rom(platform, "older"),
admin_user,
{"last_played": datetime(2020, 1, 1, tzinfo=timezone.utc)},
)
_make_rom(platform, "never_played")
@pytest.mark.parametrize(
("order_dir", "expected"),
[
("asc", ["older", "recent", "never_played"]),
("desc", ["recent", "older", "never_played"]),
],
)
def test_last_played_keeps_unplayed_roms_last(
self,
admin_user: User,
played_library: None,
order_dir: str,
expected: list[str],
):
assert _ordered_names(admin_user, "last_played", order_dir) == expected
def test_rating_ascending_keeps_unrated_roms_last(
self, admin_user: User, rated_library: None
):
assert _ordered_names(admin_user, "rating", "asc") == [
"low",
"high",
"untouched",
]
def test_count_includes_roms_without_a_rom_user_row(
self, admin_user: User, rated_library: None
):
query, _ = db_rom_handler.get_roms_query(
order_by="rating", user_id=admin_user.id
)
assert db_rom_handler.get_rom_count(query=query) == 3
def test_char_index_visits_the_null_bucket_last(
self, admin_user: User, platform: Platform
):
for name in ("first_done", "second_done"):
_set_user_props(
_make_rom(platform, name),
admin_user,
{"status": RomUserStatus.FINISHED},
)
_make_rom(platform, "untouched")
query, order_column = db_rom_handler.get_roms_query(
order_by="status", user_id=admin_user.id
)
# The status-less rom sorts last, so it must not shift the offsets.
assert db_rom_handler.with_char_index(query, order_column) == [("F", 0)]