From 2d58122d29b8de740cf8ffcfc76e42aa5dcf4ea0 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Thu, 1 Oct 2026 17:00:11 -0400 Subject: [PATCH] feat(search): Rank exact title matches first in relevance-ordered searches (#4996) * Rank exact title matches first in relevance-ordered searches Relevance only scored whether a ROM's name, filename or aliases held the search as a phrase, so a spin-off whose alias contains "Final Fantasy 7" tied with the game whose alias is exactly that, and the tie fell to title order. Searches ordered by relevance now rank an exact name or alias match first, then names starting with the search, then the phrase score. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * pr-ready step 2 (code-review): match escaped aliases and tidy search parsing The alias pre-check now looks for the term as the joined aliases store it, with JSON escapes, so a quoted alias (and, on MariaDB, a non-ASCII one) can rank as exact. Search phrases reuse the shared term split, the order_by API description matches the current ranking, and the dialect test's NULL row is a real SQL NULL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * pr-ready step 3 (simplify): flatten the search rank and share helpers The exact-name check is one IN over the folded terms, the provider alias check has its own helper, json_titles_contain_folded folds the title itself and builds on json_array_contains_value, PostgreSQL only scans the aliases for the raw form of a term, and the running-engine dialect tests share one scratch-table helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * Rank one-word searches of three or more characters A search for an alias like "ff7" now puts the exact match first. The rule for when relevance leads (and the letter index is dropped) moves to search_relevance_leads, which the order clauses and the endpoint share: no explicit sort, and either a multi-word phrase or a term of at least three characters. Shorter terms keep the name order, since they match most of a library and ranking would sort every match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * Rank exact titles stored with extra spaces or accented capitals The exact and prefix tiers now collapse runs of whitespace on the stored name and alias side too, so "Final Fantasy VII" ranks as exact for "final fantasy vii". On MariaDB, which stores non-ASCII characters as \uXXXX escapes that LOWER can't fold, a non-ASCII term is checked against the aliases decoded through JSON_TABLE, and the alias pre-check goes word by word, skipping words it can't match in escaped text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * Rank search results against a stored, folded title column Search ranking compared the term against the name and each provider's alternative titles, which meant decoding JSON blobs per row and working around MariaDB's escaped Unicode, tabs and newlines. Store the folded name and aliases in a new `roms.search_titles` column instead, kept in sync by mapper events and `update_rom`, and backfilled by migration 0147 in batches. Ranking becomes two LIKE checks against that column. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * Keep fitting aliases after one that overflows the search titles cap Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * Rank a name prefix only where the search ends a word "final fantasy viii" starts with "final fantasy vii", so Final Fantasy VIII took the prefix rank for that search. The name now has to continue with a non-alphanumeric character after the search, which a regex checks on the rows the LIKE prefix already narrowed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * pr-ready code review: fix punctuation prefixes and hidden sort direction - A search ending in punctuation has already ended its word, so the name prefix rank no longer needs a further non-alphanumeric character. - Relevance has no direction: a hidden descending order no longer reverses its ties, in the order clauses or the grouped aggregate. - An alias equal to the name isn't stored twice in `search_titles`. - `update_rom` reads the stored row once instead of up to three times. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 * pr-ready simplify: keep relevance's direction rule with its order clauses - `_gallery_order_clauses` decides once whether relevance leads and drops the direction there, rather than each caller overriding it. - The search terms are built only where the rank needs them. - The page hydration query drops a sort its rows are reordered out of. - The ranking tests share one helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6 --------- Co-authored-by: Claude Opus 5.5 --- .../versions/0147_roms_search_titles.py | 72 ++++++++++ backend/endpoints/roms/__init__.py | 12 +- backend/handler/database/roms_handler.py | 94 ++++++++++--- backend/models/rom.py | 70 +++++++++- .../endpoints/roms/test_rom_sidecar_cache.py | 6 +- backend/tests/handler/test_db_handler.py | 130 ++++++++++++++++++ backend/tests/models/test_rom.py | 79 ++++++++++- backend/tests/test_migrations.py | 38 +++++ backend/utils/roms_columns.py | 8 +- 9 files changed, 481 insertions(+), 28 deletions(-) create mode 100644 backend/alembic/versions/0147_roms_search_titles.py diff --git a/backend/alembic/versions/0147_roms_search_titles.py b/backend/alembic/versions/0147_roms_search_titles.py new file mode 100644 index 000000000..9980492bd --- /dev/null +++ b/backend/alembic/versions/0147_roms_search_titles.py @@ -0,0 +1,72 @@ +"""Store each ROM's folded name and aliases for search ranking + +Revision ID: 0147_roms_search_titles +Revises: 0146_roms_search_aliases +Create Date: 2026-10-01 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +from models.rom import ALTERNATIVE_NAME_SOURCES, compute_search_titles +from utils.database import CustomJSON +from utils.roms_columns import SEARCH_TITLES_COLUMN, ensure_roms_columns + +# revision identifiers, used by Alembic. +revision = "0147_roms_search_titles" +down_revision = "0146_roms_search_aliases" +branch_labels = None +depends_on = None + +BATCH_SIZE = 1000 + +ROMS = sa.table( + "roms", + sa.column("id", sa.Integer()), + sa.column("name", sa.String()), + sa.column(SEARCH_TITLES_COLUMN, sa.Text()), + *(sa.column(column, CustomJSON()) for column, _ in ALTERNATIVE_NAME_SOURCES), +) + + +def _fill_search_titles(conn: sa.Connection) -> None: + """Fill the rows still without titles, so an interrupted run resumes.""" + # Only each provider's titles are read, not the whole metadata blob. + titles = [ROMS.c[column][key] for column, key in ALTERNATIVE_NAME_SOURCES] + last_id = 0 + while rows := conn.execute( + sa.select(ROMS.c.id, ROMS.c.name, *titles) + .where(ROMS.c[SEARCH_TITLES_COLUMN].is_(None), ROMS.c.id > last_id) + .order_by(ROMS.c.id) + .limit(BATCH_SIZE) + ).all(): + filled = { + rom_id: compute_search_titles( + name, + { + column: {key: names} + for (column, key), names in zip( + ALTERNATIVE_NAME_SOURCES, provider_titles, strict=True + ) + }, + ) + for rom_id, name, *provider_titles in rows + } + # One statement per batch, since a round trip per row dominates. + conn.execute( + sa.update(ROMS) + .where(ROMS.c.id.in_(filled)) + .values({SEARCH_TITLES_COLUMN: sa.case(filled, value=ROMS.c.id)}) + ) + last_id = rows[-1][0] + + +def upgrade() -> None: + conn = op.get_bind() + ensure_roms_columns(conn) + _fill_search_titles(conn) + + +def downgrade() -> None: + op.drop_column("roms", SEARCH_TITLES_COLUMN, if_exists=True) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 32e844f02..92f58b3fb 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -570,9 +570,10 @@ def get_roms( str, Query( description=( - "Field to order results by. Leave empty to order by search " - "relevance when a search term is given on MySQL/MariaDB; other " - "databases fall back to name." + "Field to order results by. Leave empty to order a search of " + "two or more words, or of at least three characters, by " + "relevance: exact name or alias matches first, then names " + "starting with the term, then phrase matches." ), ), ] = "", @@ -796,7 +797,10 @@ def get_roms( ) if page_ids: - page_rows = session.scalars(query.where(Rom.id.in_(page_ids))).all() + # The rows are reordered by `page_ids` below, so the sort is dropped. + page_rows = session.scalars( + query.where(Rom.id.in_(page_ids)).order_by(None) + ).all() rows_by_id = {rom.id: rom for rom in page_rows} page_items = [rows_by_id[i] for i in page_ids if i in rows_by_id] else: diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index d1a478669..817fbc9cf 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -61,8 +61,11 @@ from models.collection import Collection, CollectionRom, SmartCollection from models.music import MusicFavoriteTrack, MusicPlaylistTrack from models.platform import Platform from models.rom import ( + ALTERNATIVE_NAME_SOURCES, METADATA_SOURCE_FACET_COLUMNS, ROM_IS_IDENTIFIED, + SEARCH_TITLE_COLUMNS, + SEARCH_TITLE_SEPARATOR, Rom, RomDeletionTarget, RomFacets, @@ -81,6 +84,8 @@ from models.rom import ( TrackMeta, compute_full_path_hash, compute_name_sort_key, + compute_search_titles, + fold_search_title, ) from utils import get_version from utils.database import ( @@ -249,6 +254,44 @@ def _fulltext_match(boolean_query: str) -> ColumnElement[Any]: ) +# A shorter one-word search matches most of a library, and ranking it would +# sort every match instead of walking the name index. +SEARCH_RANK_MIN_LENGTH = 3 + + +def _search_terms(search_term: str) -> list[str]: + """The `|`-separated alternatives of a search, blanks dropped.""" + return [term for term in (part.strip() for part in search_term.split("|")) if term] + + +def _name_starts_with(title: str) -> ColumnElement[bool]: + """Whether the ROM's folded name starts with `title`, ending a word there.""" + sep = SEARCH_TITLE_SEPARATOR + # The name comes first, so it is the title the column starts with. + starts = Rom.search_titles.startswith(f"{sep}{title}", autoescape=True) + # A title ending in punctuation has already ended its word. + if not title[-1].isalnum(): + return starts + # Both engines' regex dialects read a backslash before a non-alphanumeric + # character as that character. The LIKE narrows the rows the regex reads. + escaped = "".join(char if char.isalnum() else f"\\{char}" for char in title) + return and_(starts, Rom.search_titles.regexp_match(f"^{sep}{escaped}[^[:alnum:]]")) + + +def _search_rank(terms: Sequence[str]) -> ColumnElement[int]: + """2 when the name or an alias equals a term, 1 when the name starts with one, else 0.""" + sep = SEARCH_TITLE_SEPARATOR + folded = [title for term in terms if (title := fold_search_title(term))] + exact = or_( + *( + Rom.search_titles.contains(f"{sep}{title}{sep}", autoescape=True) + for title in folded + ) + ) + prefix = or_(*(_name_starts_with(title) for title in folded)) + return case((exact, 2), (prefix, 1), else_=0) + + def _search_relevance(phrases: Sequence[str]) -> ColumnElement[Any]: """How well the ROM's name, filename or aliases hold the phrases, words in order.""" holds_a_phrase = or_(*(_name_like(phrase) for phrase in phrases)) @@ -1133,7 +1176,7 @@ class DBRomsHandler(DBBaseHandler): def _build_search_phrases(self, search_term: str) -> list[str]: """The multi-word terms of a search, which relevance ranks by.""" phrases: list[str] = [] - for term in search_term.split("|"): + for term in _search_terms(search_term): words = FULLTEXT_TOKEN_REGEX.findall(term) if len(words) > 1: phrases.append(" ".join(words)) @@ -1195,8 +1238,7 @@ class DBRomsHandler(DBBaseHandler): ] def _filter_by_search_term[S: Select[Any]](self, query: S, search_term: str) -> S: - terms = [term.strip() for term in search_term.split("|")] - terms = [term for term in terms if term] + terms = _search_terms(search_term) if not terms: return query @@ -1817,8 +1859,10 @@ class DBRomsHandler(DBBaseHandler): def search_relevance_leads(self, order_by: str, search_term: str | None) -> bool: """Whether a gallery query orders by search relevance ahead of its sort key.""" - return not order_by and bool( - search_term and self._build_search_phrases(search_term) + if order_by or not search_term: + return False + return bool(self._build_search_phrases(search_term)) or any( + len(term) >= SEARCH_RANK_MIN_LENGTH for term in _search_terms(search_term) ) def _gallery_order_clauses( @@ -1830,7 +1874,9 @@ class DBRomsHandler(DBBaseHandler): nulls_last: bool, search_term: str | None, ) -> list[Any]: - descending = order_dir == "desc" + relevance_leads = self.search_relevance_leads(order_by, search_term) + # Relevance has no direction, so its ties always run A to Z. + descending = order_dir == "desc" and not relevance_leads if nulls_last: nulls_last_clause, order_clause = _nulls_last_ordering( sort_column, descending @@ -1847,14 +1893,16 @@ class DBRomsHandler(DBBaseHandler): sort_clauses: list[Any] = [order_clause] phrases = self._build_search_phrases(search_term) if search_term else [] - if phrases: - # Relevance breaks an explicit sort's ties, or leads (with name - # breaking its ties) when no sort is picked. - relevance_clause = _search_relevance(phrases).desc() - if order_by: - sort_clauses.append(relevance_clause) - else: - sort_clauses.insert(0, relevance_clause) + relevance = [_search_relevance(phrases).desc()] if phrases else [] + # Phrase relevance breaks an explicit sort's ties. With no sort, the rank + # (which reads provider metadata) and relevance lead, and name breaks ties. + if order_by: + sort_clauses.extend(relevance) + elif relevance_leads and search_term: + sort_clauses[:0] = [ + _search_rank(_search_terms(search_term)).desc(), + *relevance, + ] return [ clause @@ -2197,13 +2245,27 @@ class DBRomsHandler(DBBaseHandler): # Re-derive the key from the new name, but only when the stored key # is still the derived value (i.e. not a manual override). Mirrors # the `@validates` logic, which the bulk update() bypasses. - existing = session.scalars(select(Rom).filter_by(id=id)).one() + existing = session.get_one(Rom, id) if ( existing.name_sort_key is None or existing.name_sort_key == compute_name_sort_key(existing.name) ): data = {**data, "name_sort_key": compute_name_sort_key(data["name"])} + if data.keys() & SEARCH_TITLE_COLUMNS: + # The bulk update() skips the mapper event that keeps this in sync. + stored = session.get_one(Rom, id) + data = { + **data, + "search_titles": compute_search_titles( + data.get("name", stored.name), + { + column: data.get(column, getattr(stored, column)) + for column, _ in ALTERNATIVE_NAME_SOURCES + }, + ), + } + if "fs_name" in data: parts = compute_file_name_parts(data["fs_name"]) data = { @@ -2216,7 +2278,7 @@ class DBRomsHandler(DBBaseHandler): if "fs_name" in data or "fs_path" in data: # The unique index reads the digest, so whichever half the caller # left out has to come from the stored row. - stored = session.scalars(select(Rom).filter_by(id=id)).one() + stored = session.get_one(Rom, id) data = { **data, "full_path_hash": compute_full_path_hash( diff --git a/backend/models/rom.py b/backend/models/rom.py index 75703635e..e4b1642f3 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -5,7 +5,7 @@ import enum import hashlib import re import sys -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import datetime from functools import cached_property @@ -26,7 +26,9 @@ from sqlalchemy import ( Text, UniqueConstraint, and_, + event, func, + inspect, or_, select, ) @@ -113,6 +115,44 @@ def compute_full_path_hash(fs_path: str | None, fs_name: str | None) -> str: ).hexdigest() +# Closes every title in `Rom.search_titles`; a control character no title holds. +SEARCH_TITLE_SEPARATOR = "\x1f" +# In characters: a utf8mb4 TEXT holds 65535 bytes, and a longer value would +# fail the INSERT under strict mode. +SEARCH_TEXT_MAX_LENGTH = 16000 + + +def fold_search_title(title: str) -> str: + """`title` as search ranking compares it: lowercased, whitespace collapsed.""" + return " ".join(title.replace(SEARCH_TITLE_SEPARATOR, " ").split()).lower() + + +def compute_search_titles(name: str | None, metadata: Mapping[str, Any]) -> str: + """Precompute `Rom.search_titles`: the folded name, then each folded alias. + + Args: + metadata: Each `ALTERNATIVE_NAME_SOURCES` column's value, by column name. + """ + sep = SEARCH_TITLE_SEPARATOR + aliases = ( + title + for column, key in ALTERNATIVE_NAME_SOURCES + if isinstance(blob := metadata.get(column), dict) + and isinstance(names := blob.get(key), list) + for title in names + if isinstance(title, str) + ) + folded_name = fold_search_title(name or "") + value = sep + folded_name + sep + for alias in dict.fromkeys(fold_search_title(title) for title in aliases): + if not alias or alias == folded_name: + continue + if len(value) + len(alias) + len(sep) > SEARCH_TEXT_MAX_LENGTH: + continue + value += alias + sep + return value + + def _ra_achievement_sort_key(achievement: dict[str, Any]) -> tuple[int, int]: """Orders achievements by RetroAchievements' "Display Order", ties by id.""" order = achievement.get("display_order") @@ -922,6 +962,9 @@ class Rom(BaseModel): server_onupdate=FetchedValue(), deferred=True, ) + # The folded name and aliases, kept by `compute_search_titles` on every + # write; search ranking matches whole titles against it. + search_titles: Mapped[str | None] = mapped_column(Text(), deferred=True) crc_hash: Mapped[str | None] = mapped_column(String(length=100)) md5_hash: Mapped[str | None] = mapped_column(String(length=100)) @@ -1278,6 +1321,31 @@ def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: ) +SEARCH_TITLE_COLUMNS = ("name", *(column for column, _ in ALTERNATIVE_NAME_SOURCES)) + + +def rom_search_titles(rom: Rom) -> str: + """`compute_search_titles` over the ROM's current name and metadata.""" + return compute_search_titles( + rom.name, + {column: getattr(rom, column) for column, _ in ALTERNATIVE_NAME_SOURCES}, + ) + + +@event.listens_for(Rom, "before_insert") +def _set_search_titles(_mapper: Any, _connection: Any, rom: Rom) -> None: + rom.search_titles = rom_search_titles(rom) + + +@event.listens_for(Rom, "before_update") +def _refresh_search_titles(_mapper: Any, _connection: Any, rom: Rom) -> None: + state = inspect(rom) + if any( + state.attrs[column].history.has_changes() for column in SEARCH_TITLE_COLUMNS + ): + rom.search_titles = rom_search_titles(rom) + + class HasFileOnDiskFilters(TypedDict): physical: bool missing: bool diff --git a/backend/tests/endpoints/roms/test_rom_sidecar_cache.py b/backend/tests/endpoints/roms/test_rom_sidecar_cache.py index d12cd8841..2b30d36b0 100644 --- a/backend/tests/endpoints/roms/test_rom_sidecar_cache.py +++ b/backend/tests/endpoints/roms/test_rom_sidecar_cache.py @@ -245,8 +245,10 @@ def test_unfiltered_request_still_reads_unscoped_char_index_cache( # Relevance leads, so the rows run in no letter order. ({"search_term": "final fantasy"}, {}), ({"search_term": "final fantasy", "order_by": "name"}, {"f": 0}), - # One word has no phrase to rank by, so the name order stands. - ({"search_term": "fantasy"}, {"f": 0}), + ({"search_term": "fantasy"}, {}), + # Too short to rank, so the name order stands. + ({"search_term": "fa"}, {"f": 0}), + ({}, {"f": 0}), ], ) def test_char_index_follows_whether_relevance_leads( diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index 51f53736c..00ea74bed 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -254,6 +254,136 @@ def test_filter_by_search_term_multi_word_and_ranking(platform: Platform): assert explicit_ids.index(fantasy_final.id) < explicit_ids.index(ff.id) +def _ranked(search_term: str, order_by: str = "", order_dir: str = "asc") -> list[int]: + roms = db_rom_handler.get_roms_scalar( + search_term=search_term, order_by=order_by, order_dir=order_dir + ) + return [rom.id for rom in roms] + + +def test_search_ranks_exact_titles_then_name_prefixes(platform: Platform): + def _add(name: str, aliases: list[str]) -> Rom: + return make_rom(platform, name, igdb_metadata={"alternative_names": aliases}) + + crisis_core = _add( + "Crisis Core: Final Fantasy VII", ["Crisis Core: Final Fantasy 7"] + ) + dirge = _add("Dirge of Cerberus: Final Fantasy VII", []) + ff7 = _add("Final Fantasy VII", ["FF7", "Final Fantasy 7"]) + remake = _add("Final Fantasy VII Remake", ["Final Fantasy 7 Remake"]) + moby_titled = make_rom( + platform, + "Seventh Fantasy", + moby_metadata={"alternate_titles": ["FINAL FANTASY VII"]}, + ) + + # An alias equal to the search beats one that only holds it. + assert _ranked("final fantasy 7") == [ff7.id, crisis_core.id, remake.id] + + # Exact name or alias first, then names the search starts, then the rest. + assert _ranked("Final Fantasy VII") == [ + ff7.id, + moby_titled.id, + remake.id, + crisis_core.id, + dirge.id, + ] + + # The rank only leads; an explicit sort keeps its order. + assert _ranked("final fantasy vii", order_by="name") == [ + crisis_core.id, + dirge.id, + ff7.id, + remake.id, + moby_titled.id, + ] + + # A one-word search ranks too, though it has no phrase to score. + fan_mod = _add("A FF7 Fan Mod", []) + assert _ranked("ff7") == [ff7.id, fan_mod.id] + + +def test_search_ranks_a_name_prefix_only_where_a_word_ends(platform: Platform): + ff7 = make_rom(platform, "Final Fantasy VII") + ff8 = make_rom(platform, "Final Fantasy VIII") + advent_children = make_rom(platform, "Final Fantasy VII: Advent Children") + crisis_core = make_rom(platform, "Crisis Core: Final Fantasy VII") + + assert _ranked("final fantasy vii") == [ + ff7.id, + advent_children.id, + crisis_core.id, + ff8.id, + ] + + +@pytest.mark.parametrize( + ("name", "search_term"), + [ + ("Dr. Mario 64", "dr. mario"), + ("Mario + Rabbids Kingdom Battle", "mario + rabbids"), + ], +) +def test_search_ranks_a_name_prefix_holding_regex_characters( + platform: Platform, name: str, search_term: str +): + prefixed = make_rom(platform, name) + # Ahead by name, so only the prefix rank puts the other first. + holder = make_rom(platform, f"A {name} Fan Game") + + assert _ranked(search_term) == [prefixed.id, holder.id] + + +def test_search_relevance_ignores_the_sort_direction(platform: Platform): + make_rom(platform, "Final Fantasy VII") + make_rom(platform, "Crisis Core: Final Fantasy VII") + make_rom(platform, "Dirge of Cerberus: Final Fantasy VII") + + assert _ranked("final fantasy vii", order_dir="desc") == _ranked( + "final fantasy vii", order_dir="asc" + ) + + +def test_search_ranks_a_name_prefix_ending_in_punctuation(platform: Platform): + prefixed = make_rom(platform, "Mr.Driller") + holder = make_rom(platform, "Adventures of Mr. Driller") + + assert _ranked("mr.") == [prefixed.id, holder.id] + + +@pytest.mark.parametrize( + "alias", ['Say "Cheese"', "Pokémon Rouge", "ŌKAMI Den", "Chrono\tTrigger"] +) +def test_search_ranks_exact_aliases_with_escaped_characters( + platform: Platform, alias: str +): + titled = make_rom( + platform, f"{alias} Edition", igdb_metadata={"alternative_names": [alias]} + ) + untitled = make_rom( + platform, + f"{alias} Advent", + igdb_metadata={"alternative_names": [f"{alias} Advent"]}, + ) + + roms = db_rom_handler.get_roms_scalar(search_term=" ".join(alias.lower().split())) + + assert [rom.id for rom in roms] == [titled.id, untitled.id] + + +@pytest.mark.parametrize("stored", ["Final Fantasy VII", "Final\tFantasy\nVII"]) +def test_search_ranks_exact_titles_stored_with_uneven_spacing( + platform: Platform, stored: str +): + spaced = make_rom(platform, stored) + longer = make_rom(platform, "Final Fantasy VII Remake") + contains = make_rom(platform, "Crisis Core: Final Fantasy VII") + + roms = db_rom_handler.get_roms_scalar(search_term="final fantasy vii") + + assert [rom.id for rom in roms] == [spaced.id, longer.id, contains.id] + + @pytest.mark.parametrize( ("search_term", "expected"), [ diff --git a/backend/tests/models/test_rom.py b/backend/tests/models/test_rom.py index 79506d8c1..847f1b1e8 100644 --- a/backend/tests/models/test_rom.py +++ b/backend/tests/models/test_rom.py @@ -4,8 +4,16 @@ import pytest from tests.factories import make_rom from handler.database import db_rom_handler +from handler.database.base_handler import sync_session from models.platform import Platform -from models.rom import LookupHashes, Rom, RomFile, compute_full_path_hash +from models.rom import ( + SEARCH_TEXT_MAX_LENGTH, + LookupHashes, + Rom, + RomFile, + compute_full_path_hash, + compute_search_titles, +) def test_rom(rom: Rom): @@ -338,3 +346,72 @@ class TestMergedRAMetadata: assert merged is not None assert [a["ra_id"] for a in stored["achievements"]] == [2, 1] assert stored["achievements"][0]["badge_path"] == "2.png" + + +def test_search_titles_fold_the_name_then_each_alias(): + titles = compute_search_titles( + "Final Fantasy\tVII", + { + "igdb_metadata": {"alternative_names": ["FF7", "ŌKAMI Den", "ff7", ""]}, + "moby_metadata": {"alternate_titles": ["Final Fantasy 7"]}, + "ss_metadata": {"alternative_names": ["FINAL FANTASY VII"]}, + }, + ) + + assert titles == "\x1ffinal fantasy vii\x1fff7\x1fōkami den\x1ffinal fantasy 7\x1f" + + +def test_search_titles_skip_a_hand_edited_blob_that_is_not_an_object(): + titles = compute_search_titles( + "Name", {"igdb_metadata": ["FF7"], "moby_metadata": "FF7"} + ) + + assert titles == "\x1fname\x1f" + + +def test_search_titles_keep_the_name_slot_without_a_name_or_metadata(): + assert compute_search_titles(None, {"igdb_metadata": None}) == "\x1f\x1f" + + +def test_search_titles_drop_aliases_past_the_length_cap(): + aliases = [f"alias {i:05d} " + "x" * 100 for i in range(500)] + + titles = compute_search_titles( + "Name", {"igdb_metadata": {"alternative_names": aliases}} + ) + + assert len(titles) <= SEARCH_TEXT_MAX_LENGTH + assert titles.endswith("\x1f") + + +def test_search_titles_keep_a_short_alias_after_one_past_the_cap(): + titles = compute_search_titles( + "Name", + {"igdb_metadata": {"alternative_names": ["x" * SEARCH_TEXT_MAX_LENGTH, "FF7"]}}, + ) + + assert titles == "\x1fname\x1fff7\x1f" + + +def test_search_titles_follow_orm_and_bulk_writes(platform: Platform): + rom = make_rom( + platform, "Final Fantasy VII", igdb_metadata={"alternative_names": ["FF7"]} + ) + + def stored() -> str | None: + with sync_session.begin() as session: + return session.get_one(Rom, rom.id).search_titles + + assert stored() == "\x1ffinal fantasy vii\x1fff7\x1f" + + db_rom_handler.update_rom(rom.id, {"name": "Final Fantasy VII (PAL)"}) + assert stored() == "\x1ffinal fantasy vii (pal)\x1fff7\x1f" + + db_rom_handler.update_rom( + rom.id, {"moby_metadata": {"alternate_titles": ["FFVII"]}} + ) + assert stored() == "\x1ffinal fantasy vii (pal)\x1fff7\x1fffvii\x1f" + + with sync_session.begin() as session: + session.get_one(Rom, rom.id).name = "Final Fantasy VII International" + assert stored() == "\x1ffinal fantasy vii international\x1fff7\x1fffvii\x1f" diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index 950e962e4..d5d8fcf76 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -18,6 +18,7 @@ from alembic.migration import MigrationContext from alembic.operations import Operations from sqlalchemy import DefaultClause, FetchedValue, Table, UniqueConstraint from sqlalchemy.sql.schema import NULL_UNSPECIFIED +from tests.factories import make_rom import models from handler.database import db_collection_handler, db_platform_handler @@ -388,6 +389,43 @@ def test_the_search_aliases_revision_reverses_and_replays(): assert _schema_of(connection, "roms") == before +def test_the_search_titles_revision_reverses_replays_and_fills(platform: Platform): + """0147 fills existing rows, and resumes a run that stopped part-way.""" + migration = _load_migration("0147_roms_search_titles.py") + first = make_rom( + platform, "Final Fantasy VII", igdb_metadata={"alternative_names": ["FF7"]} + ) + second = make_rom(platform, "Chrono Trigger") + + def titles(connection: sa.Connection) -> dict[int, str | None]: + rows = connection.execute( + sa.text("SELECT id, search_titles FROM roms WHERE id IN (:a, :b)"), + {"a": first.id, "b": second.id}, + ) + return dict(rows.tuples().all()) + + with sync_engine.begin() as connection: + before = _schema_of(connection, "roms") + expected = titles(connection) + with Operations.context(MigrationContext.configure(connection)): + migration.downgrade() + assert not has_column(connection, "roms", "search_titles") + migration.downgrade() + + migration.upgrade() + assert titles(connection) == expected + + connection.execute( + sa.text("UPDATE roms SET search_titles = NULL WHERE id = :id"), + {"id": second.id}, + ) + migration.upgrade() + assert titles(connection) == expected + + assert _schema_of(connection, "roms") == before + assert expected[first.id] == "\x1ffinal fantasy vii\x1fff7\x1f" + + def _slot_collations(connection: sa.Connection) -> dict[str, str | None]: inspector = sa.inspect(connection) collations = {} diff --git a/backend/utils/roms_columns.py b/backend/utils/roms_columns.py index e8e4667ed..194e83030 100644 --- a/backend/utils/roms_columns.py +++ b/backend/utils/roms_columns.py @@ -22,6 +22,7 @@ from sqlalchemy.schema import CreateColumn from models.rom import ( ALTERNATIVE_NAME_SOURCES, FULL_PATH_HASH_LENGTH, + SEARCH_TEXT_MAX_LENGTH, TITLE_ID_MAX_LENGTH, ) from utils.database import ( @@ -48,9 +49,7 @@ PRIMARY_REGION_COLUMN = "generated_primary_region" PRIMARY_REGION_LENGTH = 50 FULL_PATH_HASH_COLUMN = "full_path_hash" RATING_COUNT_COLUMN = "generated_rating_count" -# In characters: a utf8mb4 TEXT holds 65535 bytes, and a longer value would -# fail the INSERT under strict mode. -SEARCH_ALIASES_MARIA_LENGTH = 16000 +SEARCH_TITLES_COLUMN = "search_titles" SAVE_TARGET_LAYOUT_COLUMN = "save_target_layout" SAVE_TARGET_LAYOUT_ENUM = "savetargetlayout" @@ -362,7 +361,7 @@ def _maria_alias_array(source: str, key: str) -> str: def _maria_search_aliases() -> str: arrays = [_maria_alias_array(src, key) for src, key in ALTERNATIVE_NAME_SOURCES] joined = "CONCAT_WS(' ', " + ", ".join(arrays) + ")" - return f"NULLIF(LEFT({joined}, {SEARCH_ALIASES_MARIA_LENGTH}), '')" + return f"NULLIF(LEFT({joined}, {SEARCH_TEXT_MAX_LENGTH}), '')" # --------------------------------------------------------------------------- @@ -567,6 +566,7 @@ PLAIN_COLUMNS = [ SAVE_TARGET_LAYOUT_COLUMN, sa.Enum(*SAVE_TARGET_LAYOUT_VALUES, name=SAVE_TARGET_LAYOUT_ENUM), ), + sa.Column(SEARCH_TITLES_COLUMN, sa.Text()), ]