diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 803d6e41d..61b254160 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -694,11 +694,9 @@ def get_roms( updated_after=updated_after, released_days=parsed_released_days, released_before_year=released_before_year, - # The page's files answer all three flags without the subqueries. - include_file_stats=not with_files, - # Siblings and the notes indicator are resolved per page below. - include_siblings=False, - include_notes=False, + # Only ids, letters and counts are selected from it; the page's rows load + # through get_page_rows_query below. + include_related=False, ) # Cache only the fully unscoped library scan: the sidecar cache key encodes @@ -850,9 +848,14 @@ def get_roms( ) if page_ids: - # The rows are reordered by `page_ids` below, so the sort is dropped. + # The ids already passed the filters and the sibling grouping, so the + # rows load without re-running either. page_rows = session.scalars( - query.where(Rom.id.in_(page_ids)).order_by(None) + db_rom_handler.get_page_rows_query( + page_ids, + visibility=perms.rom_visibility, + include_file_stats=not with_files, + ) ).all() rows_by_id = {rom.id: rom for rom in page_rows} page_items = [rows_by_id[i] for i in page_ids if i in rows_by_id] diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 949382901..9ceda52d7 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -44,6 +44,7 @@ from sqlalchemy.orm import ( selectinload, undefer, ) +from sqlalchemy.orm.interfaces import ORMOption from sqlalchemy.sql.dml import Insert from sqlalchemy.sql.elements import ColumnElement, UnaryExpression from sqlalchemy.sql.selectable import Select @@ -564,25 +565,24 @@ def _region_rank() -> ColumnElement[Any]: ) -def _prerelease_rank() -> ColumnElement[Any]: - """Rank pre-release dumps after full releases within a sibling group. +# "(" then any tag, so "(Demo)", "(Beta 2)" and "(Prototype)" match and a title that +# merely contains "demo" does not. +_PRERELEASE_PATTERN = ( + rf"\(({'|'.join(re.escape(tag) for tag in PRERELEASE_FILENAME_TAGS)})" +) - 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, + +def _prerelease_rank() -> ColumnElement[Any]: + """Rank pre-release dumps after full releases within a sibling group.""" + # The filename: `tags` keeps the dumper's casing and the covering index lacks it. + # One regex beats a LOWER() per ILIKE on MariaDB; PostgreSQL's ILIKEs are faster. + is_prerelease = DialectCase( + postgresql=or_( + *[Rom.fs_name_no_ext.ilike(f"%({tag}%") for tag in PRERELEASE_FILENAME_TAGS] ), - else_=0, + mysql=Rom.fs_name_no_ext.regexp_match(_PRERELEASE_PATTERN, flags="i"), ) + return case((is_prerelease, 1), else_=0) # The RomUser column types whose MIN/MAX matches ORDER BY semantics on every @@ -654,12 +654,67 @@ def sorts_by_rom_user_column(order_by: str, user_id: int) -> bool: INJECTED_ROM_QUERY = typing_cast(RomSelect, None) +def _rom_card_loaders( + *, + files: bool = True, + file_meta: bool = True, + file_stats: bool = True, + siblings: bool = True, + notes: bool = True, +) -> list[ORMOption]: + """The loads `SimpleRomSchema` reads, each optional part switched by its flag.""" + options: list[ORMOption] = [ + selectinload(Rom.platform), + selectinload(Rom.rom_users).options( + raiseload(RomUser.rom), raiseload(RomUser.user) + ), + selectinload(Rom.metadatum).options(raiseload(RomMetadata.rom)), + ] + if files: + rom_backref = joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name) + options.append( + selectinload(Rom.files).options( + rom_backref, + selectinload(RomFile.track_meta), + selectinload(RomFile.doc_meta), + ) + if file_meta + else selectinload(Rom.files).options(rom_backref) + ) + if file_stats: + options += [ + undefer(Rom.multi_file), + undefer(Rom.top_level_file_count), + undefer(Rom.has_soundtrack), + undefer(Rom.is_easyrpg_game), + ] + if siblings: + options.append( + selectinload(Rom.sibling_roms).options( + raiseload(Rom.platform), + raiseload(Rom.metadatum), + # is_main_sibling needs each sibling's RomUser (`lazy="raise"`). + selectinload(Rom.rom_users).options( + raiseload(RomUser.rom), raiseload(RomUser.user) + ), + load_only( + *ROM_VISIBILITY_COLUMNS, + Rom.name, + Rom.fs_name_no_tags, + Rom.fs_name_no_ext, + ), + ) + ) + if notes: + options.append(selectinload(Rom.notes)) + return options + + 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), + *_rom_card_loaders(), selectinload(Rom.saves).options( raiseload(Save.rom), raiseload(Save.user), @@ -671,39 +726,7 @@ def with_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: selectinload(Rom.screenshots).options( raiseload(Screenshot.rom), ), - selectinload(Rom.rom_users).options( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - selectinload(Rom.metadatum).options(raiseload(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( - raiseload(Rom.platform), - raiseload(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( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - load_only( - *ROM_VISIBILITY_COLUMNS, - Rom.name, - 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), - undefer(Rom.is_easyrpg_game), ) return func(*args, **kwargs) @@ -711,49 +734,11 @@ def with_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: 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. - """ + """Eager-load only what the `SimpleRomSchema` (v2 gallery card) serializes.""" @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( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - selectinload(Rom.metadatum).options(raiseload(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( - raiseload(Rom.platform), - raiseload(Rom.metadatum), - # Per-sibling is_main_sibling resolution needs each sibling's - # RomUser (relationship is `lazy="raise"`). - selectinload(Rom.rom_users).options( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - load_only( - *ROM_VISIBILITY_COLUMNS, - Rom.name, - 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), - undefer(Rom.is_easyrpg_game), - ) + kwargs["query"] = select(Rom).options(*_rom_card_loaders()) return func(*args, **kwargs) return wrapper @@ -1553,11 +1538,8 @@ class DBRomsHandler(DBBaseHandler): 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, visibility: RomVisibilityFilter = UNRESTRICTED, session: Session = INJECTED_SESSION, ) -> S: @@ -1570,52 +1552,10 @@ class DBRomsHandler(DBBaseHandler): # 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( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - # Sort table by metadata (first_release_date) - selectinload(Rom.metadatum).options(raiseload(RomMetadata.rom)), - ) - - # Show sibling rom badges on cards - if include_siblings: - query = query.options( - selectinload(Rom.sibling_roms).options( - raiseload(Rom.platform), - raiseload(Rom.metadatum), - # is_main_sibling needs each sibling's RomUser. - selectinload(Rom.rom_users).options( - raiseload(RomUser.rom), raiseload(RomUser.user) - ), - ) + # Feeds read the files for download paths, never their metadata. + *_rom_card_loaders( + files=include_files, file_meta=False, file_stats=False ) - - # 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), - undefer(Rom.is_easyrpg_game), ) # Handle platform filtering - platform filtering always uses OR logic since ROMs belong to only one platform @@ -2000,6 +1940,28 @@ class DBRomsHandler(DBBaseHandler): return query.order_by(*order_clauses), sort_key + def get_page_rows_query( + self, + page_ids: Sequence[int], + *, + visibility: RomVisibilityFilter = UNRESTRICTED, + include_file_stats: bool = False, + ) -> RomSelect: + """The rows of one page, loaded by id with none of the filters re-run.""" + # Visibility is re-checked in case a cached id index predates a rule change. + return ( + select(Rom) + .where(Rom.id.in_(page_ids), *visibility.clauses()) + .options( + *_rom_card_loaders( + files=False, + file_stats=include_file_stats, + siblings=False, + notes=False, + ) + ) + ) + def _scoped_roms_query( self, *, diff --git a/backend/tests/endpoints/roms/test_hidden_status_page.py b/backend/tests/endpoints/roms/test_hidden_status_page.py new file mode 100644 index 000000000..5b11a9dc5 --- /dev/null +++ b/backend/tests/endpoints/roms/test_hidden_status_page.py @@ -0,0 +1,40 @@ +from typing import Any, cast + +from fastapi import status +from fastapi.testclient import TestClient +from tests.factories import make_rom + +from handler.database import db_rom_handler +from models.platform import Platform +from models.rom import RomUser +from models.user import User + + +def _add_rom(admin_user: User, platform: Platform, name: str) -> RomUser: + rom = make_rom(platform, name) + return db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) + + +def _list(client: TestClient, access_token: str, **params: str) -> dict[str, Any]: + response = client.get( + "/api/roms", + headers={"Authorization": f"Bearer {access_token}"}, + params={"group_by_meta_id": "true", **params}, + ) + assert response.status_code == status.HTTP_200_OK + return cast(dict[str, Any], response.json()) + + +def test_a_page_picked_with_the_hidden_status_is_not_emptied_on_reload( + client: TestClient, access_token: str, admin_user: User, platform: Platform +) -> None: + shown = _add_rom(admin_user, platform, "shown_rom") + hidden = _add_rom(admin_user, platform, "hidden_rom") + db_rom_handler.update_rom_user(hidden.id, {"hidden": True}) + + page = _list(client, access_token, statuses="hidden") + + assert page["total"] == 1 + assert [item["id"] for item in page["items"]] == [hidden.rom_id] + default_ids = [item["id"] for item in _list(client, access_token)["items"]] + assert default_ids == [shown.rom_id] diff --git a/backend/tests/handler/database/test_roms_page_rows_query.py b/backend/tests/handler/database/test_roms_page_rows_query.py new file mode 100644 index 000000000..775d483ef --- /dev/null +++ b/backend/tests/handler/database/test_roms_page_rows_query.py @@ -0,0 +1,58 @@ +"""Loading a page's rows by id, without the filters or the sibling grouping.""" + +from typing import Any + +from sqlalchemy import Select +from tests.conftest import engine # noqa: F401 (loads the test database setup) +from tests.sql_dialects import POSTGRESQL_DIALECT, compile_sql + +from handler.auth.rom_visibility import RomVisibilityFilter +from handler.database import db_rom_handler +from handler.database.rom_filters import RomFilterParams + +PAGE_IDS = [11, 22, 33] + + +def _sql(statement: Select[Any]) -> str: + return compile_sql(statement, POSTGRESQL_DIALECT, literal_binds=True).lower() + + +def test_the_grouped_query_does_rank_the_library(): + """Grouping puts a window over every rom, which the page-row tests below must not.""" + query, sort_key = db_rom_handler.get_roms_query(order_by="name", user_id=1) + grouped = db_rom_handler.filter_roms( + query=query, + filters=RomFilterParams(group_by_meta_id=True), + sort_key=sort_key, + order_by="name", + user_id=1, + ) + + assert "row_number()" in _sql(grouped) + + +def test_loading_a_page_does_not_rank_the_library(): + assert "row_number()" not in _sql(db_rom_handler.get_page_rows_query(PAGE_IDS)) + + +def test_loading_a_page_is_limited_to_its_ids(): + assert "roms.id in (11, 22, 33)" in _sql( + db_rom_handler.get_page_rows_query(PAGE_IDS) + ) + + +def test_loading_a_page_does_not_refilter_on_rom_user(): + assert "rom_user" not in _sql(db_rom_handler.get_page_rows_query(PAGE_IDS)) + + +def test_loading_a_page_keeps_the_visibility_filter(): + visibility = RomVisibilityFilter(hidden_platform_ids=frozenset({7})) + sql = _sql(db_rom_handler.get_page_rows_query(PAGE_IDS, visibility=visibility)) + + assert "roms.platform_id not in (7)" in sql + + +def test_loading_a_page_keeps_the_file_stats_the_serializer_reads(): + assert "rom_files" in _sql( + db_rom_handler.get_page_rows_query(PAGE_IDS, include_file_stats=True) + ) diff --git a/backend/tests/handler/database/test_roms_prerelease_rank.py b/backend/tests/handler/database/test_roms_prerelease_rank.py new file mode 100644 index 000000000..2935a2745 --- /dev/null +++ b/backend/tests/handler/database/test_roms_prerelease_rank.py @@ -0,0 +1,89 @@ +"""The pre-release rank that orders a sibling group's versions: a tag counts only right after "(".""" + +import re + +import pytest +from sqlalchemy import select +from tests.conftest import engine # noqa: F401 (loads the test database setup) +from tests.factories import make_rom +from tests.sql_dialects import MARIADB_DIALECT, POSTGRESQL_DIALECT, compile_sql + +from handler.database.base_handler import sync_session +from handler.database.roms_handler import _PRERELEASE_PATTERN, _prerelease_rank +from models.base import PRERELEASE_FILENAME_TAGS +from models.platform import Platform +from models.rom import Rom + + +def _ilike_rule(name: str) -> bool: + """What the PostgreSQL ILIKEs match: the lowercase name contains "(" plus a tag.""" + return any(f"({tag}" in name.lower() for tag in PRERELEASE_FILENAME_TAGS) + + +NAMES = [ + "Game (USA)", + "Game (Demo)", + "Game (DEMO) (USA)", + "Game (Demo Kiosk)", + "Game (Beta 2)", + "Game (Proto)", + "Game (Prototype)", + "Game (Sample)", + "Game (Kiosk)", + "Game (Preview)", + "Game (Europe) (Beta)", + "Demolition Man (USA)", + "Beta Fish (USA)", + "Game [Preview]", + "Game - Demo Edition", + "Game (Rev 1)", + "", +] + + +@pytest.mark.parametrize("name", NAMES) +def test_the_regex_agrees_with_the_ilike_rule(name: str): + matches = bool(re.search(_PRERELEASE_PATTERN, name, re.IGNORECASE)) + + assert matches == _ilike_rule(name) + + +def test_mariadb_matches_one_regex_per_row(): + sql = compile_sql(select(_prerelease_rank()), MARIADB_DIALECT).lower() + + assert sql.count("regexp") == 1 + assert "like" not in sql + + +def test_postgresql_keeps_one_ilike_per_tag(): + sql = compile_sql(select(_prerelease_rank()), POSTGRESQL_DIALECT).lower() + + assert sql.count("ilike") == len(PRERELEASE_FILENAME_TAGS) + assert "~*" not in sql + + +@pytest.mark.parametrize( + ("stem", "rank"), + [ + ("Game One (USA)", 0), + ("Game Two (Demo)", 1), + # Upper case: the match must be case-insensitive on this database too. + ("GAME THREE (DEMO) (USA)", 1), + ("Game Four (Beta 2)", 1), + ("Game Five (Prototype)", 1), + ("Game Six (Kiosk Demo)", 1), + # Accent-sensitive on both engines, whatever the MariaDB collation. + ("Game Seven (Démo)", 0), + # A tag counts only right after "(". + ("Demolition Man (USA)", 0), + ("Beta Fish (USA)", 0), + ], +) +def test_the_rank_on_a_real_row(platform: Platform, stem: str, rank: int): + """Runs on whichever database the suite uses, so the engine's own regex decides.""" + rom = make_rom(platform, stem) + + with sync_session.begin() as session: + result = session.scalar(select(_prerelease_rank()).where(Rom.id == rom.id)) + + assert result == rank diff --git a/backend/tools/explain_gallery_query.py b/backend/tools/explain_gallery_query.py new file mode 100644 index 000000000..48e4ff4cb --- /dev/null +++ b/backend/tools/explain_gallery_query.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Time the statements behind one gallery window, with EXPLAIN (ANALYZE). + +A window fetch picks the page's ids, then loads those rows plus one follow-up +query per eager-loaded relationship. This runs them the way GET /api/roms does +for the given user, then prints each one's execution time and the plan nodes +that spend the most of it, so a change to the grouped query can be compared +before and after without the browser. + +Read-only: it opens a READ ONLY transaction and only runs EXPLAIN on SELECTs. +PostgreSQL only. Run from the backend directory: + + uv run tools/explain_gallery_query.py + uv run tools/explain_gallery_query.py --offset 90000 --repeat 3 + uv run tools/explain_gallery_query.py --work-mem 32MB --plan +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import statistics +import sys +from collections.abc import Callable +from typing import Any + +# Allow running as `python3 tools/explain_gallery_query.py` from backend/. +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from sqlalchemy import event, text # noqa: E402 +from sqlalchemy.orm import Session # noqa: E402 + +from handler.database import db_rom_handler, db_user_handler # noqa: E402 + +# Imported after handler.database, which it would otherwise import half-built. +from handler.auth.permissions import resolve_permissions # noqa: E402 # isort: skip +from handler.database.base_handler import sync_session # noqa: E402 +from handler.database.rom_filters import RomFilterParams # noqa: E402 +from models.rom import Rom # noqa: E402 + +TOP_NODES = 5 +SELECTED_TABLE = re.compile(r"^\s*SELECT\s+(\w+)\.", re.IGNORECASE) + +Captured = tuple[str, Any] + + +def _capture(session: Session, run: Callable[[], object]) -> list[Captured]: + """Every (statement, parameters) the driver receives while `run` executes.""" + captured: list[Captured] = [] + + def record(*args: Any) -> None: + # (conn, cursor, statement, parameters, context, executemany) + captured.append((args[2], args[3])) + + connection = session.connection() + event.listen(connection, "before_cursor_execute", record) + try: + run() + finally: + event.remove(connection, "before_cursor_execute", record) + return captured + + +def _explain(session: Session, captured: Captured) -> dict[str, Any]: + """Run EXPLAIN (ANALYZE, BUFFERS) on a captured statement and return the plan.""" + statement, parameters = captured + row: Any = ( + session.connection() + .exec_driver_sql( + f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {statement}", parameters + ) + .scalar_one() + ) + document = json.loads(row) if isinstance(row, str) else row + plan: dict[str, Any] = document[0] + return plan + + +def _own_times( + node: dict[str, Any], out: list[tuple[float, str]], processes: int = 1 +) -> float: + """Collect each node's own time (its time minus its children's); return its total.""" + # Under a Gather, loops count every worker while times average per loop, + # so dividing by the process count keeps the total in wall-clock terms. + loops = float(node.get("Actual Loops", 1)) + total = float(node.get("Actual Total Time", 0.0)) * loops / processes + if node["Node Type"] in ("Gather", "Gather Merge"): + processes = int(node.get("Workers Launched", 0)) + 1 + children = sum(_own_times(child, out, processes) for child in node.get("Plans", [])) + label = node["Node Type"] + if "Relation Name" in node: + label += f" on {node['Relation Name']}" + if "Index Name" in node: + label += f" using {node['Index Name']}" + out.append((total - children, label)) + return total + + +def _report(name: str, plans: list[dict[str, Any]], show_plan: bool) -> float: + times = [plan["Execution Time"] for plan in plans] + print(f"\n{name}") + print( + f" execution min {min(times):.1f} ms median {statistics.median(times):.1f} ms" + f" ({len(times)} runs)" + ) + nodes: list[tuple[float, str]] = [] + _own_times(plans[-1]["Plan"], nodes) + for own, label in sorted(nodes, reverse=True)[:TOP_NODES]: + print(f" {own:8.1f} ms {label}") + if show_plan: + print(json.dumps(plans[-1]["Plan"], indent=2)) + return float(statistics.median(times)) + + +def _positive_int(value: str) -> int: + number = int(value) + if number < 1: + raise argparse.ArgumentTypeError(f"must be at least 1, got {number}") + return number + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--user-id", type=int, default=1) + parser.add_argument( + "--order-by", default="", help="Empty is the endpoint's default (relevance)." + ) + parser.add_argument("--order-dir", default="asc") + parser.add_argument("--offset", type=int, default=0) + parser.add_argument("--limit", type=int, default=72) + parser.add_argument( + "--ungrouped", + action="store_true", + help="Leave siblings uncollapsed, to see the cost grouping adds.", + ) + parser.add_argument( + "--filters", + default="{}", + help='RomFilterParams as JSON, e.g. \'{"search_term": "astral"}\' or \'{"genres": ["Sport"]}\'.', + ) + parser.add_argument("--repeat", type=_positive_int, default=3) + parser.add_argument( + "--work-mem", help="Session work_mem for the run, e.g. 32MB (an experiment)." + ) + parser.add_argument("--plan", action="store_true", help="Print the last full plan.") + args = parser.parse_args() + + # JSON overrides the grouped default; --ungrouped overrides both. + params = {"group_by_meta_id": True, **json.loads(args.filters)} + if args.ungrouped: + params["group_by_meta_id"] = False + filters = RomFilterParams(**params) + # The endpoint lowercases both before building the query. + order_by = args.order_by.lower() + order_dir = args.order_dir.lower() + user = db_user_handler.get_user(args.user_id) + if user is None: + print(f"No user with id {args.user_id}.", file=sys.stderr) + return 1 + visibility = resolve_permissions(user).rom_visibility + unfiltered_query, sort_key = db_rom_handler.get_roms_query( + user_id=args.user_id, + order_by=order_by, + order_dir=order_dir, + search_term=filters.search_term, + ) + query = db_rom_handler.filter_roms( + query=unfiltered_query, + filters=filters, + sort_key=sort_key, + order_by=order_by, + order_dir=order_dir, + user_id=args.user_id, + include_related=False, + visibility=visibility, + ) + + with sync_session.begin() as session: + if session.get_bind().dialect.name != "postgresql": + print("This tool runs on PostgreSQL only.", file=sys.stderr) + return 1 + session.execute(text("SET TRANSACTION READ ONLY")) + if args.work_mem: + session.execute( + text("SELECT set_config('work_mem', :v, true)"), {"v": args.work_mem} + ) + database: str = session.execute(text("SELECT current_database()")).scalar_one() + print( + f"database {database}, user {args.user_id}, " + f"order {order_by or 'default'} " + f"{order_dir}, window {args.offset}+{args.limit}, " + f"grouping {'off' if args.ungrouped else 'on'}, filters {args.filters}" + ) + + ids_statement = ( + query.with_only_columns(Rom.id).offset(args.offset).limit(args.limit) + ) + page_ids: list[int] = [] + captured = _capture( + session, lambda: page_ids.extend(session.scalars(ids_statement).all()) + ) + if not page_ids: + print("The window is empty: is the database seeded?", file=sys.stderr) + return 1 + + load_statement = db_rom_handler.get_page_rows_query( + page_ids, visibility=visibility, include_file_stats=True + ) + rows, *loaders = _capture( + session, lambda: session.scalars(load_statement).all() + ) + steps = [("1. page ids", captured[0]), ("2. load rows by id", rows)] + for index, loader in enumerate(loaders, start=1): + table = SELECTED_TABLE.search(loader[0]) + label = table.group(1) if table else "?" + steps.append((f"2.{index} eager load of {label}", loader)) + + total = 0.0 + for name, statement in steps: + plans = [_explain(session, statement) for _ in range(args.repeat)] + total += _report(name, plans, args.plan) + + print(f"\nall {len(steps)} statements, median total: {total:.1f} ms") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())