mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
Merge pull request #4260 from sdornan/feat/region-priority-default-sibling
feat(gallery): pick a game's default version by region priority
This commit is contained in:
87
backend/alembic/versions/0108_roms_primary_region.py
Normal file
87
backend/alembic/versions/0108_roms_primary_region.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""Add a generated primary_region column and cover it in the dedup index
|
||||
|
||||
Region priority decides which sibling represents its group in the gallery, so
|
||||
the group_by_meta_id dedup window has to read each rom's region. `roms.regions`
|
||||
is JSON, which no covering index can carry (a prefix index cannot answer
|
||||
JSON_CONTAINS on its own), and 0107 measured what one uncovered reference costs
|
||||
that window: the plan drops from `type=index, Using index` to `type=ALL,
|
||||
key=NULL`, four times per gallery page load.
|
||||
|
||||
A STORED generated column over `regions[0]` gives the window a scalar the index
|
||||
can cover. The engine computes it at write time and keeps it in sync, so no
|
||||
scan hook and no backfill are needed: ALTER TABLE populates existing rows, and
|
||||
multi-region names like "(USA, Europe)" resolve to the first tag, which is the
|
||||
release's primary market.
|
||||
|
||||
`idx_roms_sibling_cover` grows by a varchar(50), well inside both the InnoDB
|
||||
3072-byte key limit and PostgreSQL's btree tuple limit.
|
||||
|
||||
Cross-engine notes:
|
||||
- MariaDB JSON_EXTRACT returns a quoted scalar, so JSON_UNQUOTE runs before the
|
||||
result reaches the varchar.
|
||||
- Both expressions truncate with LEFT, because `regions` has no length cap of
|
||||
its own: an unrecognized `[Reg-...]` tag is kept verbatim, and a value longer
|
||||
than the column would otherwise fail the INSERT under strict mode.
|
||||
|
||||
Revision ID: 0108_roms_primary_region
|
||||
Revises: 0107_roms_dedup_cover_index
|
||||
Create Date: 2026-08-21 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op # type: ignore[attr-defined]
|
||||
|
||||
from utils.database import is_postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0108_roms_primary_region"
|
||||
down_revision = "0107_roms_dedup_cover_index"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
COLUMN_NAME = "generated_primary_region"
|
||||
COLUMN_LENGTH = 50
|
||||
|
||||
INDEX_NAME = "idx_roms_sibling_cover"
|
||||
_INDEX_HEAD = [
|
||||
"platform_id",
|
||||
"igdb_id",
|
||||
"moby_id",
|
||||
"ss_id",
|
||||
"launchbox_id",
|
||||
"ra_id",
|
||||
"hasheous_id",
|
||||
"tgdb_id",
|
||||
"flashpoint_id",
|
||||
"fs_name_no_ext",
|
||||
]
|
||||
OLD_INDEX_COLUMNS = [*_INDEX_HEAD, "id"]
|
||||
NEW_INDEX_COLUMNS = [*_INDEX_HEAD, COLUMN_NAME, "id"]
|
||||
|
||||
_MARIA_EXPR = f"LEFT(JSON_UNQUOTE(JSON_EXTRACT(regions, '$[0]')), {COLUMN_LENGTH})"
|
||||
_POSTGRES_EXPR = f"left(regions ->> 0, {COLUMN_LENGTH})"
|
||||
|
||||
|
||||
def _rebuild_index(columns: list[str]) -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.drop_index(INDEX_NAME, if_exists=True)
|
||||
batch_op.create_index(
|
||||
INDEX_NAME,
|
||||
columns,
|
||||
unique=False,
|
||||
if_not_exists=True,
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
expr = _POSTGRES_EXPR if is_postgresql(op.get_bind()) else _MARIA_EXPR
|
||||
op.execute(
|
||||
f"ALTER TABLE roms ADD COLUMN {COLUMN_NAME} VARCHAR({COLUMN_LENGTH}) " # nosec B608
|
||||
f"GENERATED ALWAYS AS ({expr}) STORED"
|
||||
)
|
||||
_rebuild_index(NEW_INDEX_COLUMNS)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_rebuild_index(OLD_INDEX_COLUMNS)
|
||||
op.execute(f"ALTER TABLE roms DROP COLUMN {COLUMN_NAME}") # nosec B608
|
||||
@@ -15,6 +15,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses.config import ConfigResponse
|
||||
from exceptions.config_exceptions import ConfigNotWritableException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_rom_handler
|
||||
from logger.logger import log
|
||||
from utils.router import APIRouter
|
||||
|
||||
@@ -253,6 +254,10 @@ async def delete_exclusion(
|
||||
async def update_scan_settings(request: Request, payload: ScanSettingsPayload) -> None:
|
||||
"""Replace the scan.* section of the configuration"""
|
||||
|
||||
region_priority_changed = (
|
||||
cm.get_config().SCAN_REGION_PRIORITY != payload.region_priority
|
||||
)
|
||||
|
||||
try:
|
||||
cm.update_scan_settings(
|
||||
metadata_priority=payload.metadata_priority,
|
||||
@@ -275,3 +280,8 @@ async def update_scan_settings(request: Request, payload: ScanSettingsPayload) -
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
|
||||
) from exc
|
||||
|
||||
# Region priority picks the primary rom of each sibling group, so every
|
||||
# cached gallery sidecar is stale the moment the order changes.
|
||||
if region_priority_changed:
|
||||
db_rom_handler.invalidate_filter_values_cache()
|
||||
|
||||
@@ -44,11 +44,12 @@ from sqlalchemy.sql.elements import ColumnElement
|
||||
from sqlalchemy.sql.selectable import Select
|
||||
|
||||
from config import ROMM_DB_DRIVER
|
||||
from config.config_manager import config_manager as cm
|
||||
from decorators.database import begin_session
|
||||
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
|
||||
from handler.redis_handler import sync_cache
|
||||
from models.assets import Save, Screenshot, State
|
||||
from models.base import compute_file_name_parts
|
||||
from models.base import PRERELEASE_FILENAME_TAGS, compute_file_name_parts
|
||||
from models.collection import Collection, CollectionRom, SmartCollection
|
||||
from models.music import MusicFavoriteTrack, MusicPlaylistTrack
|
||||
from models.platform import Platform
|
||||
@@ -325,6 +326,49 @@ def _create_metadata_id_case(
|
||||
)
|
||||
|
||||
|
||||
def _region_rank() -> ColumnElement:
|
||||
"""Rank a rom by where its region sits in the configured region priority.
|
||||
|
||||
Reads the generated scalar rather than the `regions` JSON so the dedup
|
||||
window stays inside idx_roms_sibling_cover. Roms whose region is not in the
|
||||
list rank last, so a Japan-only release still wins a group of one.
|
||||
"""
|
||||
# Imported here because handler.filesystem and handler.metadata import each
|
||||
# other, and reaching filesystem first from this module trips the cycle.
|
||||
from handler.filesystem.base_handler import region_ranks_for_priority
|
||||
|
||||
ranks = region_ranks_for_priority(cm.get_config().SCAN_REGION_PRIORITY)
|
||||
if not ranks:
|
||||
return literal(0)
|
||||
|
||||
return case(
|
||||
ranks,
|
||||
value=Rom.generated_primary_region,
|
||||
else_=max(ranks.values()) + 1,
|
||||
)
|
||||
|
||||
|
||||
def _prerelease_rank() -> ColumnElement:
|
||||
"""Rank pre-release dumps after full releases within a sibling group.
|
||||
|
||||
Matched with a case-insensitive LIKE over the filename rather than against
|
||||
the parsed `tags` column, which keeps whatever casing the dumper used, and
|
||||
which the dedup window's covering index does not carry.
|
||||
"""
|
||||
return case(
|
||||
(
|
||||
or_(
|
||||
*[
|
||||
Rom.fs_name_no_ext.ilike(f"%({tag}%")
|
||||
for tag in PRERELEASE_FILENAME_TAGS
|
||||
]
|
||||
),
|
||||
1,
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
|
||||
|
||||
def with_details(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
@@ -1273,8 +1317,10 @@ class DBRomsHandler(DBBaseHandler):
|
||||
else literal(1)
|
||||
)
|
||||
|
||||
# Create a subquery that identifies the primary ROM in each group
|
||||
# Priority order: is_main_sibling (desc), then by fs_name_no_ext (asc).
|
||||
# Create a subquery that identifies the primary ROM in each group.
|
||||
# Priority order: is_main_sibling (desc), then a full release over
|
||||
# a pre-release, then the configured region priority, then
|
||||
# fs_name_no_ext (asc) as a stable tiebreak.
|
||||
# Materialize only the columns the dedup window needs (not all of
|
||||
# Rom, whose JSON metadata blobs make the derived table huge), and
|
||||
# drop the carried-over ORDER BY the window doesn't use.
|
||||
@@ -1283,6 +1329,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
.with_only_columns( # type: ignore
|
||||
Rom.id,
|
||||
Rom.fs_name_no_ext,
|
||||
_prerelease_rank().label("prerelease_rank"),
|
||||
_region_rank().label("region_rank"),
|
||||
Rom.platform_id,
|
||||
Rom.igdb_id,
|
||||
Rom.ss_id,
|
||||
@@ -1360,6 +1408,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
),
|
||||
order_by=[
|
||||
is_main_sibling_order,
|
||||
base_subquery.c.prerelease_rank.asc(),
|
||||
base_subquery.c.region_rank.asc(),
|
||||
base_subquery.c.fs_name_no_ext.asc(),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from collections.abc import Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from enum import Enum
|
||||
from io import BytesIO
|
||||
@@ -150,6 +151,37 @@ def region_name_to_provider_shortcode(region_name: str | None) -> str | None:
|
||||
return _REGION_NAME_TO_PROVIDER_SHORTCODE_CI.get(region_name.lower())
|
||||
|
||||
|
||||
# Reverse of REGION_NAME_TO_PROVIDER_SHORTCODE. A list per code because two
|
||||
# names can claim one code ("nl" for both Holland and Netherlands), and a rom
|
||||
# tagged with either has to rank the same.
|
||||
_REGION_NAMES_BY_PROVIDER_SHORTCODE: dict[str, list[str]] = {}
|
||||
for _name, _code in REGION_NAME_TO_PROVIDER_SHORTCODE.items():
|
||||
_REGION_NAMES_BY_PROVIDER_SHORTCODE.setdefault(_code, []).append(_name)
|
||||
|
||||
|
||||
def region_ranks_for_priority(shortcodes: Sequence[str]) -> dict[str, int]:
|
||||
"""Map canonical region names to their rank in a shortcode priority list.
|
||||
|
||||
The rank is the shortcode's position, not the name's, so two names claiming
|
||||
one shortcode ("nl" for both Holland and Netherlands) rank equally and fall
|
||||
through to whatever tiebreak follows.
|
||||
|
||||
A shortcode naming no known region (ScreenScraper's "ss", or a typo the
|
||||
open-ended settings input allowed) contributes nothing rather than shifting
|
||||
the ranks of everything after it. Nor does a repeated shortcode.
|
||||
"""
|
||||
ranks: dict[str, int] = {}
|
||||
next_rank = 0
|
||||
for shortcode in dict.fromkeys(code.lower() for code in shortcodes):
|
||||
names = _REGION_NAMES_BY_PROVIDER_SHORTCODE.get(shortcode)
|
||||
if not names:
|
||||
continue
|
||||
for name in names:
|
||||
ranks[name] = next_rank
|
||||
next_rank += 1
|
||||
return ranks
|
||||
|
||||
|
||||
LANGUAGES_BY_SHORTCODE = {lang[0]: lang[1] for lang in LANGUAGES}
|
||||
|
||||
# Every accepted language spelling, lowercased, mapped to its canonical name.
|
||||
|
||||
@@ -14,6 +14,18 @@ TAG_GROUP_REGEX = re.compile(r"(?:\s*(?:\([^)]*\)|\[[^]]*\]))+\s*$")
|
||||
# Matches a trailing file extension, including multi-part ones like ".tar.gz".
|
||||
EXTENSION_REGEX = re.compile(r"\.(([a-z]+\.)*\w+)$")
|
||||
|
||||
# Filename tags that mark a dump as a pre-release rather than the shipped game.
|
||||
# Lowercase and unterminated so one prefix covers its variants: "demo" also
|
||||
# matches "(Demo Kiosk)", "proto" also matches "(Prototype)".
|
||||
PRERELEASE_FILENAME_TAGS = (
|
||||
"demo",
|
||||
"beta",
|
||||
"proto",
|
||||
"sample",
|
||||
"kiosk",
|
||||
"preview",
|
||||
)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
@@ -384,6 +384,7 @@ class Rom(BaseModel):
|
||||
"tgdb_id",
|
||||
"flashpoint_id",
|
||||
"fs_name_no_ext",
|
||||
"generated_primary_region",
|
||||
"id",
|
||||
),
|
||||
Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"),
|
||||
@@ -488,6 +489,14 @@ class Rom(BaseModel):
|
||||
languages: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
|
||||
tags: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[])
|
||||
|
||||
# STORED generated column over regions[0], carried by idx_roms_sibling_cover
|
||||
# so the dedup window can rank regions without reading the JSON.
|
||||
generated_primary_region: Mapped[str | None] = mapped_column(
|
||||
String(length=50),
|
||||
server_default=FetchedValue(),
|
||||
server_onupdate=FetchedValue(),
|
||||
)
|
||||
|
||||
crc_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
md5_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
sha1_hash: Mapped[str | None] = mapped_column(String(length=100))
|
||||
|
||||
@@ -13,12 +13,18 @@ its partition tail and its sort tiebreaker. The gallery issues the grouped query
|
||||
up to four times per page load (page, count, char index, id index), so the scan
|
||||
was paid four times over. 0107 widened the index to close the gap.
|
||||
|
||||
0108 added `generated_primary_region` for the same reason: region priority ranks
|
||||
each sibling, and `roms.regions` is JSON that no covering index can carry.
|
||||
|
||||
The failure mode is silent, and adding a metadata provider is the way back into
|
||||
it: a new id column joins the window's COALESCE chain, the index does not follow
|
||||
it, and the gallery quietly returns to full scans.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.dialects import mysql
|
||||
from sqlalchemy.sql import Subquery
|
||||
from sqlalchemy.sql.expression import Select
|
||||
from tests.conftest import engine
|
||||
@@ -37,6 +43,7 @@ INDEX_COLUMNS = [
|
||||
"tgdb_id",
|
||||
"flashpoint_id",
|
||||
"fs_name_no_ext",
|
||||
"generated_primary_region",
|
||||
"id",
|
||||
]
|
||||
|
||||
@@ -52,25 +59,47 @@ def _subqueries(clause, found: list[Subquery] | None = None) -> list[Subquery]:
|
||||
return found
|
||||
|
||||
|
||||
def _dedup_window_columns() -> set[str]:
|
||||
"""The `roms` columns the grouped query materializes for its window."""
|
||||
def _dedup_window_subquery() -> Select:
|
||||
"""The narrow `roms` subquery the grouped query materializes for its window."""
|
||||
query, _ = db_rom_handler.get_roms_query()
|
||||
grouped = db_rom_handler.filter_roms(query=query, group_by_meta_id=True)
|
||||
|
||||
for subquery in _subqueries(grouped):
|
||||
if not isinstance(subquery.element, Select):
|
||||
continue
|
||||
columns = {
|
||||
column.name
|
||||
if any(
|
||||
getattr(column, "table", None) is Rom.__table__
|
||||
for column in subquery.element.selected_columns
|
||||
if getattr(column, "table", None) is Rom.__table__
|
||||
}
|
||||
if columns:
|
||||
return columns
|
||||
):
|
||||
return subquery.element
|
||||
|
||||
raise AssertionError("the grouped query no longer materializes a roms subquery")
|
||||
|
||||
|
||||
def _dedup_window_columns() -> set[str]:
|
||||
"""The `roms` columns the window selects directly."""
|
||||
return {
|
||||
column.name
|
||||
for column in _dedup_window_subquery().selected_columns
|
||||
if getattr(column, "table", None) is Rom.__table__
|
||||
}
|
||||
|
||||
|
||||
def _dedup_window_referenced_columns() -> set[str]:
|
||||
"""Every `roms` column the window's SQL reads, expressions included.
|
||||
|
||||
Selecting a bare column is only one way in: a CASE or a function call over
|
||||
an uncovered column reads it just the same while carrying no `.table`, so
|
||||
the compiled SQL is what has to be inspected.
|
||||
"""
|
||||
sql = str(
|
||||
_dedup_window_subquery().compile(
|
||||
dialect=mysql.dialect(), compile_kwargs={"literal_binds": True}
|
||||
)
|
||||
)
|
||||
return set(re.findall(r"\broms\.(\w+)", sql))
|
||||
|
||||
|
||||
class TestSiblingCoverIndex:
|
||||
def test_migrations_create_covering_index(self):
|
||||
indexes = [
|
||||
@@ -84,6 +113,9 @@ class TestGroupByMetaIdCoverage:
|
||||
def test_dedup_window_reads_only_covered_columns(self):
|
||||
assert _dedup_window_columns() <= set(INDEX_COLUMNS)
|
||||
|
||||
def test_dedup_window_expressions_read_only_covered_columns(self):
|
||||
assert _dedup_window_referenced_columns() <= set(INDEX_COLUMNS)
|
||||
|
||||
def test_dedup_window_excludes_the_wide_metadata_columns(self):
|
||||
assert not {
|
||||
column for column in _dedup_window_columns() if column.endswith("_metadata")
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
from fastapi import UploadFile
|
||||
|
||||
from config.config_manager import DEFAULT_EXCLUDED_FILES
|
||||
from handler.filesystem.base_handler import FSHandler
|
||||
from handler.filesystem.base_handler import FSHandler, region_ranks_for_priority
|
||||
from models.base import FILE_NAME_MAX_LENGTH
|
||||
|
||||
|
||||
@@ -605,3 +605,35 @@ class TestFSHandlerInit:
|
||||
):
|
||||
with pytest.raises(PermissionError):
|
||||
FSHandler("/some/unwritable/path")
|
||||
|
||||
|
||||
class TestRegionRanksForPriority:
|
||||
"""Ranking is per configured shortcode, not per expanded region name."""
|
||||
|
||||
def test_two_names_sharing_a_shortcode_rank_equally(self):
|
||||
ranks = region_ranks_for_priority(["nl", "jp"])
|
||||
|
||||
assert ranks["Holland"] == ranks["Netherlands"]
|
||||
# And the next shortcode still ranks strictly below them.
|
||||
assert ranks["Japan"] > ranks["Netherlands"]
|
||||
|
||||
def test_unknown_shortcode_does_not_shift_later_ranks(self):
|
||||
# "ss" is a ScreenScraper bucket, not a region.
|
||||
assert region_ranks_for_priority(["us", "ss", "jp"]) == {
|
||||
"USA": 0,
|
||||
"Japan": 1,
|
||||
}
|
||||
|
||||
def test_repeated_shortcode_does_not_shift_later_ranks(self):
|
||||
assert region_ranks_for_priority(["us", "us", "jp"]) == {
|
||||
"USA": 0,
|
||||
"Japan": 1,
|
||||
}
|
||||
|
||||
def test_ranks_follow_the_configured_order(self):
|
||||
ranks = region_ranks_for_priority(["jp", "us"])
|
||||
|
||||
assert ranks["Japan"] < ranks["USA"]
|
||||
|
||||
def test_empty_priority_yields_no_ranks(self):
|
||||
assert region_ranks_for_priority([]) == {}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
@@ -387,6 +389,159 @@ def test_group_by_meta_id_with_empty_fs_name_no_tags(platform: Platform):
|
||||
assert len(roms) == len(rom_names)
|
||||
|
||||
|
||||
def test_group_by_meta_id_prefers_full_release_over_prerelease(platform: Platform):
|
||||
"""A pre-release must not represent its group just by sorting first.
|
||||
|
||||
"(Demo)" sorts ahead of "(USA)", so the filename tiebreaker alone hands the
|
||||
gallery entry to the demo.
|
||||
"""
|
||||
for tag in ["(Demo)", "(USA)"]:
|
||||
name = f"Sonic {tag}"
|
||||
db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
igdb_id=1234,
|
||||
name=name,
|
||||
slug=f"sonic-{tag.strip('()').lower()}",
|
||||
fs_name=f"{name}.zip",
|
||||
fs_name_no_tags="Sonic",
|
||||
fs_name_no_ext=name,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
)
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id],
|
||||
order_by="name",
|
||||
order_dir="asc",
|
||||
group_by_meta_id=True,
|
||||
)
|
||||
|
||||
assert [r.fs_name_no_ext for r in roms] == ["Sonic (USA)"]
|
||||
|
||||
|
||||
def _add_sibling(platform: Platform, tag: str, igdb_id: int, regions: list[str]):
|
||||
name = f"Sonic {tag}"
|
||||
return db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
igdb_id=igdb_id,
|
||||
name=name,
|
||||
slug=f"sonic-{tag.strip('()').lower()}",
|
||||
fs_name=f"{name}.zip",
|
||||
fs_name_no_tags="Sonic",
|
||||
fs_name_no_ext=name,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
regions=regions,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _grouped_names(platform: Platform) -> list[str]:
|
||||
return [
|
||||
rom.fs_name_no_ext
|
||||
for rom in db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id],
|
||||
order_by="name",
|
||||
order_dir="asc",
|
||||
group_by_meta_id=True,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_primary_region_mirrors_the_first_parsed_region(platform: Platform):
|
||||
"""The generated column tracks regions[0] without the scan writing it."""
|
||||
rom = _add_sibling(platform, "(USA, Europe)", 4321, ["USA", "Europe"])
|
||||
|
||||
assert db_rom_handler.get_rom(rom.id).generated_primary_region == "USA"
|
||||
|
||||
|
||||
def test_primary_region_is_null_without_region_tags(platform: Platform):
|
||||
rom = _add_sibling(platform, "(Unknown)", 4322, [])
|
||||
|
||||
assert db_rom_handler.get_rom(rom.id).generated_primary_region is None
|
||||
|
||||
|
||||
def test_group_by_meta_id_prefers_the_higher_priority_region(platform: Platform):
|
||||
"""The default priority puts USA ahead of Japan.
|
||||
|
||||
"(Japan)" sorts before "(USA)", so the filename tiebreaker alone hands the
|
||||
gallery entry to the Japanese release.
|
||||
"""
|
||||
_add_sibling(platform, "(Japan)", 2345, ["Japan"])
|
||||
_add_sibling(platform, "(USA)", 2345, ["USA"])
|
||||
|
||||
assert _grouped_names(platform) == ["Sonic (USA)"]
|
||||
|
||||
|
||||
def test_group_by_meta_id_keeps_an_unprioritized_region_group(platform: Platform):
|
||||
"""A region absent from the priority list still represents a group of one."""
|
||||
_add_sibling(platform, "(Korea)", 3456, ["Korea"])
|
||||
|
||||
assert _grouped_names(platform) == ["Sonic (Korea)"]
|
||||
|
||||
|
||||
def test_group_by_meta_id_ranks_region_below_release_status(platform: Platform):
|
||||
"""A demo of the preferred region loses to a full release of any region.
|
||||
|
||||
A pre-release is not a substitute for the game, so release status outranks
|
||||
region rather than the other way round.
|
||||
"""
|
||||
_add_sibling(platform, "(USA) (Demo)", 4567, ["USA"])
|
||||
_add_sibling(platform, "(Japan)", 4567, ["Japan"])
|
||||
|
||||
assert _grouped_names(platform) == ["Sonic (Japan)"]
|
||||
|
||||
|
||||
def test_group_by_meta_id_ties_names_sharing_a_region_shortcode(
|
||||
platform: Platform,
|
||||
):
|
||||
"""Holland and Netherlands both configure as "nl", so neither outranks the
|
||||
other and the filename tiebreak decides.
|
||||
|
||||
The filenames deliberately sort opposite to the order the reverse shortcode
|
||||
map emits those two names in, so ranking them separately picks the Holland
|
||||
rom and ranking them equally picks the alphabetically first one.
|
||||
"""
|
||||
_add_sibling(platform, "(NL-a)", 5678, ["Netherlands"])
|
||||
_add_sibling(platform, "(NL-b)", 5678, ["Holland"])
|
||||
|
||||
with patch(
|
||||
"handler.database.roms_handler.cm.get_config",
|
||||
return_value=SimpleNamespace(SCAN_REGION_PRIORITY=["nl"]),
|
||||
):
|
||||
assert _grouped_names(platform) == ["Sonic (NL-a)"]
|
||||
|
||||
|
||||
def test_group_by_meta_id_keeps_a_prerelease_only_group(platform: Platform):
|
||||
"""A game that exists only as a pre-release still gets a gallery entry."""
|
||||
name = "Unreleased Game (Proto)"
|
||||
db_rom_handler.add_rom(
|
||||
Rom(
|
||||
platform_id=platform.id,
|
||||
igdb_id=5678,
|
||||
name=name,
|
||||
slug="unreleased-game-proto",
|
||||
fs_name=f"{name}.zip",
|
||||
fs_name_no_tags="Unreleased Game",
|
||||
fs_name_no_ext=name,
|
||||
fs_extension="zip",
|
||||
fs_path=f"{platform.slug}/roms",
|
||||
)
|
||||
)
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id],
|
||||
order_by="name",
|
||||
order_dir="asc",
|
||||
group_by_meta_id=True,
|
||||
)
|
||||
|
||||
assert [r.fs_name_no_ext for r in roms] == [name]
|
||||
|
||||
|
||||
def test_natural_sort_order(platform: Platform):
|
||||
"""Numbers in names should sort numerically, not lexicographically."""
|
||||
for name in ["Game 10", "Game 2", "Game 1"]:
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Предложения",
|
||||
"scan-region-placeholder": "Добави код на регион (напр. us, eu, jp)",
|
||||
"scan-region-priority": "Приоритет на регионите",
|
||||
"scan-region-priority-desc": "Ред на кодовете на региони, използвани от IGDB и ScreenScraper за регионални варианти. Печели първият наличен регион.",
|
||||
"scan-region-priority-desc": "Ред на кодовете на региони, използвани за регионални варианти — както за версията на игра, показвана по подразбиране, така и за графиките от IGDB и ScreenScraper. Печели първият наличен регион.",
|
||||
"scan-settings": "Настройки за сканиране",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Návrhy",
|
||||
"scan-region-placeholder": "Přidejte kód regionu (např. us, eu, jp)",
|
||||
"scan-region-priority": "Priorita regionů",
|
||||
"scan-region-priority-desc": "Pořadí kódů regionů používaných IGDB a ScreenScraper pro regionální varianty. Vyhrává první dostupný region.",
|
||||
"scan-region-priority-desc": "Pořadí kódů regionů používaných pro regionální varianty, jak pro výchozí zobrazenou verzi hry, tak pro grafiku z IGDB a ScreenScraper. Vyhrává první dostupný region.",
|
||||
"scan-settings": "Nastavení skenování",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Vorschläge",
|
||||
"scan-region-placeholder": "Regionscode hinzufügen (z. B. us, eu, jp)",
|
||||
"scan-region-priority": "Regionspriorität",
|
||||
"scan-region-priority-desc": "Reihenfolge der von IGDB und ScreenScraper für regionale Varianten verwendeten Regionscodes. Die erste verfügbare Region gewinnt.",
|
||||
"scan-region-priority-desc": "Reihenfolge der Regionscodes für regionale Varianten, sowohl für die standardmäßig angezeigte Version eines Spiels als auch für das Artwork von IGDB und ScreenScraper. Die erste verfügbare Region gewinnt.",
|
||||
"scan-settings": "Scan-Einstellungen",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Suggestions",
|
||||
"scan-region-placeholder": "Add a region code (e.g. us, eu, jp)",
|
||||
"scan-region-priority": "Region priority",
|
||||
"scan-region-priority-desc": "Order of region codes used by IGDB and ScreenScraper for regional variants. The first available region wins.",
|
||||
"scan-region-priority-desc": "Order of region codes used for regional variants, both the version of a game shown by default and the artwork from IGDB and ScreenScraper. The first available region wins.",
|
||||
"scan-settings": "Scan settings",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Suggestions",
|
||||
"scan-region-placeholder": "Add a region code (e.g. us, eu, jp)",
|
||||
"scan-region-priority": "Region priority",
|
||||
"scan-region-priority-desc": "Order of region codes used by IGDB and ScreenScraper for regional variants. The first available region wins.",
|
||||
"scan-region-priority-desc": "Order of region codes used for regional variants, both the version of a game shown by default and the artwork from IGDB and ScreenScraper. The first available region wins.",
|
||||
"scan-settings": "Scan settings",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Sugerencias",
|
||||
"scan-region-placeholder": "Añadir un código de región (p. ej. us, eu, jp)",
|
||||
"scan-region-priority": "Prioridad de regiones",
|
||||
"scan-region-priority-desc": "Orden de los códigos de región usados por IGDB y ScreenScraper para las variantes regionales. Gana la primera región disponible.",
|
||||
"scan-region-priority-desc": "Orden de los códigos de región usados para las variantes regionales, tanto la versión de un juego mostrada por defecto como las ilustraciones de IGDB y ScreenScraper. Gana la primera región disponible.",
|
||||
"scan-settings": "Ajustes de escaneo",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Suggestions",
|
||||
"scan-region-placeholder": "Ajouter un code de région (ex. us, eu, jp)",
|
||||
"scan-region-priority": "Priorité des régions",
|
||||
"scan-region-priority-desc": "Ordre des codes de région utilisés par IGDB et ScreenScraper pour les variantes régionales. La première région disponible l'emporte.",
|
||||
"scan-region-priority-desc": "Ordre des codes de région utilisés pour les variantes régionales, à la fois la version d'un jeu affichée par défaut et les artworks d'IGDB et ScreenScraper. La première région disponible l'emporte.",
|
||||
"scan-settings": "Paramètres de scan",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Javaslatok",
|
||||
"scan-region-placeholder": "Régiókód hozzáadása (pl. us, eu, jp)",
|
||||
"scan-region-priority": "Régió prioritás",
|
||||
"scan-region-priority-desc": "Az IGDB és a ScreenScraper által a regionális változatokhoz használt régiókódok sorrendje. Az első elérhető régió nyer.",
|
||||
"scan-region-priority-desc": "A regionális változatokhoz használt régiókódok sorrendje, mind a játék alapértelmezetten megjelenő verziójához, mind az IGDB és a ScreenScraper grafikáihoz. Az első elérhető régió nyer.",
|
||||
"scan-settings": "Szkennelési beállítások",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Suggerimenti",
|
||||
"scan-region-placeholder": "Aggiungi un codice regione (es. us, eu, jp)",
|
||||
"scan-region-priority": "Priorità regioni",
|
||||
"scan-region-priority-desc": "Ordine dei codici regione usati da IGDB e ScreenScraper per le varianti regionali. Vince la prima regione disponibile.",
|
||||
"scan-region-priority-desc": "Ordine dei codici regione usati per le varianti regionali, sia per la versione predefinita mostrata di un gioco sia per gli artwork da IGDB e ScreenScraper. Vince la prima regione disponibile.",
|
||||
"scan-settings": "Impostazioni di scansione",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "候補",
|
||||
"scan-region-placeholder": "リージョンコードを追加(例: us, eu, jp)",
|
||||
"scan-region-priority": "リージョン優先順位",
|
||||
"scan-region-priority-desc": "IGDB と ScreenScraper が地域別バリアントに使用するリージョンコードの順序。最初に利用可能なリージョンが使用されます。",
|
||||
"scan-region-priority-desc": "地域別バリアントに使用するリージョンコードの順序。ゲームのデフォルトバージョンと、IGDB や ScreenScraper から取得するアートワークの両方に適用されます。最初に利用可能なリージョンが使用されます。",
|
||||
"scan-settings": "スキャン設定",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "추천",
|
||||
"scan-region-placeholder": "지역 코드 추가 (예: us, eu, jp)",
|
||||
"scan-region-priority": "지역 우선순위",
|
||||
"scan-region-priority-desc": "IGDB와 ScreenScraper가 지역별 변형에 사용하는 지역 코드의 순서입니다. 사용 가능한 첫 번째 지역이 선택됩니다.",
|
||||
"scan-region-priority-desc": "지역별 변형에 사용하는 지역 코드의 순서입니다. 게임의 기본 버전과 IGDB 및 ScreenScraper에서 가져오는 아트워크에 모두 적용됩니다. 사용 가능한 첫 번째 지역이 선택됩니다.",
|
||||
"scan-settings": "스캔 설정",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Propozycje",
|
||||
"scan-region-placeholder": "Dodaj kod regionu (np. us, eu, jp)",
|
||||
"scan-region-priority": "Priorytet regionów",
|
||||
"scan-region-priority-desc": "Kolejność kodów regionów używanych przez IGDB i ScreenScraper dla wariantów regionalnych. Wygrywa pierwszy dostępny region.",
|
||||
"scan-region-priority-desc": "Kolejność kodów regionów używanych dla wariantów regionalnych, zarówno dla domyślnie wyświetlanej wersji gry, jak i dla grafik z IGDB i ScreenScraper. Wygrywa pierwszy dostępny region.",
|
||||
"scan-settings": "Ustawienia skanowania",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Sugestões",
|
||||
"scan-region-placeholder": "Adicionar um código de região (ex.: us, eu, jp)",
|
||||
"scan-region-priority": "Prioridade de regiões",
|
||||
"scan-region-priority-desc": "Ordem dos códigos de região usados pelo IGDB e ScreenScraper para variantes regionais. A primeira região disponível prevalece.",
|
||||
"scan-region-priority-desc": "Ordem dos códigos de região usados para variantes regionais, tanto a versão de um jogo exibida por padrão quanto as imagens do IGDB e ScreenScraper. A primeira região disponível prevalece.",
|
||||
"scan-settings": "Configurações de escaneamento",
|
||||
"scan-settings-load-error-desc": "Não foi possível carregar as configurações de escaneamento do servidor. A edição está desativada para evitar sobrescrever sua configuração existente.",
|
||||
"scan-settings-load-error-title": "Não foi possível carregar as configurações de escaneamento",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Sugestii",
|
||||
"scan-region-placeholder": "Adaugă un cod de regiune (ex. us, eu, jp)",
|
||||
"scan-region-priority": "Prioritate regiune",
|
||||
"scan-region-priority-desc": "Ordinea codurilor de regiune folosite de IGDB și ScreenScraper pentru variantele regionale. Prima regiune disponibilă câștigă.",
|
||||
"scan-region-priority-desc": "Ordinea codurilor de regiune folosite pentru variantele regionale, atât pentru versiunea unui joc afișată implicit, cât și pentru grafica de la IGDB și ScreenScraper. Prima regiune disponibilă câștigă.",
|
||||
"scan-settings": "Setări de scanare",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Предложения",
|
||||
"scan-region-placeholder": "Добавьте код региона (напр. us, eu, jp)",
|
||||
"scan-region-priority": "Приоритет регионов",
|
||||
"scan-region-priority-desc": "Порядок кодов регионов, используемых IGDB и ScreenScraper для региональных вариантов. Побеждает первый доступный регион.",
|
||||
"scan-region-priority-desc": "Порядок кодов регионов, используемых для региональных вариантов: как версия игры, отображаемая по умолчанию, так и иллюстрации из IGDB и ScreenScraper. Побеждает первый доступный регион.",
|
||||
"scan-settings": "Настройки сканирования",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "Öneriler",
|
||||
"scan-region-placeholder": "Bir bölge kodu ekleyin (ör. us, eu, jp)",
|
||||
"scan-region-priority": "Bölge önceliği",
|
||||
"scan-region-priority-desc": "IGDB ve ScreenScraper tarafından bölgesel varyantlar için kullanılan bölge kodlarının sırası. İlk mevcut bölge kazanır.",
|
||||
"scan-region-priority-desc": "Bölgesel varyantlar için kullanılan bölge kodlarının sırası; hem bir oyunun varsayılan olarak gösterilen sürümü hem de IGDB ve ScreenScraper'dan alınan görseller için geçerlidir. İlk mevcut bölge kazanır.",
|
||||
"scan-settings": "Tarama ayarları",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "推荐",
|
||||
"scan-region-placeholder": "添加地区代码(例如 us, eu, jp)",
|
||||
"scan-region-priority": "地区优先级",
|
||||
"scan-region-priority-desc": "IGDB 和 ScreenScraper 用于地区变体的地区代码顺序。第一个可用的地区将被采用。",
|
||||
"scan-region-priority-desc": "用于地区变体的地区代码顺序,同时适用于游戏默认显示的版本以及从 IGDB 和 ScreenScraper 获取的美术图。第一个可用的地区将被采用。",
|
||||
"scan-settings": "扫描设置",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
@@ -377,7 +377,7 @@
|
||||
"scan-priority-suggestions": "建議",
|
||||
"scan-region-placeholder": "新增地區代碼(例如 us, eu, jp)",
|
||||
"scan-region-priority": "地區優先順序",
|
||||
"scan-region-priority-desc": "IGDB 和 ScreenScraper 用於地區變體的地區代碼順序。第一個可用的地區將被採用。",
|
||||
"scan-region-priority-desc": "用於地區變體的地區代碼順序,同時適用於遊戲預設顯示的版本以及從 IGDB 和 ScreenScraper 取得的美術圖。第一個可用的地區將被採用。",
|
||||
"scan-settings": "掃描設定",
|
||||
"scan-settings-load-error-desc": "The scan settings could not be loaded from the server. Editing is disabled to avoid overwriting your existing configuration.",
|
||||
"scan-settings-load-error-title": "Unable to load scan settings",
|
||||
|
||||
Reference in New Issue
Block a user