import functools import json import re import secrets from collections import Counter, abc from collections.abc import Callable, Iterable, Sequence from datetime import datetime from types import SimpleNamespace from typing import Any, Literal, NamedTuple from redis.exceptions import WatchError from sqlalchemy import ( ColumnExpressionArgument, DateTime, Enum, Integer, SQLColumnExpression, String, Text, and_, case, cast, delete, event, false, func, ) from sqlalchemy import inspect as sa_inspect from sqlalchemy import ( literal, not_, or_, select, true, union, update, ) from sqlalchemy.dialects import mysql from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import ( ColumnProperty, Mapper, QueryableAttribute, Session, joinedload, load_only, noload, selectinload, undefer, ) from sqlalchemy.sql.elements import ClauseList, ColumnElement, UnaryExpression from sqlalchemy.sql.selectable import Select from config.config_manager import config_manager as cm from decorators.database import begin_session from handler.database.rom_filters import ( ROM_FILTER_SPECS, FilterKind, RomFilterParams, RomFiltersDict, RomFilterSpec, ) from handler.redis_handler import sync_cache from logger.logger import log from models.assets import Save, Screenshot, State 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 from models.rom import ( METADATA_SOURCE_FACET_COLUMNS, Rom, RomDeletionTarget, RomFacets, RomFile, RomFileCategory, RomFileDocMeta, RomFileUser, RomIdentityKey, RomMetadata, RomNote, RomUser, RomVisibility, RomVisibilityLabel, SiblingRom, TrackMeta, compute_full_path_hash, compute_name_sort_key, ) from utils import get_version from utils.database import ( LIKE_ESCAPE_CHAR, SORTABLE_NULLABLE_ROM_COLUMNS, epoch_ms_in_ranges, escape_like, release_day_ranges, rom_unset_flag_column, ) from utils.platform_slugs import UniversalPlatformSlug as UPS from utils.sql_dialect import ( Analyze, DialectCase, json_array_contains_all, json_array_contains_any, json_array_contains_value, nulls_last, ) from .base_handler import DBBaseHandler, affected_rows type RomSelect = Select[tuple[Rom]] EJS_SUPPORTED_PLATFORMS = [ UPS._3DO, UPS.AMIGA, UPS.AMIGA_CD, UPS.AMIGA_CD32, UPS.ARCADE, UPS.NEOGEOAES, UPS.NEOGEOMVS, UPS.ATARI2600, UPS.ATARI5200, UPS.ATARI7800, UPS.C_PLUS_4, UPS.CPET, UPS.C64, UPS.C128, UPS.COLECOVISION, UPS.JAGUAR, UPS.LYNX, UPS.DOOM, UPS.DOS, UPS.NEO_GEO_POCKET, UPS.NEO_GEO_POCKET_COLOR, UPS.NES, UPS.FAMICOM, UPS.FDS, UPS.N64, UPS.N64DD, UPS.NDS, UPS.NINTENDO_DSI, UPS.GB, UPS.GBA, UPS.GBC, UPS.PC_FX, UPS.PHILIPS_CD_I, UPS.PSX, UPS.PSP, UPS.SEGACD, UPS.SEGA32, UPS.GENESIS, UPS.SMS, UPS.GAMEGEAR, UPS.SATURN, UPS.SNES, UPS.SFAM, UPS.TG16, UPS.VIC_20, UPS.VIRTUALBOY, UPS.WONDERSWAN, UPS.WONDERSWAN_COLOR, ] RUFFLE_SUPPORTED_PLATFORMS = [ UPS.BROWSER, ] # Used to remove native full-text SQL operators FULLTEXT_BOOLEAN_OPERATORS_REGEX = re.compile(r'[+\-~<>()"@*]') # 3 is the default minimum size in InnoDB FULLTEXT_MIN_TOKEN_SIZE = 3 # A term reaches the hash columns only when it is hex of exactly a digest # length, so an ordinary name search builds no hash SQL at all. Hashes are # stored lowercase, which keeps the lookup an indexed equality. HEX_DIGEST_REGEX = re.compile(r"[0-9a-fA-F]+") # Primary keys offered per round trip when picking a random rom. Sixteen # lands a hit ~99% of the time on a library occupying a quarter of its id # range, which is what deletions leave behind on a long-lived instance. RANDOM_ID_SAMPLE_SIZE = 16 # CRC32 (8), MD5 and RetroAchievements (32), SHA-1 (40). ROM_HASH_COLUMNS_BY_DIGEST_LENGTH: dict[int, tuple[QueryableAttribute[Any], ...]] = { 8: (Rom.crc_hash,), 32: (Rom.md5_hash, Rom.ra_hash), 40: (Rom.sha1_hash,), } # Multi-file games (multi-disc, multi-track) keep their hashes per file, which # is the hash a user has in hand. `chd_sha1_hash` is the uncompressed disc's # digest, the one datfiles publish for a CHD. ROM_FILE_HASH_COLUMNS_BY_DIGEST_LENGTH: dict[ int, tuple[QueryableAttribute[Any], ...] ] = { 8: (RomFile.crc_hash,), 32: (RomFile.md5_hash, RomFile.ra_hash), 40: (RomFile.sha1_hash, RomFile.chd_sha1_hash), } # Every column here is indexed on `roms`, so the sort key needs no join to # the view. ROM_METADATA_ORDER_COLUMNS: dict[str, QueryableAttribute[Any]] = { "first_release_date": Rom.generated_first_release_date, "average_rating": Rom.generated_average_rating, "player_count": Rom.generated_player_count, "hltb_main_story": Rom.generated_hltb_main_story, } # Keyed by the column each flag stands in for. `idx_roms__sort` spans # the flag, the value and the `id` tiebreak, so the ascending sort reads the # whole ordering out of an index. ROM_UNSET_SORT_FLAGS: dict[str, QueryableAttribute[Any]] = { column: getattr(Rom, rom_unset_flag_column(column)) for column in SORTABLE_NULLABLE_ROM_COLUMNS } def _nulls_last_ordering( sort_key: SQLColumnExpression[Any], descending: bool ) -> tuple[ColumnExpressionArgument[bool] | None, ColumnElement[Any]]: """NULL sort keys land last on every engine. Returns: A leading unset term (or None) and the directed sort clause. """ if not descending: # A materialized flag lets the ascending sort read out of an index; a # key without one (rom_user, the view, a grouped aggregate) costs a sort. flag = ROM_UNSET_SORT_FLAGS.get(getattr(sort_key, "key", "")) if flag is not None: return flag, sort_key.asc() return None, nulls_last(sort_key, descending) def _fulltext_match(boolean_query: str) -> mysql.match: """A MariaDB/MySQL FULLTEXT match of the ROM's name and filename.""" return mysql.match( Rom.name.expression, Rom.fs_name.expression, against=boolean_query ).in_boolean_mode() # 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`. _FILTER_VALUES_SELECT = select( RomFacets.genres, RomFacets.franchises, RomFacets.collections, RomFacets.companies, RomFacets.publishers, RomFacets.developers, RomFacets.game_modes, RomFacets.age_ratings, RomFacets.player_count, RomFacets.regions, RomFacets.languages, RomFacets.tags, RomFacets.platform_id, ) # Cached ROM filter values (genres/franchises/etc.) so it doesn't get # recomputed on every call to /api/roms ROM_FILTERS_CACHE_VERSION_KEY = "filter_values:ver" ROM_FILTERS_CACHE_TTL = 60 * 60 * 24 * 7 # 7 days ROM_FILTERS_CACHE_SCHEMA_VERSION = get_version().replace(".", "_") # Columns copied from a scanned (transient) RomFile onto its database row. ROM_FILE_SCANNED_COLUMNS = ( "file_name", "file_path", "file_size_bytes", "last_modified", "crc_hash", "md5_hash", "sha1_hash", "ra_hash", "chd_sha1_hash", "archive_members", "category", ) TRACK_META_SCANNED_COLUMNS = ( "title", "artist", "album", "genre", "year", "track", "disc", "duration_seconds", "has_embedded_cover", "cover_path", ) @functools.cache def _nullable_columns(model: type) -> frozenset[str]: mapper: Mapper[Any] = sa_inspect(model) return frozenset(c.key for c in mapper.columns if c.nullable) def _copy_scanned_columns( source: RomFile | TrackMeta, target: RomFile | TrackMeta, columns: Sequence[str], model: type, keep_when_unset: frozenset[str] = frozenset(), ) -> None: """Copy scanned values onto a row, writing only the columns that changed. A column left unset on the scanned row reads as None, and the model default only applies on insert, so writing it through would break the NOT NULL columns on the update path. `keep_when_unset` extends that protection to nullable columns the scanner doesn't own. """ for column in columns: value = getattr(source, column) if value is None and ( column in keep_when_unset or column not in _nullable_columns(model) ): continue if getattr(target, column) != value: setattr(target, column, value) class SyncedRomFiles(NamedTuple): files: list[RomFile] orphaned_cover_paths: list[str] def _rom_file_content_key(rom_file: RomFile) -> tuple[str, str, str] | None: """Identity of a file by content, or None when it can't be identified. All three hashes are required, mirroring `get_matching_missing_rom`: a partial match is not strong enough to move a row onto a different file. """ if not (rom_file.crc_hash and rom_file.md5_hash and rom_file.sha1_hash): return None return (rom_file.crc_hash, rom_file.md5_hash, rom_file.sha1_hash) def _cache_value_to_str(value: Any) -> str | None: if value is None: return None if isinstance(value, bytes): return value.decode() return str(value) def _cache_version(key: str) -> str: return _cache_value_to_str(sync_cache.get(key)) or "0" def _filter_values_cache_version() -> str: return _cache_version(ROM_FILTERS_CACHE_VERSION_KEY) def _filter_values_cache_keys_key(version: str) -> str: return f"filter_values:keys:v{version}" def _user_sort_version_key(user_id: int) -> str: return f"sidecar:user_ver:{user_id}" def _user_sibling_version_key(user_id: int) -> str: return f"sidecar:user_sib_ver:{user_id}" def user_sort_cache_version(user_id: int) -> str: """Version component for one user's RomUser-sorted sidecar cache keys.""" return _cache_version(_user_sort_version_key(user_id)) def user_sibling_cache_version(user_id: int) -> str: """Version component for one user's grouped sidecar cache keys, moved only by main-sibling picks.""" return _cache_version(_user_sibling_version_key(user_id)) def _sidecar_redis_key(prefix: str, cache_key: str, version: str) -> str: """Every gallery sidecar key shares this shape, so none can omit the schema version.""" return f"{prefix}:{ROM_FILTERS_CACHE_SCHEMA_VERSION}:{cache_key}:v{version}" def _filter_values_redis_key(cache_key: str, version: str) -> str: return _sidecar_redis_key("filter_values", cache_key, version) def _char_index_redis_key(cache_key: str, version: str) -> str: return _sidecar_redis_key("char_index", cache_key, version) def _rom_id_index_redis_key(cache_key: str, version: str) -> str: return _sidecar_redis_key("rom_id_index", cache_key, version) def _store_versioned_cache(redis_key: str, version: str, result: Any) -> None: version_keys_set = _filter_values_cache_keys_key(version) with sync_cache.pipeline() as pipe: try: pipe.watch(ROM_FILTERS_CACHE_VERSION_KEY) current_version = ( _cache_value_to_str(pipe.get(ROM_FILTERS_CACHE_VERSION_KEY)) or "0" ) if current_version != version: pipe.unwatch() else: pipe.multi() pipe.set(redis_key, json.dumps(result), ex=ROM_FILTERS_CACHE_TTL) pipe.sadd(version_keys_set, redis_key) pipe.expire(version_keys_set, ROM_FILTERS_CACHE_TTL) pipe.execute() except WatchError: pass def _create_metadata_id_case( prefix: str, id_column: ColumnElement[Any], platform_id_column: ColumnElement[Any], ) -> ColumnElement[Any]: return case( ( id_column.isnot(None), func.concat( f"{prefix}-", platform_id_column, "-", id_column, ), ), else_=None, ) def _region_rank() -> ColumnElement[Any]: """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[Any]: """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, ) # The RomUser column types whose MIN/MAX matches ORDER BY semantics on every # dialect; enum and boolean keys stay on the representative. _GROUP_SORT_AGGREGATE_TYPES = (DateTime, Integer) class _GallerySortKey(NamedTuple): column: QueryableAttribute[Any] source: Literal["rom", "rom_user", "rom_metadata"] # Nullable keys get the NULLS LAST treatment; an indexed Rom column is # sorted as-is. nullable: bool = False def _mapped_sort_column(model: type, order_by: str) -> QueryableAttribute[Any] | None: """The mapped column `order_by` names on `model`, or None for non-columns.""" attr = getattr(model, order_by, None) if isinstance(attr, QueryableAttribute) and isinstance( attr.property, ColumnProperty ): return attr return None def _rom_user_not_hidden() -> ColumnElement[bool]: """NULL-safe visibility check; a missing rom_user row counts as visible.""" return or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None)) def _zero_unset_folded(column: Any) -> Any: """NULLIF folds the marked zero-as-unset metrics into the NULL bucket.""" if getattr(column, "info", {}).get("zero_is_unset"): return func.nullif(column, 0) return column def _resolve_gallery_sort_key(order_by: str, user_id: int | None) -> _GallerySortKey: """Map a gallery `order_by` name to its sort column and source table.""" rom_column = _mapped_sort_column(Rom, order_by) if user_id and rom_column is None: rom_user_column = _mapped_sort_column(RomUser, order_by) if rom_user_column is not None: return _GallerySortKey(rom_user_column, "rom_user", nullable=True) if order_by in ROM_METADATA_ORDER_COLUMNS: return _GallerySortKey( ROM_METADATA_ORDER_COLUMNS[order_by], "rom", nullable=True ) if rom_column is None: metadata_column = _mapped_sort_column(RomMetadata, order_by) if metadata_column is not None: return _GallerySortKey(metadata_column, "rom_metadata", nullable=True) column = rom_column if rom_column is not None else Rom.name # Use indexed `name_sort_key` to have fast access to names without # articles (the, a, an) and leading digits. The key is derived from # `name` at write time, or holds a custom override when one is set. if column is Rom.name: column = Rom.name_sort_key return _GallerySortKey(column, "rom") def sorts_by_rom_user_column(order_by: str, user_id: int) -> bool: """True when this sort key resolves to a per-user RomUser column.""" return _resolve_gallery_sort_key(order_by, user_id).source == "rom_user" def with_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Rom).options( # Ensure platform is loaded for main ROM objects selectinload(Rom.platform), selectinload(Rom.saves).options( noload(Save.rom), noload(Save.user), ), selectinload(Rom.states).options( noload(State.rom), noload(State.user), ), selectinload(Rom.screenshots).options( noload(Screenshot.rom), ), selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), selectinload(Rom.metadatum).options(noload(RomMetadata.rom)), # Multi-file downloads, 3DS QR codes, and metadata matching selectinload(Rom.files).options( joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), selectinload(RomFile.track_meta), selectinload(RomFile.doc_meta), ), selectinload(Rom.sibling_roms).options( noload(Rom.platform), noload(Rom.metadatum), # Per-sibling is_main_sibling resolution for the # SiblingRomSchema needs each sibling's RomUser for the # request user — the relationship is `lazy="raise"`, so # it has to be eager-loaded here. selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), load_only( Rom.id, Rom.name, Rom.platform_id, Rom.fs_name_no_tags, Rom.fs_name_no_ext, ), ), selectinload(Rom.collections), selectinload(Rom.notes), undefer(Rom.multi_file), undefer(Rom.top_level_file_count), undefer(Rom.has_soundtrack), ) return func(*args, **kwargs) return wrapper def with_simple_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: """Lightweight eager-load for the `SimpleRomSchema` (v2 gallery card). Loads only the relationships `SimpleRomSchema` serializes (rom_users, files, sibling_roms + their rom_users, notes) and the deferred file-count columns, skipping the `saves` / `states` / `screenshots` / `collections` arrays that `with_details` pulls for the detail view. Keeps per-card hydration cheap on low-power hosts. """ @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Rom).options( selectinload(Rom.platform), selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), selectinload(Rom.metadatum).options(noload(RomMetadata.rom)), selectinload(Rom.files).options( joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), selectinload(RomFile.track_meta), selectinload(RomFile.doc_meta), ), selectinload(Rom.sibling_roms).options( noload(Rom.platform), noload(Rom.metadatum), # Per-sibling is_main_sibling resolution needs each sibling's # RomUser (relationship is `lazy="raise"`). selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), load_only( Rom.id, Rom.name, Rom.platform_id, Rom.fs_name_no_tags, Rom.fs_name_no_ext, ), ), selectinload(Rom.notes), undefer(Rom.multi_file), undefer(Rom.top_level_file_count), undefer(Rom.has_soundtrack), ) return func(*args, **kwargs) return wrapper # The fields the recommendation feed scores on. Every writer of `rom_user` # goes through `update_rom_user`, so the cached feed is dropped there rather # than at each of the call sites that move these. RECOMMENDATION_SEED_FIELDS = frozenset( {"rating", "status", "last_played", "now_playing", "hidden"} ) def _queue_user_cache_bumps( session: Session, user_id: int, *, sort_keys: bool = False, siblings: bool = False, feed: bool = False, ) -> None: """Queues per-user cache invalidations for after this transaction commits, so a rollback bumps nothing and a concurrent reader cannot cache pre-commit rows under the new version.""" bumps: dict[int, set[str]] = session.info.setdefault("user_cache_bumps", {}) flags = bumps.setdefault(user_id, set()) flags.update( flag for flag, queued in (("sort", sort_keys), ("sib", siblings), ("feed", feed)) if queued ) if "user_cache_bumps_armed" in session.info: return session.info["user_cache_bumps_armed"] = True def _consume(ending_session: Session) -> dict[int, set[str]]: # Popping the state re-arms the next transaction on a reused session. ending_session.info.pop("user_cache_bumps_armed", None) return ending_session.info.pop("user_cache_bumps", {}) @event.listens_for(session, "after_commit", once=True) def _flush(_session: Session) -> None: # No keys-set bookkeeping: entries under an old version become # unreachable and are reaped by the TTL or the next global bump. for uid, uid_flags in _consume(_session).items(): # The write is already durable, so a cache failure only logs; # the stale entry falls to the TTL. try: if "sort" in uid_flags: sync_cache.incr(_user_sort_version_key(uid)) if "sib" in uid_flags: sync_cache.incr(_user_sibling_version_key(uid)) if "feed" in uid_flags: # Imported here because the recommendation package reads # this module. from handler.recommendation import invalidate_cached_feed invalidate_cached_feed(uid) except Exception: log.exception("Failed to bump user %s cache versions", uid) @event.listens_for(session, "after_rollback", once=True) def _discard(_session: Session) -> None: _consume(_session) class DBRomsHandler(DBBaseHandler): @begin_session @with_details def add_rom( self, rom: Rom, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Rom: rom = session.merge(rom) session.flush() return session.scalars(query.filter_by(id=rom.id).limit(1)).one() @begin_session @with_details def get_rom( self, id: int, *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Rom | None: return session.scalar(query.filter_by(id=id).limit(1)) @begin_session def get_rom_visibility( self, id: int, *, session: Session = None, # type: ignore[assignment] ) -> RomVisibility | None: """The id and platform id a visibility check needs, nothing else.""" row = session.execute( select(Rom.id, Rom.platform_id).where(Rom.id == id) ).one_or_none() if row is None: return None return RomVisibility(id=row.id, platform_id=row.platform_id) @begin_session def get_rom_visibility_label( self, id: int, *, session: Session = None, # type: ignore[assignment] ) -> RomVisibilityLabel | None: """`get_rom_visibility` plus the name pair the file-delete logs need.""" row = session.execute( select(Rom.id, Rom.platform_id, Rom.name, Rom.fs_name).where(Rom.id == id) ).one_or_none() if row is None: return None return RomVisibilityLabel( id=row.id, platform_id=row.platform_id, name=row.name, fs_name=row.fs_name ) @begin_session def get_rom_deletion_target( self, id: int, *, session: Session = None, # type: ignore[assignment] ) -> RomDeletionTarget | None: """The columns the bulk-delete route reads off one rom, and no relations.""" row = session.execute( select( Rom.id, Rom.platform_id, Rom.name, Rom.fs_name, Rom.fs_path, Platform.slug.label("platform_slug"), Platform.name.label("platform_name"), Platform.custom_name.label("platform_custom_name"), ) .join(Platform, Rom.platform_id == Platform.id) .where(Rom.id == id) ).one_or_none() if row is None: return None return RomDeletionTarget( id=row.id, platform_id=row.platform_id, name=row.name, fs_name=row.fs_name, fs_path=row.fs_path, platform_slug=row.platform_slug, platform_name=row.platform_name, platform_custom_name=row.platform_custom_name, ) @begin_session @with_simple_details def get_rom_simple( self, id: int, *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Rom | None: """Get a rom by ID with only the loads `SimpleRomSchema` needs.""" return session.scalar(query.filter_by(id=id).limit(1)) @begin_session @with_details def get_roms_by_ids( self, ids: list[int], *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Get multiple ROMs by their IDs.""" if not ids: return [] return session.scalars(query.filter(Rom.id.in_(ids))).all() @begin_session @with_simple_details def get_roms_simple_by_ids( self, ids: Sequence[int], *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Get multiple ROMs by ID with only the loads `SimpleRomSchema` needs.""" if not ids: return [] return session.scalars(query.filter(Rom.id.in_(ids))).all() def get_files_for_roms( self, rom_ids: list[int], *, session: Session, ) -> dict[int, list[RomFile]]: """Return {rom_id: [RomFile, ...]} for the given rom IDs in a single query. Used by the list endpoint to serialize files without relying on the query's relationship eager-load surviving pagination. """ if not rom_ids: return {} files = session.scalars( select(RomFile) .where(RomFile.rom_id.in_(rom_ids)) .options(selectinload(RomFile.track_meta)) ).all() buckets: dict[int, list[RomFile]] = {rom_id: [] for rom_id in rom_ids} for file in files: buckets[file.rom_id].append(file) return buckets def get_siblings_for_roms( self, rom_ids: list[int], user_id: int, *, session: Session, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, ) -> dict[int, list[tuple[Rom, bool]]]: """Return {rom_id: [(sibling Rom, is_main_sibling), ...]} in a single query. Joins sibling_roms → roms (only the columns SiblingRomSchema needs) and left-joins rom_user for the requesting user, so the per-user `is_main_sibling` flag is resolved without hydrating the wide roms table or its JSON metadata on every page. Siblings hidden from the caller (their platform or the sibling itself) are excluded. """ if not rom_ids: return {} query = ( select( SiblingRom.rom_id, Rom, func.coalesce(RomUser.is_main_sibling, false()).label( "is_main_sibling" ), ) .join(Rom, Rom.id == SiblingRom.sibling_rom_id) .outerjoin( RomUser, and_( RomUser.rom_id == SiblingRom.sibling_rom_id, RomUser.user_id == user_id, ), ) .where(SiblingRom.rom_id.in_(rom_ids)) .options( # Both default to `lazy="joined"`, and `load_only` narrows # columns but not relationships. noload(Rom.platform), noload(Rom.metadatum), load_only( Rom.name, Rom.fs_name_no_tags, Rom.fs_name_no_ext, ), ) ) if hidden_platform_ids: query = query.where(Rom.platform_id.not_in(hidden_platform_ids)) if hidden_rom_ids: query = query.where(Rom.id.not_in(hidden_rom_ids)) rows = session.execute(query).all() # Dedupe by (parent rom, sibling id) so a duplicate join row doesn't # surface the same sibling twice on the wire. seen: dict[int, set[int]] = {rom_id: set() for rom_id in rom_ids} buckets: dict[int, list[tuple[Rom, bool]]] = {rom_id: [] for rom_id in rom_ids} for rom_id, sibling, is_main in rows: if sibling.id in seen[rom_id]: continue seen[rom_id].add(sibling.id) buckets[rom_id].append((sibling, bool(is_main))) return buckets def get_rom_ids_with_notes( self, rom_ids: list[int], user_id: int, *, session: Session, ) -> set[int]: """Return the subset of `rom_ids` carrying a note the caller can see.""" if not rom_ids: return set() return set( session.scalars( select(RomNote.rom_id) .where( RomNote.rom_id.in_(rom_ids), or_(RomNote.is_public, RomNote.user_id == user_id), ) .distinct() ).all() ) def filter_by_platform_id(self, query: RomSelect, platform_id: int) -> RomSelect: return query.filter(Rom.platform_id == platform_id) def _filter_by_platform_ids[S: Select[Any]]( self, query: S, platform_ids: Sequence[int] ) -> S: return query.filter(Rom.platform_id.in_(platform_ids)) def _filter_by_collection_id[S: Select[Any]]( self, query: S, collection_id: int ) -> S: # `collections_roms` is keyed on (collection_id, rom_id), so membership # is an indexed subquery rather than a list of ids fetched into Python. return query.filter( Rom.id.in_( select(CollectionRom.rom_id).where( CollectionRom.collection_id == collection_id ) ) ) def _filter_by_virtual_collection_id[S: Select[Any]]( self, query: S, virtual_collection_id: str ) -> S: from . import db_collection_handler return query.filter( Rom.id.in_( db_collection_handler.get_virtual_collection_rom_ids( virtual_collection_id ) ) ) def _filter_by_smart_collection_id[S: Select[Any]]( self, query: S, session: Session, smart_collection_id: int, user_id: int | None, ) -> S: from . import db_collection_handler smart_collection = db_collection_handler.get_smart_collection( smart_collection_id, session=session ) if not smart_collection: return query.filter(false()) member_ids = self._join_rom_user(select(Rom.id), user_id) return query.filter( Rom.id.in_( db_collection_handler.build_smart_collection_query( query=member_ids, smart_collection=smart_collection, user_id=user_id, session=session, ) ) ) def _join_rom_user[S: Select[Any]](self, query: S, user_id: int | None) -> S: if not user_id: return query return query.outerjoin( RomUser, and_(RomUser.rom_id == Rom.id, RomUser.user_id == user_id) ) @begin_session def get_smart_collection_matches( self, *, smart_collection: SmartCollection, rom_ids: Iterable[int], user_id: int | None, session: Session = None, # type: ignore[assignment] ) -> set[int]: """Which of `rom_ids` currently match the collection's criteria. Restricting the criteria to a few ids keeps this an indexed lookup, so a caller can ask whether one ROM moved without scanning the library. """ from . import db_collection_handler query = self._join_rom_user(select(Rom.id), user_id).filter(Rom.id.in_(rom_ids)) return set( session.scalars( db_collection_handler.build_smart_collection_query( query=query, smart_collection=smart_collection, user_id=user_id, session=session, ) ) ) def _build_fulltext_boolean_query(self, term: str) -> str | None: words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split() if not words or any(len(word) < FULLTEXT_MIN_TOKEN_SIZE for word in words): return None return " ".join(f"+{word}*" for word in words) def _build_fulltext_relevance(self, search_term: str) -> str | None: parts: list[str] = [] for term in search_term.split("|"): words = FULLTEXT_BOOLEAN_OPERATORS_REGEX.sub(" ", term).split() if len(words) > 1: parts.append('"' + " ".join(words) + '"') return " ".join(parts) if parts else None def _build_name_conditions(self, terms: Sequence[str]) -> list[Any]: """One condition per term, matching it against the ROM's name and filename.""" # PostgreSQL's pg_trgm indexes serve the ILIKE; MariaDB and MySQL use # their FULLTEXT index unless a word is too short for it. like_conditions = [ and_( *( or_(Rom.fs_name.ilike(f"%{word}%"), Rom.name.ilike(f"%{word}%")) for word in term.split() ) ) for term in terms ] boolean_queries = [ query for term in terms if (query := self._build_fulltext_boolean_query(term)) is not None ] if len(boolean_queries) < len(terms): return like_conditions return [ DialectCase(postgresql=like, mysql=_fulltext_match(boolean_query)) for boolean_query, like in zip( boolean_queries, like_conditions, strict=True ) ] def _build_hash_selects(self, terms: Iterable[str]) -> list[Select[tuple[int]]]: """Id-yielding selects for terms shaped like a hash digest. A ROM's own hashes and its files' are queried separately so each side keeps its own index. Returns nothing when no term looks like a digest, which is the case for every ordinary name search. """ rom_predicates: list[ColumnElement[bool]] = [] file_predicates: list[ColumnElement[bool]] = [] for term in terms: rom_columns = ROM_HASH_COLUMNS_BY_DIGEST_LENGTH.get(len(term)) if rom_columns is None or not HEX_DIGEST_REGEX.fullmatch(term): continue digest = term.lower() rom_predicates.extend(column == digest for column in rom_columns) file_predicates.extend( column == digest for column in ROM_FILE_HASH_COLUMNS_BY_DIGEST_LENGTH[len(term)] ) if not rom_predicates: return [] return [ select(Rom.id).where(or_(*rom_predicates)), select(RomFile.rom_id.label("id")).where(or_(*file_predicates)), ] 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] if not terms: return query name_conditions = self._build_name_conditions(terms) hash_selects = self._build_hash_selects(terms) if not hash_selects: return query.filter(or_(*name_conditions)) # OR-ing the hash columns onto the name conditions would cost the # full-text index its only chance to drive the query, scanning `roms` # end to end. Resolving each side through its own index and unioning # the ids searches both without giving up either index. matches = union( select(Rom.id).where(or_(*name_conditions)), *hash_selects ).subquery() return query.filter(Rom.id.in_(select(matches.c.id))) def _filter_by_matched[S: Select[Any]](self, query: S, value: bool) -> S: """Filter based on whether the rom is matched to a metadata provider. Args: value: True for matched ROMs, False for unmatched ROMs """ predicate = or_( Rom.igdb_id.isnot(None), Rom.moby_id.isnot(None), Rom.ss_id.isnot(None), Rom.ra_id.isnot(None), Rom.launchbox_id.isnot(None), Rom.hasheous_id.isnot(None), Rom.tgdb_id.isnot(None), Rom.flashpoint_id.isnot(None), ) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_favorite[S: Select[Any]]( self, query: S, value: bool, user_id: int | None ) -> S: """Filter based on whether the rom is in the user's favorites collection.""" if not user_id: return query # An empty (or missing) favorites collection needs no special case: the # subquery yields no rows, so IN matches nothing and NOT IN matches all. favorites = ( select(CollectionRom.rom_id) .join(Collection, Collection.id == CollectionRom.collection_id) .where(Collection.is_favorite, Collection.user_id == user_id) ) predicate = Rom.id.in_(favorites) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_duplicate[S: Select[Any]](self, query: S, value: bool) -> S: """Filter based on whether the rom has duplicates.""" predicate = Rom.sibling_roms.any() if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_playable[S: Select[Any]](self, query: S, value: bool) -> S: """Filter based on whether the rom is playable on supported platforms.""" predicate = or_( Platform.slug.in_(EJS_SUPPORTED_PLATFORMS), Platform.slug.in_(RUFFLE_SUPPORTED_PLATFORMS), ) if not value: predicate = not_(predicate) return query.join(Platform).filter(predicate) def _filter_by_last_played[S: Select[Any]]( self, query: S, value: bool, user_id: int | None = None ) -> S: """Filter based on whether the rom has a last played value for the user.""" if not user_id: return query has_last_played = ( RomUser.last_played.is_(None) if not value else RomUser.last_played.isnot(None) ) return query.filter(has_last_played) def _filter_by_has_ra[S: Select[Any]](self, query: S, value: bool) -> S: predicate = Rom.ra_id.isnot(None) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_has_saves[S: Select[Any]]( self, query: S, value: bool, user_id: int | None = None ) -> S: """Filter based on whether the rom has saves visible to the current user: their own plus other users' public (community) saves.""" if not user_id: return query predicate = Rom.saves.any(or_(Save.user_id == user_id, Save.is_public)) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_has_states[S: Select[Any]]( self, query: S, value: bool, user_id: int | None = None ) -> S: """Filter based on whether the rom has save states visible to the current user: their own plus other users' public (community) states.""" if not user_id: return query predicate = Rom.states.any(or_(State.user_id == user_id, State.is_public)) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_missing_from_fs[S: Select[Any]](self, query: S, value: bool) -> S: # The column is NOT NULL, so equality matches the same rows as the # `IS [NOT] FALSE` form. MariaDB only treats the equality as indexable # though, and this filter backs the Missing tab's whole-library scan. if not value: return query.filter(Rom.missing_from_fs == false()) # Physical games are never "missing"; exclude them so a stray flag can # never make one eligible for the missing-roms cleanup that hard-deletes. return query.filter( and_(Rom.missing_from_fs == true(), Rom.is_physical.is_(False)) ) def _filter_by_verified[S: Select[Any]](self, query: S, value: bool) -> S: keys_to_check = [ "tosec_match", "mame_arcade_match", "mame_mess_match", "nointro_match", "redump_match", "mame_redump_match", "whdload_match", "ra_match", "fbneo_match", "puredos_match", ] # A missing key or a JSON null can extract as NULL, which would poison the # OR and its negation; coalesce folds it to false on every engine. predicate = or_( *( func.coalesce(Rom.hasheous_metadata[key].as_boolean(), false()) for key in keys_to_check ), func.coalesce(Rom.ra_metadata["hash_match"].as_boolean(), false()), ) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_status[S: Select[Any]]( self, query: S, *, values: Sequence[str], match_all: bool = False, match_none: bool = False, ) -> S: if not values: return query status_filters: list[ColumnElement[bool]] = [] for selected_status in values: if selected_status == "now_playing": status_filters.append(RomUser.now_playing.is_(True)) elif selected_status == "backlogged": status_filters.append(RomUser.backlogged.is_(True)) elif selected_status == "hidden": status_filters.append(RomUser.hidden.is_(True)) else: status_filters.append(RomUser.status == selected_status) comb = and_ if match_all else or_ condition = comb(*status_filters) # Apply negation if match_none, otherwise apply condition query = query.filter(~condition) if match_none else query.filter(condition) # Don't apply the hidden filter is hidden is set if "hidden" in values: return query return query.filter(_rom_user_not_hidden()) def _apply_filter_spec[S: Select[Any]]( self, query: S, spec: RomFilterSpec, *, values: Sequence[str], match_all: bool = False, match_none: bool = False, ) -> S: """Narrow `query` to the roms matching `values` under `spec`.""" column = spec.column if column is None: # PROVIDER_IDS is the only kind without a single column: each # selected provider names its own id column on the mirror. return self._filter_by_metadata_providers( query, values=values, match_all=match_all, match_none=match_none, ) if spec.kind == FilterKind.SCALAR_IN: # A scalar column can't hold every selected value, so "all" has no # meaning here and matches "any". condition = column.in_(values) else: op = json_array_contains_all if match_all else json_array_contains_any condition = op(column, values) return query.filter(~condition) if match_none else query.filter(condition) def _filter_by_metadata_providers[S: Select[Any]]( self, query: S, *, values: Sequence[str], match_all: bool = False, match_none: bool = False, ) -> S: """Filter on which metadata providers a ROM matched, keyed off each provider's id column on the facets mirror. - "any": matched at least one of the selected providers. - "all": matched every selected provider. - "none": matched none of the selected providers. """ columns = [ METADATA_SOURCE_FACET_COLUMNS[value] for value in values if value in METADATA_SOURCE_FACET_COLUMNS ] # Unknown slugs (stale bookmark / hand-edited URL) leave nothing to # filter on; treat that as a no-op rather than an empty result set. if not columns: return query predicates = [column.isnot(None) for column in columns] if match_none: return query.filter(not_(or_(*predicates))) if match_all: return query.filter(and_(*predicates)) return query.filter(or_(*predicates)) @begin_session def filter_roms[S: Select[Any]]( self, query: S, filters: RomFilterParams | None = None, *, # The grouped dedup aggregates the active sort key over each group; # get_roms_query callers pass the key they resolved for the query. sort_key: _GallerySortKey | None = None, order_by: str = "", order_dir: str = "asc", user_id: int | None = None, updated_after: datetime | None = None, released_days: Sequence[tuple[int, int]] | None = None, released_before_year: int | None = None, include_file_stats: bool = False, include_files: bool = False, include_related: bool = True, include_siblings: bool = True, include_notes: bool = True, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, session: Session = None, # type: ignore[assignment] ) -> S: from handler.scan_handler import MetadataSource filters = filters or RomFilterParams() order_dir = order_dir.lower() # Callers that select bare columns (a membership subquery) pass # include_related=False: loader options can't apply without an entity. if include_related: query = query.options( # Ensure platform is loaded for main ROM objects selectinload(Rom.platform), # Display properties for the current user (last_played) selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), # Sort table by metadata (first_release_date) selectinload(Rom.metadatum).options(noload(RomMetadata.rom)), ) # Show sibling rom badges on cards if include_siblings: query = query.options( selectinload(Rom.sibling_roms).options( noload(Rom.platform), noload(Rom.metadatum), # is_main_sibling needs each sibling's RomUser. selectinload(Rom.rom_users).options( noload(RomUser.rom), noload(RomUser.user) ), ) ) # Notes indicator on cards if include_notes: query = query.options(selectinload(Rom.notes)) # Only load files (and the RomFile.rom backref needed by `is_top_level` / # `file_name_for_download`) when the caller iterates them — e.g. the # feed endpoints. The gallery/list and filter-value paths serialize # SimpleRomSchema without files, so they skip this entirely. if include_files: query = query.options( selectinload(Rom.files).options( joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name) ) ) # Correlated subqueries and only undefer when the caller serializes the # gallery-card flags. Feeds and filter-value lookups don't need them. if include_file_stats: query = query.options( undefer(Rom.multi_file), undefer(Rom.top_level_file_count), undefer(Rom.has_soundtrack), ) # Handle platform filtering - platform filtering always uses OR logic since ROMs belong to only one platform if filters.platform_ids: query = self._filter_by_platform_ids(query, filters.platform_ids) if filters.collection_id: query = self._filter_by_collection_id(query, filters.collection_id) if filters.virtual_collection_id: query = self._filter_by_virtual_collection_id( query, filters.virtual_collection_id ) if filters.smart_collection_id: query = self._filter_by_smart_collection_id( query, session, filters.smart_collection_id, user_id ) if filters.search_term: query = self._filter_by_search_term(query, filters.search_term) if filters.matched is not None: query = self._filter_by_matched(query, value=filters.matched) if filters.favorite is not None: query = self._filter_by_favorite( query, value=filters.favorite, user_id=user_id ) if filters.duplicate is not None: query = self._filter_by_duplicate(query, value=filters.duplicate) if filters.last_played is not None: query = self._filter_by_last_played( query, value=filters.last_played, user_id=user_id ) if filters.playable is not None: query = self._filter_by_playable(query, value=filters.playable) if filters.has_ra is not None: query = self._filter_by_has_ra(query, value=filters.has_ra) if filters.has_saves is not None: query = self._filter_by_has_saves( query, value=filters.has_saves, user_id=user_id ) if filters.has_states is not None: query = self._filter_by_has_states( query, value=filters.has_states, user_id=user_id ) if filters.missing is not None: query = self._filter_by_missing_from_fs(query, value=filters.missing) if filters.physical is not None: query = query.filter(Rom.is_physical.is_(filters.physical)) if filters.verified is not None: query = self._filter_by_verified(query, value=filters.verified) if filters.has_soundtrack is not None: query = ( query.filter(Rom.has_soundtrack) if filters.has_soundtrack else query.filter(~Rom.has_soundtrack) ) if updated_after: query = query.filter(Rom.updated_at > updated_after) if released_days: query = query.filter( epoch_ms_in_ranges( Rom.generated_first_release_date, release_day_ranges(released_days, before_year=released_before_year), ) ) # A NULL length is excluded by either comparison, so a range filter # only ever returns roms HowLongToBeat actually has a time for. if filters.hltb_main_story_min is not None: query = query.filter( Rom.generated_hltb_main_story >= filters.hltb_main_story_min ) if filters.hltb_main_story_max is not None: query = query.filter( Rom.generated_hltb_main_story <= filters.hltb_main_story_max ) # One join serves every filter below. It has to land before them: the # dedup subquery is derived from `query` and would inherit them without # it. if any(filters.selected(spec.name)[0] for spec in ROM_FILTER_SPECS): query = query.outerjoin(RomFacets, RomFacets.rom_id == Rom.id) # Applied before the `group_by_meta_id` window below, so a title whose # match sits on a non-primary version still reaches the gallery. for spec in ROM_FILTER_SPECS: values, logic = filters.selected(spec.name) if values: query = self._apply_filter_spec( query, spec, values=values, match_all=(logic == "all"), match_none=(logic == "none"), ) # Admin-driven visibility (opt-out): hide platforms/roms an admin has # hidden from this user/group. Applied before the grouped dedup window # so a permission-hidden sibling can neither represent a group nor # drive its sort key. Empty sets (e.g. admins) skip filtering entirely. if hidden_platform_ids: query = query.filter(Rom.platform_id.not_in(hidden_platform_ids)) if hidden_rom_ids: query = query.filter(Rom.id.not_in(hidden_rom_ids)) # BEWARE YE WHO ENTERS HERE 💀 if filters.group_by_meta_id: # Convert NULL is_main_sibling to 0 (false) so it sorts after true values is_main_sibling_order = ( func.coalesce(cast(RomUser.is_main_sibling, Integer), 0).desc() if user_id else literal(1) ) if sort_key is None: sort_key = _resolve_gallery_sort_key(order_by, user_id) # A group sorts by its best sibling's key; only rom_user keys # aggregate, since a roms-side key would leave the covering index. aggregates_sort_key = sort_key.source == "rom_user" and isinstance( sort_key.column.type, _GROUP_SORT_AGGREGATE_TYPES ) # 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. base_subquery = ( query.order_by(None) .with_only_columns( 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, Rom.moby_id, Rom.ra_id, Rom.hasheous_id, Rom.launchbox_id, Rom.tgdb_id, Rom.flashpoint_id, Rom.steam_id, ) .subquery() ) partition_key = func.coalesce( _create_metadata_id_case( MetadataSource.IGDB, base_subquery.c.igdb_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.SS, base_subquery.c.ss_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.MOBY, base_subquery.c.moby_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.RA, base_subquery.c.ra_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.HASHEOUS, base_subquery.c.hasheous_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.LAUNCHBOX, base_subquery.c.launchbox_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.TGDB, base_subquery.c.tgdb_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.FLASHPOINT, base_subquery.c.flashpoint_id, base_subquery.c.platform_id, ), _create_metadata_id_case( MetadataSource.STEAM, base_subquery.c.steam_id, base_subquery.c.platform_id, ), _create_metadata_id_case( "romm", base_subquery.c.id, base_subquery.c.platform_id, ), ) # Only id, the row number and the group sort key flow downstream; # wider columns here spill the window's temp-table sort to disk. window_order = [ is_main_sibling_order, base_subquery.c.prerelease_rank.asc(), base_subquery.c.region_rank.asc(), base_subquery.c.fs_name_no_ext.asc(), ] window_columns: list[ColumnElement[Any]] = [ func.row_number() .over(partition_by=partition_key, order_by=window_order) .label("row_num"), ] if aggregates_sort_key: # MIN/MAX skip NULL siblings, and a hidden sibling's key is # masked to NULL so it cannot drive a group it is absent from. visible_sort_key = case( (_rom_user_not_hidden(), _zero_unset_folded(sort_key.column)) ) group_aggregate = func.max if order_dir == "desc" else func.min window_columns.append( # Sharing row_number's window spec keeps the derived table # on one sort pass; the frame still spans the partition. group_aggregate(visible_sort_key) .over( partition_by=partition_key, order_by=window_order, rows=(None, None), ) .label("group_sort_value") ) group_subquery = ( select(base_subquery.c.id) .select_from(base_subquery) .outerjoin( RomUser, and_( base_subquery.c.id == RomUser.rom_id, RomUser.user_id == user_id ), ) .add_columns(*window_columns) .subquery() ) if aggregates_sort_key: # Joining the primary rows carries the group's key out for the # ORDER BY; ids are partition-unique, so the join cannot fan out. dedup_subquery = ( select(group_subquery.c.id, group_subquery.c.group_sort_value) .where(group_subquery.c.row_num == 1) .subquery() ) # The null-safe match keeps this join outer; made inner, MariaDB # drives from the derived table and probes wide roms rows per group. query = query.outerjoin( dedup_subquery, Rom.id == dedup_subquery.c.id ).filter(dedup_subquery.c.id.is_not_distinct_from(Rom.id)) query = query.order_by(None).order_by( *self._gallery_order_clauses( order_by=order_by, order_dir=order_dir, sort_column=dedup_subquery.c.group_sort_value, nulls_last=sort_key.nullable, search_term=filters.search_term, ) ) else: # Add a filter to the original query to only include the primary ROM from each group query = query.filter( Rom.id.in_( select(group_subquery.c.id).where(group_subquery.c.row_num == 1) ) ) # The RomUser table is already joined if user_id is set if filters.statuses and user_id: query = self._filter_by_status( query, values=filters.statuses, match_all=(filters.statuses_logic == "all"), match_none=(filters.statuses_logic == "none"), ) elif user_id: query = query.filter(_rom_user_not_hidden()) return query def _gallery_order_clauses( self, *, order_by: str, order_dir: str, sort_column: Any, nulls_last: bool, search_term: str | None, ) -> list[Any]: descending = order_dir == "desc" if nulls_last: nulls_last_clause, order_clause = _nulls_last_ordering( sort_column, descending ) else: nulls_last_clause = None order_clause = sort_column.desc() if descending else sort_column.asc() # Ties are common on every sort key here and the gallery pages by # offset, so without a unique final key a rom can repeat in one window # and vanish from the next. The id follows the sort direction because a # mixed-direction pair forces a filesort. tiebreaker = Rom.id.desc() if descending else Rom.id.asc() relevance = self._build_fulltext_relevance(search_term) if search_term else None if relevance: relevance_clause = _fulltext_match(relevance).desc() # Only the FULLTEXT engines rank: relevance breaks an explicit sort's # ties, or leads (with name breaking its ties) when no sort is picked. order_clause = DialectCase( postgresql=order_clause, mysql=( ClauseList(order_clause, relevance_clause) if order_by else ClauseList(relevance_clause, order_clause) ), ) return [ clause for clause in (nulls_last_clause, order_clause, tiebreaker) if clause is not None ] def get_roms_query( self, *, order_by: str = "", order_dir: str = "asc", search_term: str | None = None, user_id: int | None = None, ) -> tuple[RomSelect, _GallerySortKey]: query = self._join_rom_user(select(Rom), user_id) order_dir = order_dir.lower() sort_key = _resolve_gallery_sort_key(order_by, user_id) if sort_key.source == "rom_metadata": query = query.outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id) order_clauses = self._gallery_order_clauses( order_by=order_by, order_dir=order_dir, sort_column=_zero_unset_folded(sort_key.column), nulls_last=sort_key.nullable, search_term=search_term, ) return query.order_by(*order_clauses), sort_key def _scoped_roms_query( self, *, session: Session, include_related: bool = True, **kwargs: Any, ) -> RomSelect: """The filtered, ordered query `get_roms_scalar` and `get_rom_ids` both run.""" order_by = kwargs.get("order_by", "") order_dir = kwargs.get("order_dir", "asc") user_id = kwargs.get("user_id", None) query, sort_key = self.get_roms_query( order_by=order_by, order_dir=order_dir, search_term=kwargs.get("search_term", None), user_id=user_id, ) return self.filter_roms( query=query, # Extra keys (ordering, loading flags) are not filters; ignored here. filters=RomFilterParams.model_validate(kwargs), sort_key=sort_key, order_by=order_by, order_dir=order_dir, user_id=user_id, released_days=kwargs.get("released_days", None), released_before_year=kwargs.get("released_before_year", None), # File loaders need the entity too, so they ride the same flag. include_files=include_related and kwargs.get("include_files", False), include_related=include_related, hidden_platform_ids=kwargs.get("hidden_platform_ids", None), hidden_rom_ids=kwargs.get("hidden_rom_ids", None), session=session, ) @begin_session def get_roms_scalar( self, *, session: Session = None, # type: ignore[assignment] **kwargs: Any, ) -> Sequence[Rom]: query = self._scoped_roms_query(session=session, **kwargs) return session.scalars(query).all() @begin_session def get_rom_ids( self, *, session: Session = None, # type: ignore[assignment] **kwargs: Any, ) -> list[int]: """Every matching rom id, in query order.""" query = self._scoped_roms_query( session=session, include_related=False, **kwargs ) return list(session.scalars(query.with_only_columns(Rom.id)).all()) @begin_session def get_hidden_rom_ids_among( self, rom_ids: Sequence[int], hidden_platform_ids: abc.Collection[int] | None, hidden_rom_ids: abc.Collection[int] | None, session: Session = None, # type: ignore[assignment] ) -> set[int]: """Of `rom_ids`, the subset hidden from the caller (own hide or platform).""" candidates = set(rom_ids) hide: set[int] = candidates & set(hidden_rom_ids or []) if hidden_platform_ids and candidates: rows = session.scalars( select(Rom.id).where( Rom.id.in_(candidates), Rom.platform_id.in_(hidden_platform_ids), ) ).all() hide.update(rows) return hide @begin_session def with_char_index( self, query: RomSelect, order_by_attr: Any, *, cache_key: str | None = None, order_dir: str = "asc", session: Session = None, # type: ignore[assignment] ) -> list[tuple[str, int]]: # Letter offsets only index a lexically ordered result. `Enum` subclasses # `String`, but the database orders native enums by declaration order. column_type = order_by_attr.type is_lexical = isinstance(column_type, (String, Text)) and not isinstance( column_type, Enum ) if not is_lexical: return [] redis_key: str | None = None version: str | None = None if cache_key: version = _filter_values_cache_version() redis_key = _char_index_redis_key(cache_key, version) cached = sync_cache.get(redis_key) if cached is not None: return json.loads(cached) # Drop any ordering carried over from the main query (e.g. search relevance). # This builds its own positional ordering below. query = query.order_by(None) # The alpha-strip only needs each first letter's starting offset, not a # positional number for every row. Counting rows per letter and # 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) counts = ( query.with_only_columns(letter.label("letter"), func.count().label("count")) .group_by(letter) .order_by(letter.desc() if descending else letter.asc()) ) # Walk the letters in the same direction the client paginates over, so # each letter's offset is the count of rows that sort before it. result: list[tuple[str, int]] = [] offset = 0 for value, count in session.execute(counts).all(): if value is not None: result.append((value, offset)) offset += count result.sort(key=lambda entry: entry[0]) if redis_key is not None and version is not None: _store_versioned_cache(redis_key, version, result) return result @begin_session def get_rom_id_index( self, query: RomSelect, *, cache_key: str | None = None, session: Session = None, # type: ignore[assignment] ) -> list[int]: """Return every matching rom id in query order. The list backs the gallery's virtual scroll, so it spans the whole result set (not a page) and is recomputed on every request. Building it runs the sibling-dedup window over the full library, so the unscoped case is memoised under the same versioned cache as the other gallery sidecars. """ redis_key: str | None = None version: str | None = None if cache_key: version = _filter_values_cache_version() redis_key = _rom_id_index_redis_key(cache_key, version) cached = sync_cache.get(redis_key) if cached is not None: return json.loads(cached) ids = list(session.scalars(query.with_only_columns(Rom.id)).all()) if redis_key is not None and version is not None: _store_versioned_cache(redis_key, version, ids) return ids @begin_session def get_rom_count( self, query: RomSelect, *, session: Session = None, # type: ignore[assignment] ) -> int: """Count matching roms without materialising their ids. For callers that need a page and its total but not the full ordered id list, so the database can serve the page from the sort index instead of scanning the whole library. """ return ( session.scalar( select(func.count()).select_from(query.order_by(None).subquery()) ) or 0 ) @begin_session def get_random_rom_id( self, query: RomSelect, *, session: Session = None, # type: ignore[assignment] ) -> int | None: """Pick one rom id at random, uniformly, from a filtered query. Two mechanisms, both uniform. First a batch of random primary keys is offered to the query: every id in the table is equally likely to be offered, so any hit is an unbiased pick, and the whole batch costs one index lookup per candidate no matter how large the library is. A batch misses when the query matches too little of the id space (a scoped gallery, an id range left full of gaps by deletions). It then falls back to counting the set and taking the row at a random position in it. That reads no rows, only index entries, since the statement selects nothing but the id. """ id_query = query.order_by(None).with_only_columns(Rom.id) # Bounds come from the table rather than the filtered set: they only # need to cover it, and MIN/MAX over an untouched primary key are two # index seeks, where the same pair over a joined and filtered set is a # scan of it. lowest, highest = session.execute( select(func.min(Rom.id), func.max(Rom.id)) ).one() if lowest is None or highest is None: return None span = highest - lowest + 1 candidates = { lowest + secrets.randbelow(span) for _ in range(RANDOM_ID_SAMPLE_SIZE) } hits = session.scalars(id_query.where(Rom.id.in_(candidates))).all() if hits: return secrets.choice(hits) total = self.get_rom_count(query=query, session=session) if total == 0: return None return session.scalar(id_query.limit(1).offset(secrets.randbelow(total))) @begin_session def get_roms_by_fs_name( self, platform_id: int, fs_names: Iterable[str], with_files: bool = False, session: Session = None, # type: ignore[assignment] ) -> dict[str, Rom]: """Retrieve a dictionary of roms keyed by their full path (fs_path/fs_name). Filters by file name for an indexed lookup, but keys the result on the full path so identically-named files in different folders (custom library structures) remain distinct. Eager-loads only `platform` (used downstream by the scan loop via `rom.platform_slug` / `rom.platform.fs_slug`). This deliberately avoids `with_details`, whose full relationship eager-load is wasted work for the scan-skip decision on large platforms. Scans that reconcile files opt into `with_files` to load them once per batch instead of once per rom. """ query = select(Rom).options(selectinload(Rom.platform)) if with_files: query = query.options( selectinload(Rom.files).options( joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), selectinload(RomFile.track_meta), ) ) roms = ( session.scalars( query.where( and_( Rom.platform_id == platform_id, Rom.fs_name.in_(fs_names), ) ) ) .unique() .all() ) return {rom.full_path: rom for rom in roms} @begin_session def get_roms_by_fs_names_no_ext( self, fs_names_no_ext: Iterable[str], session: Session = None, # type: ignore[assignment] ) -> list[Rom]: """ROMs on any platform with one of these extensionless file names.""" names = list(dict.fromkeys(fs_names_no_ext)) roms: list[Rom] = [] for i in range(0, len(names), 1000): roms += session.scalars( select(Rom) .options(selectinload(Rom.platform)) .where(Rom.fs_name_no_ext.in_(names[i : i + 1000])) ).all() # Id order keeps an ambiguous name resolving the same way on every sync. return sorted(roms, key=lambda rom: rom.id) @begin_session def update_rom( self, id: int, data: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> Rom: if "name" in data and "name_sort_key" not in data: # 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() 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 "fs_name" in data: parts = compute_file_name_parts(data["fs_name"]) data = { **data, "fs_name_no_tags": parts.no_tags, "fs_name_no_ext": parts.no_ext, "fs_extension": parts.extension, } 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() data = { **data, "full_path_hash": compute_full_path_hash( data.get("fs_path", stored.fs_path), data.get("fs_name", stored.fs_name), ), } session.execute( update(Rom) .where(Rom.id == id) .values(**data) .execution_options(synchronize_session="evaluate") ) return session.scalars(select(Rom).filter_by(id=id)).one() @begin_session def convert_rom_to_folder( self, id: int, folder: str, file_path: str, session: Session = None, # type: ignore[assignment] ) -> None: parts = compute_file_name_parts(folder) stored = session.scalars(select(Rom).filter_by(id=id)).one() session.execute( update(Rom) .where(Rom.id == id) .values( fs_name=folder, fs_name_no_tags=parts.no_tags, fs_name_no_ext=parts.no_ext, fs_extension=parts.extension, full_path_hash=compute_full_path_hash(stored.fs_path, folder), ) ) session.execute( update(RomFile).where(RomFile.rom_id == id).values(file_path=file_path) ) @begin_session def delete_rom( self, id: int, session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Rom) .where(Rom.id == id) .execution_options(synchronize_session="evaluate") ) @begin_session def get_missing_rom_ids( self, platform_id: int, session: Session = None, # type: ignore[assignment] ) -> set[int]: """Return the ids of a platform's ROMs currently flagged missing.""" return set( session.scalars( select(Rom.id).where( and_( Rom.platform_id == platform_id, Rom.missing_from_fs.is_(True), ) ) ).all() ) @begin_session def bulk_mark_present( self, platform_id: int, rom_ids: list[int], session: Session = None, # type: ignore[assignment] ) -> None: """Bulk set missing_from_fs=False for a list of ROM IDs. Only rows that actually flip are written, so a re-scan of an unchanged platform issues no updates and leaves `updated_at` untouched, keeping it a usable incremental signal. """ if not rom_ids: return for i in range(0, len(rom_ids), 1000): chunk = rom_ids[i : i + 1000] session.execute( update(Rom) .where( and_( Rom.platform_id == platform_id, Rom.id.in_(chunk), Rom.missing_from_fs.is_(True), ) ) .values(missing_from_fs=False) .execution_options(synchronize_session="evaluate") ) @begin_session def mark_missing_roms( self, platform_id: int, fs_roms_to_keep: list[str], session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Sync `missing_from_fs` for a platform against the keep-list. The keep-list holds rom full paths (fs_path/fs_name) so that identically-named files in different folders are tracked independently under a custom library structure. Reads the rows once and writes only those whose state actually changes, so a re-scan of an unchanged platform issues no updates. """ keep_set = set(fs_roms_to_keep) # Physical games have no file on disk, so they must never be flagged missing. rows = session.execute( select(Rom.id, Rom.fs_path, Rom.fs_name, Rom.missing_from_fs).where( and_( Rom.platform_id == platform_id, Rom.is_physical.is_(False), ) ) ).all() flips: dict[bool, list[int]] = {True: [], False: []} for rom_id, fs_path, fs_name, was_missing in rows: is_missing = f"{fs_path}/{fs_name}" not in keep_set if is_missing != was_missing: flips[is_missing].append(rom_id) for desired, ids in flips.items(): for i in range(0, len(ids), 1000): session.execute( update(Rom) .where(Rom.id.in_(ids[i : i + 1000])) .values(missing_from_fs=desired) .execution_options(synchronize_session="evaluate") ) return ( session.scalars( # The returned instances are detached, so `fs_path` is loaded up # front for callers reading `rom.full_path`. select(Rom) .options(load_only(Rom.id, Rom.fs_name, Rom.fs_path)) .where( and_( Rom.platform_id == platform_id, Rom.missing_from_fs.is_(True), Rom.is_physical.is_(False), ) ) .order_by(Rom.fs_name.asc()) ) .unique() .all() ) @begin_session def add_rom_user( self, rom_id: int, user_id: int, session: Session = None, # type: ignore[assignment] ) -> RomUser: rom_user = session.merge(RomUser(rom_id=rom_id, user_id=user_id)) session.flush() # A fresh row's zero defaults replace NULL sort keys, which moves # this user's RomUser-sorted order. _queue_user_cache_bumps(session, user_id, sort_keys=True) return rom_user @begin_session def get_rom_user( self, rom_id: int, user_id: int, session: Session = None, # type: ignore[assignment] ) -> RomUser | None: return session.scalar( select(RomUser).filter_by(rom_id=rom_id, user_id=user_id).limit(1) ) @begin_session def get_rom_user_by_id( self, id: int, session: Session = None, # type: ignore[assignment] ) -> RomUser | None: return session.scalar(select(RomUser).filter_by(id=id).limit(1)) @begin_session def update_rom_user( self, id: int, data: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> RomUser | None: session.execute( update(RomUser) .where(RomUser.id == id) .values(**data) .execution_options(synchronize_session="evaluate") ) rom_user = session.scalars(select(RomUser).filter_by(id=id)).one_or_none() if not rom_user: return None # Other RomUser columns can back a sort (hidden bumps the global version, # pinned_media sorts nothing); main-sibling picks move grouped sets. _queue_user_cache_bumps( session, rom_user.user_id, sort_keys=bool(data.keys() - {"hidden", "pinned_media"}), siblings="is_main_sibling" in data, feed=bool(RECOMMENDATION_SEED_FIELDS & data.keys()), ) if not data.get("is_main_sibling", False): return rom_user rom = self.get_rom(rom_user.rom_id) if not rom: return rom_user session.execute( update(RomUser) .where( and_( RomUser.rom_id.in_(r.id for r in rom.sibling_roms), RomUser.user_id == rom_user.user_id, ) ) .values(is_main_sibling=False) ) return rom_user @begin_session def add_rom_file( self, rom_file: RomFile, session: Session = None, # type: ignore[assignment] ) -> RomFile: merged = session.merge(rom_file) session.flush() return merged def _apply_scanned_rom_file( self, row: RomFile, scanned: RomFile, rom_id: int, ) -> str | None: """Copy a scanned file onto its row, with its track metadata. Returns the cover path this update orphaned, if any. """ _copy_scanned_columns(scanned, row, ROM_FILE_SCANNED_COLUMNS, RomFile) if row.missing_from_fs: row.missing_from_fs = False scanned_meta = scanned.track_meta if scanned_meta is None: orphaned = row.track_meta.cover_path if row.track_meta else None row.track_meta = None return orphaned meta = row.track_meta if meta is None: meta = TrackMeta(rom_id=rom_id) row.track_meta = meta meta.rom_id = rom_id # The scanner only flags whether a cover exists _copy_scanned_columns( scanned_meta, meta, TRACK_META_SCANNED_COLUMNS, TrackMeta, keep_when_unset=frozenset({"cover_path"}), ) return None @begin_session def sync_rom_files( self, rom_id: int, scanned_files: Sequence[RomFile], session: Session = None, # type: ignore[assignment] ) -> SyncedRomFiles: """Reconcile a ROM's file rows against a fresh scan, preserving row ids. Rows are matched by path first, then by content hash, so a file renamed or moved inside the ROM keeps its id, its `created_at` and its track metadata instead of being deleted and re-inserted. Rows left unmatched are deleted, and only columns that actually changed are written, so re-scanning an unchanged ROM issues no updates. Returns the persisted rows in scan order, plus the soundtrack covers left behind by dropped track metadata for the caller to unlink. """ existing = ( session.scalars( select(RomFile) .options(selectinload(RomFile.track_meta)) .filter_by(rom_id=rom_id) ) .unique() .all() ) unmatched = {row.id: row for row in existing} by_path = {(row.file_path, row.file_name): row for row in existing} pairs: list[tuple[RomFile, RomFile | None]] = [] unpaired_indexes: list[int] = [] for scanned in scanned_files: row = by_path.get((scanned.file_path, scanned.file_name)) if row is not None and row.id in unmatched: del unmatched[row.id] pairs.append((scanned, row)) else: unpaired_indexes.append(len(pairs)) pairs.append((scanned, None)) if unpaired_indexes and unmatched: # Identical copies map to the same content key, so keep only keys # that identify a single row rather than pairing them arbitrarily. by_content: dict[tuple[str, str, str], RomFile | None] = {} for row in unmatched.values(): key = _rom_file_content_key(row) if key is not None: by_content[key] = None if key in by_content else row for index in unpaired_indexes: scanned, _ = pairs[index] key = _rom_file_content_key(scanned) if key is None: continue row = by_content.get(key) if row is None: continue del unmatched[row.id] by_content[key] = None pairs[index] = (scanned, row) saved: list[RomFile] = [] orphaned_cover_paths: list[str] = [] for scanned, row in pairs: if row is None: row = RomFile(rom_id=rom_id) session.add(row) orphaned = self._apply_scanned_rom_file(row, scanned, rom_id) if orphaned: orphaned_cover_paths.append(orphaned) saved.append(row) if unmatched: # Deleting a row cascades its track metadata, so its cover would # otherwise be left on disk with nothing pointing at it. orphaned_cover_paths.extend( row.track_meta.cover_path for row in unmatched.values() if row.track_meta and row.track_meta.cover_path ) session.execute( delete(RomFile) .where(RomFile.id.in_(list(unmatched))) .execution_options(synchronize_session="evaluate") ) session.flush() return SyncedRomFiles(files=saved, orphaned_cover_paths=orphaned_cover_paths) @begin_session def get_rom_file_by_id( self, id: int, session: Session = None, # type: ignore[assignment] ) -> RomFile | None: return session.scalar( select(RomFile) .options( selectinload(RomFile.track_meta), selectinload(RomFile.doc_meta), # `is_top_level` reads `rom.full_path`, and callers validate the # row as a schema after this session has closed. joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), ) .filter_by(id=id) .limit(1) ) @begin_session def get_rom_files_by_ids( self, ids: Sequence[int], session: Session = None, # type: ignore[assignment] ) -> Sequence[RomFile]: if not ids: return [] return ( session.scalars( select(RomFile) .options( selectinload(RomFile.track_meta), joinedload(RomFile.rom).load_only(Rom.platform_id), ) .where(RomFile.id.in_(ids)) ) .unique() .all() ) @begin_session def get_rom_file_by_path( self, rom_id: int, file_path: str, file_name: str, session: Session = None, # type: ignore[assignment] ) -> RomFile | None: return session.scalar( select(RomFile) .options(selectinload(RomFile.track_meta), selectinload(RomFile.doc_meta)) .filter_by(rom_id=rom_id, file_path=file_path, file_name=file_name) .limit(1) ) @begin_session def get_rom_files_by_category( self, rom_id: int, category: RomFileCategory, session: Session = None, # type: ignore[assignment] ) -> Sequence[RomFile]: """Return the ROM's files for a single category, ordered by file_name.""" return ( session.scalars( select(RomFile) .options( selectinload(RomFile.track_meta), selectinload(RomFile.doc_meta) ) .filter_by(rom_id=rom_id, category=category) .order_by(RomFile.file_name.asc()) ) .unique() .all() ) @begin_session def rom_files_for_rom_id( self, rom_id: int, session: Session = None, # type: ignore[assignment] ) -> list[RomFile]: """Fetch a ROM's files on demand, with the `RomFile.rom` backref loaded.""" return list( session.scalars( select(RomFile) .filter_by(rom_id=rom_id) .options( joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name), selectinload(RomFile.track_meta), ) ) .unique() .all() ) @begin_session def update_rom_file( self, id: int, data: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> RomFile | None: session.execute( update(RomFile) .where(RomFile.id == id) .values(**data) .execution_options(synchronize_session="evaluate") ) return session.scalars(select(RomFile).filter_by(id=id)).one_or_none() @begin_session def upsert_track_meta( self, rom_file_id: int, rom_id: int, values: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> TrackMeta: existing = session.get(TrackMeta, rom_file_id) if existing: for key, val in values.items(): setattr(existing, key, val) session.flush() return existing track = TrackMeta(rom_file_id=rom_file_id, rom_id=rom_id, **values) session.add(track) session.flush() return track @begin_session def delete_track_meta( self, rom_file_id: int, session: Session = None, # type: ignore[assignment] ) -> None: session.execute(delete(TrackMeta).where(TrackMeta.rom_file_id == rom_file_id)) # ------------------------------------------------------- document metadata @begin_session def upsert_doc_meta( self, rom_file_id: int, rom_id: int, values: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> RomFileDocMeta: """Create or update the provenance sidecar for a document file.""" existing = session.get(RomFileDocMeta, rom_file_id) if existing: for key, val in values.items(): setattr(existing, key, val) session.flush() return existing doc = RomFileDocMeta(rom_file_id=rom_file_id, rom_id=rom_id, **values) session.add(doc) session.flush() return doc # ------------------------------------------------ document reading progress @begin_session def get_rom_file_user( self, rom_file_id: int, user_id: int, session: Session = None, # type: ignore[assignment] ) -> RomFileUser | None: return session.scalar( select(RomFileUser) .filter_by(rom_file_id=rom_file_id, user_id=user_id) .limit(1) ) @begin_session def upsert_rom_file_user( self, rom_file_id: int, user_id: int, values: dict[str, Any], session: Session = None, # type: ignore[assignment] ) -> RomFileUser: """Create or update a user's reading progress for a document file.""" select_state = ( select(RomFileUser) .filter_by(rom_file_id=rom_file_id, user_id=user_id) .limit(1) ) existing = session.scalar(select_state) if existing is None: try: with session.begin_nested(): state = RomFileUser( rom_file_id=rom_file_id, user_id=user_id, **values ) session.add(state) session.flush() except IntegrityError: # A concurrent save (e.g. a second tab) won the insert; update it. existing = session.scalar(select_state) if existing is None: raise else: return state for key, val in values.items(): setattr(existing, key, val) session.flush() return existing # ----------------------------------------------------------------- music def _music_where( self, *, hidden_platform_ids: abc.Collection[int] | None, hidden_rom_ids: abc.Collection[int] | None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, game_genre: str | None = None, platform_ids: Sequence[int] | None = None, rom_id: int | None = None, year: int | None = None, min_year: int | None = None, max_year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, exclude_field: str | None = None, ) -> list[Any]: clauses: list[Any] = [] if hidden_platform_ids: clauses.append(Rom.platform_id.not_in(hidden_platform_ids)) if hidden_rom_ids: clauses.append(Rom.id.not_in(hidden_rom_ids)) if rom_id is not None: clauses.append(Rom.id == rom_id) if search: like = f"%{escape_like(search.lower())}%" clauses.append( or_( func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR), func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR), func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR), ) ) if artist and exclude_field != "artist": clauses.append(func.lower(TrackMeta.artist) == artist.lower()) if album and exclude_field != "album": clauses.append(func.lower(TrackMeta.album) == album.lower()) if genre and exclude_field != "genre": clauses.append(func.lower(TrackMeta.genre) == genre.lower()) if platform_ids: clauses.append(Rom.platform_id.in_(platform_ids)) if game_genre and exclude_field != "game_genre": clauses.append(json_array_contains_value(RomMetadata.genres, game_genre)) if year is not None and exclude_field != "year": clauses.append(TrackMeta.year == year) if min_year is not None and exclude_field != "year": clauses.append(TrackMeta.year >= min_year) if max_year is not None and exclude_field != "year": clauses.append(TrackMeta.year <= max_year) if min_duration is not None: clauses.append(TrackMeta.duration_seconds >= min_duration) if max_duration is not None: clauses.append(TrackMeta.duration_seconds <= max_duration) return clauses @begin_session def get_music_tracks( self, *, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, game_genre: str | None = None, platform_ids: Sequence[int] | None = None, rom_id: int | None = None, year: int | None = None, min_year: int | None = None, max_year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, order_by: str = "title", order_dir: str = "asc", limit: int = 50, offset: int = 0, is_favorite_user_id: int | None = None, only_favorites: bool = False, playlist_id: int | None = None, session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: if only_favorites and is_favorite_user_id is None: return [], 0 where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, search=search, artist=artist, album=album, genre=genre, game_genre=game_genre, platform_ids=platform_ids, rom_id=rom_id, year=year, min_year=min_year, max_year=max_year, min_duration=min_duration, max_duration=max_duration, ) is_favorite_col = ( MusicFavoriteTrack.user_id.is_not(None) if is_favorite_user_id is not None else false() ) base = ( select( TrackMeta.rom_file_id, TrackMeta.rom_id, TrackMeta.title, TrackMeta.artist, TrackMeta.album, TrackMeta.genre, TrackMeta.year, TrackMeta.track, TrackMeta.disc, TrackMeta.duration_seconds, TrackMeta.has_embedded_cover, TrackMeta.cover_path, RomFile.file_name.label("file_name"), is_favorite_col.label("is_favorite"), Rom.name.label("game_name"), Rom.path_cover_l.label("path_cover_l"), RomMetadata.genres.label("game_genres"), RomFile.created_at.label("added_at"), Platform.id.label("platform_id"), Platform.slug.label("platform_slug"), Platform.name.label("platform_name"), ) .select_from(TrackMeta) .join(RomFile, TrackMeta.rom_file_id == RomFile.id) .join(Rom, TrackMeta.rom_id == Rom.id) .outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id) .join(Platform, Rom.platform_id == Platform.id) ) if is_favorite_user_id is not None: favorite_on = and_( MusicFavoriteTrack.user_id == is_favorite_user_id, MusicFavoriteTrack.rom_file_id == TrackMeta.rom_file_id, ) base = ( base.join(MusicFavoriteTrack, favorite_on) if only_favorites else base.outerjoin(MusicFavoriteTrack, favorite_on) ) if playlist_id is not None: base = base.join( MusicPlaylistTrack, and_( MusicPlaylistTrack.playlist_id == playlist_id, MusicPlaylistTrack.rom_file_id == TrackMeta.rom_file_id, ), ) base = base.where(*where) # Count over a single-column projection: the full select carries a JSON # genres blob that would otherwise be materialized just to be counted. count_subquery = base.with_only_columns(TrackMeta.rom_file_id).subquery() total = session.scalar(select(func.count()).select_from(count_subquery)) or 0 order_map = { "title": TrackMeta.title, "artist": TrackMeta.artist, "album": TrackMeta.album, "year": TrackMeta.year, "duration": TrackMeta.duration_seconds, "platform": Platform.name, "added": RomFile.created_at, } if playlist_id is not None: order_map["position"] = MusicPlaylistTrack.position col = order_map.get(order_by, TrackMeta.title) rows = session.execute( base.order_by(nulls_last(col, order_dir == "desc"), TrackMeta.rom_file_id) .limit(limit) .offset(offset) ).all() return rows, total @begin_session def get_music_facet( self, *, field: str, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, platform_ids: Sequence[int] | None = None, year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, order_by: str = "count", order_dir: str = "desc", limit: int = 50, offset: int = 0, session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: facet_columns = { "artists": (TrackMeta.artist, "artist"), "albums": (TrackMeta.album, "album"), "genres": (TrackMeta.genre, "genre"), "years": (TrackMeta.year, "year"), } col, own = facet_columns[field] where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, artist=artist, album=album, genre=genre, platform_ids=platform_ids, year=year, min_duration=min_duration, max_duration=max_duration, exclude_field=own, ) where.append(col.is_not(None)) if field != "years": where.append(func.length(func.trim(col)) > 0) if search: target = cast(col, String) if field == "years" else col where.append( func.lower(target).like( f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR ) ) count_col = func.count().label("count") base = ( select(col.label("value"), count_col) .select_from(TrackMeta) .join(RomFile, TrackMeta.rom_file_id == RomFile.id) .join(Rom, TrackMeta.rom_id == Rom.id) .join(Platform, Rom.platform_id == Platform.id) .where(*where) .group_by(col) ) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 primary: UnaryExpression[Any] if order_by == "value": primary = col.asc() if order_dir != "desc" else col.desc() else: primary = count_col.asc() if order_dir == "asc" else count_col.desc() rows = session.execute( base.order_by(primary, col.asc()).limit(limit).offset(offset) ).all() return rows, total def _music_facet_joins[S: Select[Any]](self, statement: S) -> S: return ( statement.select_from(TrackMeta) .join(RomFile, TrackMeta.rom_file_id == RomFile.id) .join(Rom, TrackMeta.rom_id == Rom.id) .outerjoin(RomMetadata, RomMetadata.rom_id == Rom.id) .join(Platform, Rom.platform_id == Platform.id) ) @begin_session def get_music_stats( self, *, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, session: Session = None, # type: ignore[assignment] ) -> tuple[int, float]: """Total track count and total duration, for the jukebox home cards. A count and a SUM beat shipping the catalog to the client just to derive two numbers from it. """ where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, ) row = session.execute( self._music_facet_joins( select( func.count().label("total"), func.coalesce(func.sum(TrackMeta.duration_seconds), 0.0).label( "duration" ), ) ).where(*where) ).one() return int(row.total or 0), float(row.duration or 0.0) @begin_session def get_music_game_genre_facet( self, *, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, platform_ids: Sequence[int] | None = None, year: int | None = None, min_year: int | None = None, max_year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, order_by: str = "count", order_dir: str = "desc", limit: int = 50, offset: int = 0, session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Distinct *game* genres over the tracked roms, with track counts. `RomMetadata.genres` is a JSON array, so it can't be grouped in SQL the way the scalar tag facets are. Counting per rom first keeps the rows proportional to games rather than tracks, then the arrays are folded in Python -- the same shape `_collect_filter_values` uses for ROM filters. """ where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, artist=artist, album=album, genre=genre, platform_ids=platform_ids, year=year, min_year=min_year, max_year=max_year, min_duration=min_duration, max_duration=max_duration, ) per_rom = self._music_facet_joins( select(Rom.id.label("rom_id"), func.count().label("total")) ).where(*where) counts_by_rom = { row.rom_id: row.total for row in session.execute(per_rom.group_by(Rom.id)).all() } if not counts_by_rom: return [], 0 totals: Counter[str] = Counter() genre_rows = session.execute( select(RomMetadata.rom_id, RomMetadata.genres).where( RomMetadata.rom_id.in_(counts_by_rom.keys()) ) ).all() needle = search.lower() if search else None for rom_id, genres in genre_rows: for value in genres or []: name = (value or "").strip() if not name: continue if needle and needle not in name.lower(): continue totals[name] += counts_by_rom[rom_id] items = list(totals.items()) if order_by == "value": items.sort(key=lambda kv: kv[0].lower(), reverse=order_dir == "desc") else: items.sort(key=lambda kv: (-kv[1], kv[0].lower())) if order_dir == "asc": items.reverse() rows = [ SimpleNamespace(value=name, count=count) for name, count in items[offset : offset + limit] ] return rows, len(items) @begin_session def get_music_platform_facet( self, *, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, game_genre: str | None = None, year: int | None = None, min_year: int | None = None, max_year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, order_by: str = "value", order_dir: str = "asc", limit: int = 50, offset: int = 0, session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Platforms that have soundtrack tracks, with per-platform counts.""" where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, artist=artist, album=album, genre=genre, game_genre=game_genre, year=year, min_year=min_year, max_year=max_year, min_duration=min_duration, max_duration=max_duration, ) if search: where.append( func.lower(Platform.name).like( f"%{escape_like(search.lower())}%", escape=LIKE_ESCAPE_CHAR ) ) count_col = func.count().label("count") base = self._music_facet_joins( select( Platform.id.label("id"), Platform.slug.label("slug"), Platform.name.label("name"), count_col, ) ).where(*where) base = base.group_by(Platform.id, Platform.slug, Platform.name) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 primary: UnaryExpression[Any] if order_by == "count": primary = count_col.asc() if order_dir == "asc" else count_col.desc() else: primary = ( Platform.name.desc() if order_dir == "desc" else Platform.name.asc() ) rows = session.execute( base.order_by(primary, Platform.name.asc()).limit(limit).offset(offset) ).all() return rows, total @begin_session def get_music_game_facet( self, *, hidden_platform_ids: abc.Collection[int] | None = None, hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, genre: str | None = None, game_genre: str | None = None, platform_ids: Sequence[int] | None = None, year: int | None = None, min_year: int | None = None, max_year: int | None = None, min_duration: float | None = None, max_duration: float | None = None, order_by: str = "value", order_dir: str = "asc", limit: int = 50, offset: int = 0, session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Games that have soundtrack tracks -- the jukebox's album list.""" where = self._music_where( hidden_platform_ids=hidden_platform_ids, hidden_rom_ids=hidden_rom_ids, artist=artist, album=album, genre=genre, game_genre=game_genre, platform_ids=platform_ids, year=year, min_year=min_year, max_year=max_year, min_duration=min_duration, max_duration=max_duration, ) if search: like = f"%{escape_like(search.lower())}%" where.append( or_( func.lower(Rom.name).like(like, escape=LIKE_ESCAPE_CHAR), func.lower(TrackMeta.title).like(like, escape=LIKE_ESCAPE_CHAR), func.lower(TrackMeta.artist).like(like, escape=LIKE_ESCAPE_CHAR), func.lower(TrackMeta.album).like(like, escape=LIKE_ESCAPE_CHAR), ) ) count_col = func.count().label("count") base = self._music_facet_joins( select( Rom.id.label("rom_id"), Rom.name.label("name"), Rom.path_cover_l.label("path_cover_l"), Platform.id.label("platform_id"), Platform.slug.label("platform_slug"), Platform.name.label("platform_name"), count_col, ) ).where(*where) base = base.group_by( Rom.id, Rom.name, Rom.path_cover_l, Platform.id, Platform.slug, Platform.name, ) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 primary: UnaryExpression[Any] if order_by == "count": primary = count_col.asc() if order_dir == "asc" else count_col.desc() else: primary = Rom.name.desc() if order_dir == "desc" else Rom.name.asc() rows = session.execute( base.order_by(primary, Rom.name.asc()).limit(limit).offset(offset) ).all() return rows, total @begin_session def delete_rom_file( self, id: int, session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(RomFile) .where(RomFile.id == id) .execution_options(synchronize_session="evaluate") ) # Note management methods def _rom_notes_query( self, rom_id: int, user_id: int, *, public_only: bool = False, search: str | None = "", tags: list[str] | None = None, ) -> Select[tuple[RomNote]]: query = select(RomNote).filter(RomNote.rom_id == rom_id) if public_only: query = query.filter(RomNote.is_public) else: # Include user's own notes (private + public) and public notes from others query = query.filter(or_(RomNote.user_id == user_id, RomNote.is_public)) if search: query = query.filter( or_(RomNote.title.contains(search), RomNote.content.contains(search)) ) if tags: for tag in tags: query = query.filter(json_array_contains_value(RomNote.tags, tag)) return query.order_by(RomNote.updated_at.desc()) @begin_session def get_rom_notes( self, rom_id: int, user_id: int, public_only: bool = False, search: str | None = "", tags: list[str] | None = None, session: Session = None, # type: ignore[assignment] ) -> Sequence[RomNote]: return session.scalars( self._rom_notes_query( rom_id=rom_id, user_id=user_id, public_only=public_only, search=search, tags=tags, ) ).all() @begin_session def get_rom_note_ids( self, rom_id: int, user_id: int, public_only: bool = False, search: str | None = "", tags: list[str] | None = None, session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `RomNote` is built and no eager rom or user join fires.""" query = self._rom_notes_query( rom_id=rom_id, user_id=user_id, public_only=public_only, search=search, tags=tags, ) return list(session.scalars(query.with_only_columns(RomNote.id)).all()) @begin_session def create_rom_note( self, rom_id: int, user_id: int, title: str, content: str = "", is_public: bool = False, tags: list[str] | None = None, session: Session = None, # type: ignore[assignment] ) -> dict[str, Any]: note = RomNote( rom_id=rom_id, user_id=user_id, title=title, content=content, is_public=is_public, tags=tags or [], ) session.add(note) session.flush() # To get the ID # Return dict to avoid detached instance issues return { "id": note.id, "title": note.title, "content": note.content, "is_public": note.is_public, "tags": note.tags, "created_at": note.created_at, "updated_at": note.updated_at, "rom_id": note.rom_id, "user_id": note.user_id, } @begin_session def update_rom_note( self, note_id: int, user_id: int, rom_id: int, session: Session = None, # type: ignore[assignment] **fields: Any, ) -> dict[str, Any] | None: note = session.scalar( select(RomNote) .filter( RomNote.id == note_id, RomNote.user_id == user_id, RomNote.rom_id == rom_id, ) .limit(1) ) if not note: return None for field, value in fields.items(): if hasattr(note, field): setattr(note, field, value) session.flush() # Ensure changes are committed # Return dict to avoid detached instance issues return { "id": note.id, "title": note.title, "content": note.content, "is_public": note.is_public, "tags": note.tags, "created_at": note.created_at, "updated_at": note.updated_at, "rom_id": note.rom_id, "user_id": note.user_id, } @begin_session def delete_rom_note( self, note_id: int, user_id: int, rom_id: int, session: Session = None, # type: ignore[assignment] ) -> bool: result = session.execute( delete(RomNote).where( and_( RomNote.id == note_id, RomNote.user_id == user_id, RomNote.rom_id == rom_id, ) ) ) return affected_rows(result) > 0 @begin_session @with_details def get_rom_by_metadata_id( self, igdb_id: int | None = None, moby_id: int | None = None, ss_id: int | None = None, ra_id: int | None = None, launchbox_id: int | None = None, hasheous_id: int | None = None, tgdb_id: int | None = None, flashpoint_id: str | None = None, hltb_id: int | None = None, demozoo_id: int | None = None, pouet_id: int | None = None, csdb_id: int | None = None, steam_id: int | None = None, *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Rom | None: """ Get a ROM by any metadata ID. Returns the first ROM that matches any of the provided metadata IDs. """ # Build filters for non-nil IDs filters = [ column == value for value, column in [ (igdb_id, Rom.igdb_id), (moby_id, Rom.moby_id), (ss_id, Rom.ss_id), (ra_id, Rom.ra_id), (launchbox_id, Rom.launchbox_id), (hasheous_id, Rom.hasheous_id), (tgdb_id, Rom.tgdb_id), (flashpoint_id, Rom.flashpoint_id), (hltb_id, Rom.hltb_id), (demozoo_id, Rom.demozoo_id), (pouet_id, Rom.pouet_id), (csdb_id, Rom.csdb_id), (steam_id, Rom.steam_id), ] if value is not None ] if not filters: return None # Return the first ROM matching any of the provided metadata IDs return session.scalar(query.filter(or_(*filters)).limit(1)) @begin_session @with_details def get_rom_by_hash( self, crc_hash: str | None = None, md5_hash: str | None = None, sha1_hash: str | None = None, ra_hash: str | None = None, *, query: RomSelect = None, # type: ignore[assignment] session: Session = None, # type: ignore[assignment] ) -> Rom | None: """ Get a ROM by calculated hash value. Returns the first ROM that matches any of the provided hash values. """ # Build filters for non-nil IDs filters = [ column == value for value, column in [ (crc_hash, Rom.crc_hash), (md5_hash, Rom.md5_hash), (sha1_hash, Rom.sha1_hash), (ra_hash, Rom.ra_hash), (crc_hash, RomFile.crc_hash), (md5_hash, RomFile.md5_hash), (sha1_hash, RomFile.sha1_hash), (ra_hash, RomFile.ra_hash), ] if value is not None ] if not filters: return None # Return the first ROM matching any of the provided hash values return session.scalar(query.outerjoin(Rom.files).filter(or_(*filters)).limit(1)) @begin_session def get_matching_missing_rom( self, platform_id: int, crc_hash: str | None = None, md5_hash: str | None = None, sha1_hash: str | None = None, title_id: str | None = None, session: Session = None, # type: ignore[assignment] ) -> Rom | None: """Find a ROM marked missing on a platform that identifies the file. Used during scanning to reassociate a renamed or moved file with its existing entry (preserving collections, notes, and assets) instead of creating a duplicate. All three hashes must match; any missing hash falls through to the binary title id, which non-hashable platforms like Switch carry instead. Returns: The single matching ROM, or None when there is no unambiguous one. """ identity: tuple[ColumnElement[bool], ...] if crc_hash and md5_hash and sha1_hash: identity = ( Rom.crc_hash == crc_hash, Rom.md5_hash == md5_hash, Rom.sha1_hash == sha1_hash, ) elif title_id: identity = (Rom.title_id == title_id,) else: return None matches = session.scalars( select(Rom) .where( and_( Rom.platform_id == platform_id, Rom.missing_from_fs.is_(True), *identity, ) ) .limit(2) ).all() # Return None when more than one match to avoid ambiguity. return matches[0] if len(matches) == 1 else None def _collect_filter_values( self, session: Session, statement: RomSelect, ) -> RomFiltersDict: genres = set() franchises = set() collections = set() companies = set() publishers = set() developers = set() game_modes = set() age_ratings = set() player_counts = set() regions = set() languages = set() tags = set() platforms = set() for row in session.execute(statement): g, f, cl, co, pub, dev, gm, ar, pc, rg, lg, tg, pid = row if g: genres.update(g) if f: franchises.update(f) if cl: collections.update(cl) if co: companies.update(co) if pub: publishers.update(pub) if dev: developers.update(dev) if gm: game_modes.update(gm) if ar: age_ratings.update(ar) if pc: player_counts.add(pc) if rg: regions.update(rg) if lg: languages.update(lg) if tg: tags.update(tg) platforms.add(pid) return RomFiltersDict( genres=sorted(genres), franchises=sorted(franchises), collections=sorted(collections), companies=sorted(companies), publishers=sorted(publishers), developers=sorted(developers), game_modes=sorted(game_modes), age_ratings=sorted(age_ratings), player_counts=sorted(player_counts), regions=sorted(regions), languages=sorted(languages), tags=sorted(tags), platforms=sorted(platforms), ) @begin_session def refresh_identity_key_statistics( self, *, session: Session = None, # type: ignore[assignment] ) -> None: """Resample `rom_identity_keys` so the sibling join keeps its indexed plan. Migration 0127's sample lands on an empty table on a fresh install, and InnoDB's auto-recalc refreshes the stored row count without replanning. """ session.execute(Analyze(RomIdentityKey.__tablename__)) def invalidate_filter_values_cache(self) -> None: old_version = str(int(sync_cache.incr(ROM_FILTERS_CACHE_VERSION_KEY)) - 1) old_keys_set = _filter_values_cache_keys_key(old_version) old_cache_keys = [ key for raw_key in sync_cache.smembers(old_keys_set) if (key := _cache_value_to_str(raw_key)) is not None ] if old_cache_keys: sync_cache.delete(*old_cache_keys) sync_cache.delete(old_keys_set) @begin_session def with_filter_values( self, query: RomSelect, *, cache_key: str | None = None, session: Session = None, # type: ignore[assignment] ) -> RomFiltersDict: """ Returns the list of filters given the current subset of ROMs in the query """ redis_key: str | None = None version: str | None = None if cache_key: version = _filter_values_cache_version() redis_key = _filter_values_redis_key(cache_key, version) cached = sync_cache.get(redis_key) if cached is not None: return json.loads(cached) ids_subq = query.order_by(None).with_only_columns(Rom.id).scalar_subquery() statement = _FILTER_VALUES_SELECT.where(RomFacets.rom_id.in_(ids_subq)) result = self._collect_filter_values(session, statement) if redis_key is not None and version is not None: _store_versioned_cache(redis_key, version, result) return result @begin_session def get_rom_filters( self, session: Session = None, # type: ignore[assignment] ) -> RomFiltersDict: """ Returns all filter values across all ROM metadata """ return self._collect_filter_values(session, _FILTER_VALUES_SELECT)