feat: refactor sibling data handling in RomSchema and update related methods

This commit is contained in:
zurdi
2026-05-26 08:21:45 +00:00
parent 8f48c92cbf
commit 2a35ca04e7
5 changed files with 134 additions and 41 deletions

View File

@@ -2,7 +2,7 @@ from __future__ import annotations
import re
from datetime import datetime, timezone
from typing import NotRequired, TypedDict, get_type_hints
from typing import Any, NotRequired, TypedDict, get_type_hints
from fastapi import Request
from pydantic import ConfigDict, computed_field, field_validator
@@ -329,22 +329,6 @@ class RomSchema(BaseModel):
@classmethod
def populate_properties(cls, db_rom: Rom, request: Request) -> Rom:
db_rom.rom_user = RomUserSchema.for_user(request.user.id, db_rom) # type: ignore
db_rom.siblings = sorted( # type: ignore
(
SiblingRomSchema(
id=s.id,
name=s.name,
fs_name_no_tags=s.fs_name_no_tags,
fs_name_no_ext=s.fs_name_no_ext,
is_main_sibling=any(
ru.user_id == request.user.id and ru.is_main_sibling
for ru in s.rom_users
),
)
for s in db_rom.sibling_roms
),
key=lambda x: x.sort_comparator,
)
db_rom.has_notes = any( # type: ignore
note.is_public or note.user_id == request.user.id for note in db_rom.notes
)
@@ -381,19 +365,62 @@ class SiblingRomSchema(BaseModel):
class SimpleRomSchema(RomSchema):
sibling_ids: list[int]
siblings: list[SiblingRomSchema]
@classmethod
def from_orm_with_request(
cls, db_rom: Rom, request: Request, sibling_ids: list[int] | None = None
cls,
db_rom: Rom,
request: Request,
sibling_data: list[dict[str, Any]] | None = None,
) -> SimpleRomSchema:
db_rom = cls.populate_properties(db_rom, request)
db_rom.sibling_ids = sibling_ids or [] # type: ignore
# List endpoint passes `sibling_data` from get_sibling_data_for_roms
# (no sibling Rom hydration). Single-rom endpoints (loaded via the
# `with_details` decorator) fall back to the eager-loaded relationship.
if sibling_data is not None:
siblings_sorted = sorted(
(
SiblingRomSchema(
id=s["id"],
name=s["name"],
fs_name_no_tags=s["fs_name_no_tags"],
fs_name_no_ext=s["fs_name_no_ext"],
is_main_sibling=s["is_main_sibling"],
)
for s in sibling_data
),
key=lambda x: x.sort_comparator,
)
else:
user_id = request.user.id
siblings_sorted = sorted(
(
SiblingRomSchema(
id=s.id,
name=s.name,
fs_name_no_tags=s.fs_name_no_tags,
fs_name_no_ext=s.fs_name_no_ext,
is_main_sibling=any(
ru.user_id == user_id and ru.is_main_sibling
for ru in s.rom_users
),
)
for s in db_rom.sibling_roms
),
key=lambda x: x.sort_comparator,
)
db_rom.siblings = siblings_sorted # type: ignore
db_rom.sibling_ids = [s.id for s in siblings_sorted] # type: ignore
return cls.model_validate(db_rom)
@classmethod
def from_orm_with_factory(cls, db_rom: Rom) -> SimpleRomSchema:
db_rom.rom_user = rom_user_schema_factory() # type: ignore
db_rom.sibling_ids = [] # type: ignore
db_rom.siblings = [] # type: ignore
db_rom.has_notes = False # type: ignore
return cls.model_validate(db_rom)
@@ -435,6 +462,22 @@ class DetailedRomSchema(RomSchema):
user_id = request.user.id
db_rom = cls.populate_properties(db_rom, request)
db_rom.siblings = sorted( # type: ignore
(
SiblingRomSchema(
id=s.id,
name=s.name,
fs_name_no_tags=s.fs_name_no_tags,
fs_name_no_ext=s.fs_name_no_ext,
is_main_sibling=any(
ru.user_id == user_id and ru.is_main_sibling
for ru in s.rom_users
),
)
for s in db_rom.sibling_roms
),
key=lambda x: x.sort_comparator,
)
db_rom.sibling_ids = [s.id for s in db_rom.siblings] # type: ignore
db_rom.user_saves = [ # type: ignore

View File

@@ -573,15 +573,17 @@ def get_roms(
rom_id_index = session.scalars(query.with_only_columns(Rom.id)).all() # type: ignore
def _transform(items: Sequence[Rom]) -> list[SimpleRomSchema]:
sibling_ids_by_rom = db_rom_handler.get_sibling_ids_for_roms(
[i.id for i in items], session=session
sibling_data_by_rom = db_rom_handler.get_sibling_data_for_roms(
[i.id for i in items],
user_id=request.user.id,
session=session,
)
return [
SimpleRomSchema.from_orm_with_request(
db_rom=item,
request=request,
sibling_ids=sibling_ids_by_rom.get(item.id, []),
sibling_data=sibling_data_by_rom.get(item.id, []),
)
for item in items
]

View File

@@ -38,7 +38,15 @@ from decorators.database import begin_session
from handler.metadata.base_handler import UniversalPlatformSlug as UPS
from models.assets import Save, Screenshot, State
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory, RomMetadata, RomNote, RomUser, SiblingRom
from models.rom import (
Rom,
RomFile,
RomFileCategory,
RomMetadata,
RomNote,
RomUser,
SiblingRom,
)
from utils.database import (
json_array_contains_all,
json_array_contains_any,
@@ -209,30 +217,64 @@ class DBRomsHandler(DBBaseHandler):
return []
return session.scalars(query.filter(Rom.id.in_(ids))).all()
def get_sibling_ids_for_roms(
def get_sibling_data_for_roms(
self,
rom_ids: list[int],
user_id: int,
*,
session: Session,
) -> dict[int, list[int]]:
"""Return {rom_id: [sibling_rom_id, ...]} for the given rom IDs.
) -> dict[int, list[dict[str, Any]]]:
"""Return {rom_id: [{id, name, fs_name_no_tags, fs_name_no_ext, is_main_sibling}, ...]}.
Single query against the sibling_roms view, projecting only the two `id` columns.
Single query joining sibling_roms → roms (scalar columns only) → rom_user
(filtered to the request user). No Rom JSON metadata is hydrated, so this
stays cheap even on large pages — the cost is one extra JOIN with a few
scalar columns vs. the bare-IDs variant.
"""
if not rom_ids:
return {}
rows = session.execute(
select(SiblingRom.rom_id, SiblingRom.sibling_rom_id).where(
SiblingRom.rom_id.in_(rom_ids)
select(
SiblingRom.rom_id,
SiblingRom.sibling_rom_id,
Rom.name,
Rom.fs_name_no_tags,
Rom.fs_name_no_ext,
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))
).all()
buckets: dict[int, set[int]] = {rom_id: set() for rom_id in rom_ids}
for rom_id, sibling_rom_id in rows:
buckets[rom_id].add(sibling_rom_id)
# Dedupe by (parent rom, sibling id) so a duplicate row in the join
# doesn't surface twice on the wire.
seen: dict[int, set[int]] = {rom_id: set() for rom_id in rom_ids}
buckets: dict[int, list[dict[str, Any]]] = {rom_id: [] for rom_id in rom_ids}
for rom_id, sib_id, name, fs_name_no_tags, fs_name_no_ext, is_main in rows:
if sib_id in seen[rom_id]:
continue
seen[rom_id].add(sib_id)
buckets[rom_id].append(
{
"id": sib_id,
"name": name,
"fs_name_no_tags": fs_name_no_tags,
"fs_name_no_ext": fs_name_no_ext,
"is_main_sibling": bool(is_main),
}
)
return {rom_id: sorted(ids) for rom_id, ids in buckets.items()}
return buckets
def filter_by_platform_id(self, query: Query, platform_id: int):
return query.filter(Rom.platform_id == platform_id)
@@ -602,14 +644,9 @@ class DBRomsHandler(DBBaseHandler):
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
# Required for multi-file ROM actions and 3DS QR code
selectinload(Rom.files),
# Show sibling rom badges on cards
selectinload(Rom.sibling_roms).options(
noload(Rom.platform),
noload(Rom.metadatum),
# Required so SiblingRomSchema.is_main_sibling can be
# computed per sibling for the request user.
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
),
# Sibling badge data is populated separately via
# get_sibling_data_for_roms — avoids hydrating full Rom rows
# (including JSON metadata) per sibling on every page.
# Notes indicator on cards
selectinload(Rom.notes),
)

View File

@@ -14,6 +14,7 @@ import type { RomMobyMetadata } from './RomMobyMetadata';
import type { RomRAMetadata } from './RomRAMetadata';
import type { RomSSMetadata } from './RomSSMetadata';
import type { RomUserSchema } from './RomUserSchema';
import type { SiblingRomSchema } from './SiblingRomSchema';
export type SimpleRomSchema = {
id: number;
igdb_id: (number | null);
@@ -86,5 +87,6 @@ export type SimpleRomSchema = {
merged_screenshots: Array<string>;
merged_ra_metadata: (RomRAMetadata | null);
sibling_ids: Array<number>;
siblings: Array<SiblingRomSchema>;
};

View File

@@ -51,6 +51,7 @@ import AssetStrip from "@/v2/components/Player/AssetStrip.vue";
import { useBackgroundArt } from "@/v2/composables/useBackgroundArt";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types";
import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils";
// Reuse v1's heavy emulator integration — do NOT rewrite this. Lazy so the
// bundle doesn't pull in the EJS shims until we actually mount the player.
@@ -78,6 +79,7 @@ const selectedCore = ref<string | null>(null);
const selectedFirmware = ref<FirmwareSchema | null>(null);
const supportedCores = ref<string[]>([]);
const gameRunning = ref(false);
const removeIOSFullscreenShim = ref<(() => void) | null>(null);
declare global {
interface Navigator {
@@ -112,6 +114,9 @@ watch(
);
async function onPlay() {
removeIOSFullscreenShim.value?.();
removeIOSFullscreenShim.value = installIOSFullscreenShim();
if (rom.value && auth.scopes.includes("roms.user.write")) {
romApi.updateUserRomProps({
romId: rom.value.id,
@@ -181,6 +186,8 @@ async function onPlay() {
playing.value = true;
fullScreen.value = fullscreenOnPlay.value;
} catch (err) {
removeIOSFullscreenShim.value?.();
removeIOSFullscreenShim.value = null;
console.error("[Play] Emulator load failure:", err);
}
}
@@ -321,6 +328,8 @@ onMounted(async () => {
onBeforeUnmount(() => {
window.EJS_emulator?.callEvent("exit");
removeIOSFullscreenShim.value?.();
removeIOSFullscreenShim.value = null;
emitter?.off("saveSelected", selectSave);
emitter?.off("stateSelected", selectState);
});