diff --git a/backend/alembic/versions/0108_normalize_region_tags.py b/backend/alembic/versions/0108_normalize_region_tags.py deleted file mode 100644 index 2ce12a12a..000000000 --- a/backend/alembic/versions/0108_normalize_region_tags.py +++ /dev/null @@ -1,245 +0,0 @@ -"""Collapse region tags onto their canonical spelling - -``parse_tags`` only normalized regions written as a shortcode. A region written -as a name was stored with whatever casing the filename used, and a "Reg-" -prefixed code that was not in the shortcode table was stored verbatim, so one -library could hold "USA", "usa", "Usa" and "US" as four separate values. Each -became its own entry in the filter dropdowns and its own bucket in the platform -stats. The parser now resolves every spelling to a canonical name; this rewrites -the rows scanned before it did. - -``roms_facets.regions`` mirrors ``roms.regions`` through the triggers added in -0100, so updating ``roms`` is enough to fix the dropdowns too. - -Revision ID: 0108_normalize_region_tags -Revises: 0107_roms_dedup_cover_index -Create Date: 2026-08-15 00:00:00.000000 - -""" - -import sqlalchemy as sa -from alembic import op # type: ignore[attr-defined] - -from utils.database import CustomJSON - -# revision identifiers, used by Alembic. -revision = "0108_normalize_region_tags" -down_revision = "0107_roms_dedup_cover_index" -branch_labels = None -depends_on = None - -# Frozen copy of the resolver in handler/filesystem/base_handler.py. Inlined so -# later edits to that table can't retroactively change what this migration did. -_CANONICAL_REGIONS = ( - "Australia", - "Asia", - "Brazil", - "Canada", - "China", - "Europe", - "France", - "Finland", - "Germany", - "Greece", - "Holland", - "Hong Kong", - "Italy", - "Japan", - "Korea", - "Netherlands", - "Norway", - "Public Domain", - "Russia", - "Spain", - "Sweden", - "Taiwan", - "USA", - "England", - "Unknown", - "Unlicensed", - "World", -) - -_REGION_ALIASES = { - "A": "Australia", - "AS": "Asia", - "B": "Brazil", - "BRA": "Brazil", - "C": "Canada", - "CH": "China", - "CHN": "China", - "E": "Europe", - "EU": "Europe", - "EUR": "Europe", - "F": "France", - "FN": "Finland", - "G": "Germany", - "GLOBAL": "World", - "GR": "Greece", - "H": "Holland", - "HK": "Hong Kong", - "I": "Italy", - "J": "Japan", - "JP": "Japan", - "K": "Korea", - "NL": "Netherlands", - "NO": "Norway", - "PD": "Public Domain", - "R": "Russia", - "S": "Spain", - "SW": "Sweden", - "T": "Taiwan", - "U": "USA", - "UK": "England", - "UNK": "Unknown", - "UNL": "Unlicensed", - "US": "USA", - "W": "World", - "WR": "World", -} - -_REGION_BY_ALIAS = { - **{name.lower(): name for name in _CANONICAL_REGIONS}, - **{alias.lower(): name for alias, name in _REGION_ALIASES.items()}, -} - -# Minimal projections; the real models carry much more. -_roms = sa.table( - "roms", - sa.column("id", sa.Integer), - sa.column("regions", CustomJSON()), -) - -# Smart collections match their saved region list against `roms.regions` with -# JSON containment, so a criteria value left as "US" would match nothing once -# the rows above become "USA". Rewriting both keeps saved collections working. -_smart_collections = sa.table( - "smart_collections", - sa.column("id", sa.Integer), - sa.column("filter_criteria", CustomJSON()), -) - -# Both spellings of the criteria key. Early versions stored a single value -# under `selected_region`, and `get_smart_collection_criteria` still reads it. -_CRITERIA_KEYS = ("regions", "selected_region") - -# Rows held in memory at once. The roms pass walks the table by id rather than -# materializing it, so a large library can't balloon startup memory. -_BATCH_SIZE = 1000 - - -def _normalize(regions: list) -> list[str]: - """Canonicalize a region list, dropping duplicates but keeping order.""" - normalized: list[str] = [] - for region in regions: - if not isinstance(region, str): - continue - # Unknown values are kept as-is: a bare code we don't recognize is - # still the only region information that ROM has. - resolved = _REGION_BY_ALIAS.get(region.strip().lower(), region) - if resolved not in normalized: - normalized.append(resolved) - return normalized - - -def _normalize_criteria(criteria: dict) -> dict | None: - """Canonicalize a criteria blob, or return None if nothing changed. - - Handles both the list-valued key and the scalar `selected_*` one, keeping - each value's original shape so the reader sees what it expects. - """ - updated = dict(criteria) - changed = False - - for key in _CRITERIA_KEYS: - value = updated.get(key) - if isinstance(value, list): - normalized: list | str = _normalize(value) - elif isinstance(value, str): - resolved = _normalize([value]) - normalized = resolved[0] if resolved else value - else: - continue - - if normalized != value: - updated[key] = normalized - changed = True - - return updated if changed else None - - -def _upgrade_roms(connection) -> None: - # Walked by id in batches: a library can hold millions of rows, and this - # runs at startup. - statement = ( - sa.update(_roms).where(_roms.c.id == sa.bindparam("rom_id")) - # Per-row values rule out a CASE expression, and the JSON bind keeps - # the dialect differences (JSON vs JSONB) inside the type. - .values(regions=sa.bindparam("new_regions", type_=CustomJSON())) - ) - - last_id = -1 - while True: - rows = connection.execute( - sa.select(_roms.c.id, _roms.c.regions) - .where(_roms.c.regions.is_not(None), _roms.c.id > last_id) - .order_by(_roms.c.id) - .limit(_BATCH_SIZE) - ).fetchall() - - if not rows: - return - - last_id = rows[-1][0] - - updates = [] - for rom_id, regions in rows: - if not isinstance(regions, list): - continue - normalized = _normalize(regions) - if normalized != regions: - updates.append({"rom_id": rom_id, "new_regions": normalized}) - - if updates: - connection.execute(statement, updates) - - -def _upgrade_smart_collections(connection) -> None: - # Not batched: one row per user-created collection, so this is tens of rows. - rows = connection.execute( - sa.select(_smart_collections.c.id, _smart_collections.c.filter_criteria) - ).fetchall() - - updates = [] - for collection_id, criteria in rows: - if not isinstance(criteria, dict): - continue - normalized_criteria = _normalize_criteria(criteria) - if normalized_criteria is not None: - updates.append( - {"collection_id": collection_id, "new_criteria": normalized_criteria} - ) - - if not updates: - return - - connection.execute( - sa.update(_smart_collections) - .where(_smart_collections.c.id == sa.bindparam("collection_id")) - .values(filter_criteria=sa.bindparam("new_criteria", type_=CustomJSON())), - updates, - ) - - -def upgrade() -> None: - connection = op.get_bind() - - _upgrade_roms(connection) - _upgrade_smart_collections(connection) - - -def downgrade() -> None: - # The pre-normalization spellings came from filenames that were not - # recorded, so the old values can't be reconstructed. A rescan rebuilds - # them under whichever parser is in place. - pass diff --git a/backend/alembic/versions/0109_normalize_language_tags.py b/backend/alembic/versions/0109_normalize_language_tags.py deleted file mode 100644 index 693578ca9..000000000 --- a/backend/alembic/versions/0109_normalize_language_tags.py +++ /dev/null @@ -1,198 +0,0 @@ -"""Collapse language tags onto their canonical spelling - -The language half of what 0108 fixed for regions: ``parse_tags`` normalized a -language written as a shortcode but stored one written as a name with whatever -casing the filename used, so "English" and "english" became two filter entries. -The parser now resolves both, and every shortcode regardless of case; this -rewrites the rows scanned before it did. - -``roms_facets.languages`` mirrors ``roms.languages`` through the triggers added -in 0100, so updating ``roms`` is enough. - -Revision ID: 0109_normalize_language_tags -Revises: 0108_normalize_region_tags -Create Date: 2026-08-15 00:00:00.000000 - -""" - -import sqlalchemy as sa -from alembic import op # type: ignore[attr-defined] - -from utils.database import CustomJSON - -# revision identifiers, used by Alembic. -revision = "0109_normalize_language_tags" -down_revision = "0108_normalize_region_tags" -branch_labels = None -depends_on = None - -# Frozen copy of the LANGUAGES table in handler/filesystem/base_handler.py. -# Inlined so later edits to that table can't retroactively change what this -# migration did. -_LANGUAGES = ( - ("Ar", "Arabic"), - ("Da", "Danish"), - ("De", "German"), - ("El", "Greek"), - ("En", "English"), - ("Es", "Spanish"), - ("Fi", "Finnish"), - ("Fr", "French"), - ("It", "Italian"), - ("Ja", "Japanese"), - ("Ko", "Korean"), - ("Nl", "Dutch"), - ("No", "Norwegian"), - ("Pl", "Polish"), - ("Pt", "Portuguese"), - ("Ru", "Russian"), - ("Sr", "Serbian"), - ("Sv", "Swedish"), - ("Zh", "Chinese"), - ("nolang", "No Language"), -) - -# Names only, which is complete: the old parser resolved shortcodes to a name -# before storing, so every value here is already a name, just possibly in the -# filename's casing. Mapping codes as well would also mean guessing at "No", -# which reads as Norwegian in this column and Norway in `regions`. -_LANGUAGE_BY_NAME = {name.lower(): name for _, name in _LANGUAGES} - -# Minimal projections; the real models carry much more. -_roms = sa.table( - "roms", - sa.column("id", sa.Integer), - sa.column("languages", CustomJSON()), -) - -# Smart collections match their saved language list against `roms.languages` -# with JSON containment, so a criteria value left as "english" would match -# nothing once the rows above become "English". -_smart_collections = sa.table( - "smart_collections", - sa.column("id", sa.Integer), - sa.column("filter_criteria", CustomJSON()), -) - -# Both spellings of the criteria key. Early versions stored a single value -# under `selected_language`, and `get_smart_collection_criteria` still reads it. -_CRITERIA_KEYS = ("languages", "selected_language") - -# Rows held in memory at once. The roms pass walks the table by id rather than -# materializing it, so a large library can't balloon startup memory. -_BATCH_SIZE = 1000 - - -def _normalize(languages: list) -> list[str]: - """Canonicalize a language list, dropping duplicates but keeping order.""" - normalized: list[str] = [] - for language in languages: - if not isinstance(language, str): - continue - resolved = _LANGUAGE_BY_NAME.get(language.strip().lower(), language) - if resolved not in normalized: - normalized.append(resolved) - return normalized - - -def _normalize_criteria(criteria: dict) -> dict | None: - """Canonicalize a criteria blob, or return None if nothing changed. - - Handles both the list-valued key and the scalar `selected_*` one, keeping - each value's original shape so the reader sees what it expects. - """ - updated = dict(criteria) - changed = False - - for key in _CRITERIA_KEYS: - value = updated.get(key) - if isinstance(value, list): - normalized: list | str = _normalize(value) - elif isinstance(value, str): - resolved = _normalize([value]) - normalized = resolved[0] if resolved else value - else: - continue - - if normalized != value: - updated[key] = normalized - changed = True - - return updated if changed else None - - -def _upgrade_roms(connection) -> None: - # Walked by id in batches: a library can hold millions of rows, and this - # runs at startup. - statement = ( - sa.update(_roms).where(_roms.c.id == sa.bindparam("rom_id")) - # Per-row values rule out a CASE expression, and the JSON bind keeps - # the dialect differences (JSON vs JSONB) inside the type. - .values(languages=sa.bindparam("new_languages", type_=CustomJSON())) - ) - - last_id = -1 - while True: - rows = connection.execute( - sa.select(_roms.c.id, _roms.c.languages) - .where(_roms.c.languages.is_not(None), _roms.c.id > last_id) - .order_by(_roms.c.id) - .limit(_BATCH_SIZE) - ).fetchall() - - if not rows: - return - - last_id = rows[-1][0] - - updates = [] - for rom_id, languages in rows: - if not isinstance(languages, list): - continue - normalized = _normalize(languages) - if normalized != languages: - updates.append({"rom_id": rom_id, "new_languages": normalized}) - - if updates: - connection.execute(statement, updates) - - -def _upgrade_smart_collections(connection) -> None: - # Not batched: one row per user-created collection, so this is tens of rows. - rows = connection.execute( - sa.select(_smart_collections.c.id, _smart_collections.c.filter_criteria) - ).fetchall() - - updates = [] - for collection_id, criteria in rows: - if not isinstance(criteria, dict): - continue - normalized_criteria = _normalize_criteria(criteria) - if normalized_criteria is not None: - updates.append( - {"collection_id": collection_id, "new_criteria": normalized_criteria} - ) - - if not updates: - return - - connection.execute( - sa.update(_smart_collections) - .where(_smart_collections.c.id == sa.bindparam("collection_id")) - .values(filter_criteria=sa.bindparam("new_criteria", type_=CustomJSON())), - updates, - ) - - -def upgrade() -> None: - connection = op.get_bind() - - _upgrade_roms(connection) - _upgrade_smart_collections(connection) - - -def downgrade() -> None: - # The pre-normalization spellings came from filenames that were not - # recorded, so the old values can't be reconstructed. A rescan rebuilds - # them under whichever parser is in place. - pass diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 3c2455866..fd8d43ee4 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -90,26 +90,10 @@ REGIONS = ( REGIONS_BY_SHORTCODE = {region[0]: region[1] for region in REGIONS} -# Alternate spellings seen in filenames, mapped onto their REGIONS name. The -# shortcodes and canonical names above are accepted without being listed here. -# Nothing in this table may collide with a LANGUAGES shortcode: region tags are -# resolved first, so "De" as a region would make German unparseable. -REGION_ALIASES = { - "BRA": "Brazil", - "CHN": "China", - "EU": "Europe", - "EUR": "Europe", - "GLOBAL": "World", - "JP": "Japan", - "US": "USA", - "WR": "World", -} - # Every accepted region spelling, lowercased, mapped to its canonical name. _REGION_BY_ALIAS = { **{name.lower(): name for _, name in REGIONS}, **{code.lower(): name for code, name in REGIONS}, - **{alias.lower(): name for alias, name in REGION_ALIASES.items()}, } @@ -169,8 +153,6 @@ def region_name_to_provider_shortcode(region_name: str | None) -> str | None: LANGUAGES_BY_SHORTCODE = {lang[0]: lang[1] for lang in LANGUAGES} # Every accepted language spelling, lowercased, mapped to its canonical name. -# No alias table alongside it: unlike regions, filenames spell languages either -# as the ISO code or the English name, both of which are already in LANGUAGES. _LANGUAGE_BY_ALIAS = { **{name.lower(): name for _, name in LANGUAGES}, **{code.lower(): name for code, name in LANGUAGES}, diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 4d7e97829..6ef1a2912 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -13,7 +13,6 @@ from tests._zipfile_shim import reload_zipfile from config.config_manager import LIBRARY_BASE_PATH, Config from handler.filesystem.base_handler import ( LANGUAGES_BY_SHORTCODE, - REGION_ALIASES, REGIONS_BY_SHORTCODE, ) from handler.filesystem.roms_handler import ( @@ -283,12 +282,9 @@ class TestFSRomsHandler: # A value that is not a shortcode is kept verbatim. assert "PAL" in handler.parse_tags("Game [Reg-PAL].rom").regions - # Aliases resolve here too, so [Reg-US] and (USA) agree. - assert "USA" in handler.parse_tags("Game [Reg-US].rom").regions - # A space after the separator isn't part of the value. assert handler.parse_tags("Game [Reg- PAL].rom").regions == ["PAL"] - assert handler.parse_tags("Game [Reg- US].rom").regions == ["USA"] + assert handler.parse_tags("Game [Reg- U].rom").regions == ["USA"] def test_parse_tags_region_casing_is_normalized(self, handler: FSRomsHandler): """Region names collapse to one canonical spelling regardless of casing.""" @@ -297,18 +293,7 @@ class TestFSRomsHandler: assert handler.parse_tags("Game (europe).rom").regions == ["Europe"] assert handler.parse_tags("Game (hong kong).rom").regions == ["Hong Kong"] - - def test_parse_tags_region_aliases(self, handler: FSRomsHandler): - """Alternate spellings resolve to the canonical region name.""" - assert handler.parse_tags("Game (US).rom").regions == ["USA"] assert handler.parse_tags("Game (u).rom").regions == ["USA"] - assert handler.parse_tags("Game (EU).rom").regions == ["Europe"] - assert handler.parse_tags("Game (eur).rom").regions == ["Europe"] - assert handler.parse_tags("Game (jp).rom").regions == ["Japan"] - - # WR joins (W) and (World) on the same facet value. - assert handler.parse_tags("Game (WR).rom").regions == ["World"] - assert handler.parse_tags("Game [Reg-WR].rom").regions == ["World"] # An unknown tag is still just a tag. parsed = handler.parse_tags("Game (Nonsense).rom") @@ -1781,19 +1766,6 @@ class TestExtractCHDHash: assert len(result) == 40 -def test_region_aliases_never_shadow_a_language_code(): - """Enforce the constraint REGION_ALIASES only documents. - - Region tags resolve before language ones, so an alias that matched a - language shortcode would make that language unparseable in lowercase. - The Nl/No overlap in REGIONS itself is deliberate and covered separately. - """ - language_codes = {code.lower() for code in LANGUAGES_BY_SHORTCODE} - collisions = {alias for alias in REGION_ALIASES if alias.lower() in language_codes} - - assert not collisions, f"region aliases shadow language codes: {collisions}" - - KNOWN_REGION_NAMES = frozenset(REGIONS_BY_SHORTCODE.values()) KNOWN_LANGUAGE_NAMES = frozenset(LANGUAGES_BY_SHORTCODE.values())