sinmplify siblings

This commit is contained in:
Georges-Antoine Assi
2026-06-08 10:25:27 -04:00
parent cfdeab589a
commit 036cf108f4
21 changed files with 56 additions and 138 deletions

View File

@@ -301,6 +301,17 @@ class RomSchema(BaseModel):
merged_screenshots: list[str]
merged_ra_metadata: RomRAMetadata | None
files: list[RomFileSchema]
siblings: list[SiblingRomSchema]
@field_validator("files")
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
return sorted(v, key=lambda x: x.file_name)
@field_validator("siblings")
def sort_siblings(cls, v: list[SiblingRomSchema]) -> list[SiblingRomSchema]:
return sorted(v, key=lambda x: x.sort_comparator)
@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
@@ -347,32 +358,16 @@ class SiblingRomSchema(BaseModel):
class SimpleRomSchema(RomSchema):
sibling_ids: list[int]
files: list[RomFileSchema] = Field(
default_factory=list, validation_alias="included_files"
)
siblings: list[SiblingRomSchema] = Field(default_factory=list)
@field_validator("files")
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
return sorted(v, key=lambda x: x.file_name)
@field_validator("siblings")
def sort_siblings(cls, v: list[SiblingRomSchema]) -> list[SiblingRomSchema]:
return sorted(v, key=lambda x: x.sort_comparator)
@classmethod
def from_orm_with_request(
cls,
db_rom: Rom,
request: Request,
sibling_ids: list[int] | None = None,
files: Sequence[RomFile] | None = None,
siblings: Sequence[Rom] | None = None,
) -> SimpleRomSchema:
db_rom = cls.populate_properties(db_rom, request)
db_rom.sibling_ids = sibling_ids or [] # type: ignore
db_rom.included_files = files or [] # type: ignore
db_rom.files = files or [] # type: ignore
db_rom.siblings = ( # type: ignore
[SiblingRomSchema.from_rom(s) for s in siblings] if siblings else []
)
@@ -381,7 +376,8 @@ class SimpleRomSchema(RomSchema):
@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.files = [] # type: ignore
db_rom.siblings = [] # type: ignore
db_rom.has_notes = False # type: ignore
return cls.model_validate(db_rom)
@@ -405,23 +401,12 @@ class UserCollectionSchema(BaseModel):
class DetailedRomSchema(RomSchema):
siblings: list[SiblingRomSchema]
sibling_ids: list[int]
files: list[RomFileSchema]
user_saves: list[SaveSchema]
user_states: list[StateSchema]
user_screenshots: list[ScreenshotSchema]
user_collections: list[UserCollectionSchema]
all_user_notes: list[UserNoteSchema]
@field_validator("siblings")
def sort_siblings(cls, v: list[SiblingRomSchema]) -> list[SiblingRomSchema]:
return sorted(v, key=lambda x: x.sort_comparator)
@field_validator("files")
def sort_files(cls, v: list[RomFileSchema]) -> list[RomFileSchema]:
return sorted(v, key=lambda x: x.file_name)
@classmethod
def from_orm_with_request(cls, db_rom: Rom, request: Request) -> DetailedRomSchema:
user_id = request.user.id
@@ -432,7 +417,6 @@ class DetailedRomSchema(RomSchema):
key=lambda x: x.sort_comparator,
)
db_rom.siblings = sorted_siblings # type: ignore
db_rom.sibling_ids = [s.id for s in sorted_siblings] # type: ignore
db_rom.user_saves = [ # type: ignore
SaveSchema.model_validate(s) for s in db_rom.saves if s.user_id == user_id

View File

@@ -486,10 +486,6 @@ def get_roms(
bool,
Query(description="Whether to include each rom's file entries."),
] = False,
with_siblings: Annotated[
bool,
Query(description="Whether to include each rom's sibling roms."),
] = False,
) -> CustomLimitOffsetPage[SimpleRomSchema]:
"""Retrieve roms."""
unfiltered_query, order_by_attr = db_rom_handler.get_roms_query(
@@ -585,27 +581,14 @@ def get_roms(
if with_files
else {}
)
if with_siblings:
siblings_by_rom = db_rom_handler.get_siblings_for_roms(
rom_ids, session=session
)
# Derive the id list from the full siblings instead of a second query.
sibling_ids_by_rom = {
rid: sorted({s.id for s in sibs})
for rid, sibs in siblings_by_rom.items()
}
else:
siblings_by_rom = {}
sibling_ids_by_rom = db_rom_handler.get_sibling_ids_for_roms(
rom_ids, session=session
)
siblings_by_rom = db_rom_handler.get_siblings_for_roms(
rom_ids, session=session
)
return [
SimpleRomSchema.from_orm_with_request(
db_rom=item,
request=request,
sibling_ids=sibling_ids_by_rom.get(item.id, []),
files=files_by_rom.get(item.id, []),
siblings=siblings_by_rom.get(item.id, []),
)

View File

@@ -206,31 +206,6 @@ class DBRomsHandler(DBBaseHandler):
return []
return session.scalars(query.filter(Rom.id.in_(ids))).all()
def get_sibling_ids_for_roms(
self,
rom_ids: list[int],
*,
session: Session,
) -> dict[int, list[int]]:
"""Return {rom_id: [sibling_rom_id, ...]} for the given rom IDs.
Single query against the sibling_roms view, projecting only the two `id` columns.
"""
if not rom_ids:
return {}
rows = session.execute(
select(SiblingRom.rom_id, SiblingRom.sibling_rom_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)
return {rom_id: sorted(ids) for rom_id, ids in buckets.items()}
def get_files_for_roms(
self,
rom_ids: list[int],
@@ -261,7 +236,11 @@ class DBRomsHandler(DBBaseHandler):
*,
session: Session,
) -> dict[int, list[Rom]]:
"""Return {rom_id: [sibling Rom, ...]} for the given rom IDs in a single query."""
"""Return {rom_id: [sibling Rom, ...]} for the given rom IDs in a single query.
Only loads the columns consumed by SiblingRomSchema (id is always loaded
as the primary key) to avoid hydrating every column of the wide roms table.
"""
if not rom_ids:
return {}
@@ -269,6 +248,13 @@ class DBRomsHandler(DBBaseHandler):
select(SiblingRom.rom_id, Rom)
.join(Rom, Rom.id == SiblingRom.sibling_rom_id)
.where(SiblingRom.rom_id.in_(rom_ids))
.options(
load_only(
Rom.name,
Rom.fs_name_no_tags,
Rom.fs_name_no_ext,
)
)
).all()
buckets: dict[int, list[Rom]] = {rom_id: [] for rom_id in rom_ids}

View File

@@ -114,44 +114,6 @@ def test_get_all_roms_with_files(
assert item["siblings"] == []
def test_get_all_roms_with_siblings(
client: TestClient, access_token: str, platform: Platform, admin_user: User
):
siblings = [
db_rom_handler.add_rom(
Rom(
platform_id=platform.id,
igdb_id=424242,
name=name,
slug=slug,
fs_name=f"{slug}.zip",
fs_name_no_tags=slug,
fs_name_no_ext=slug,
fs_extension="zip",
fs_path=f"{platform.slug}/roms",
)
)
for name, slug in (("Game A", "game_a"), ("Game B", "game_b"))
]
for sibling in siblings:
db_rom_handler.add_rom_user(rom_id=sibling.id, user_id=admin_user.id)
response = client.get(
"/api/roms",
headers={"Authorization": f"Bearer {access_token}"},
params={"platform_id": platform.id, "with_siblings": True},
)
assert response.status_code == status.HTTP_200_OK
items = {item["id"]: item for item in response.json()["items"]}
rom_a, rom_b = siblings
assert [s["id"] for s in items[rom_a.id]["siblings"]] == [rom_b.id]
assert [s["id"] for s in items[rom_b.id]["siblings"]] == [rom_a.id]
assert items[rom_a.id]["sibling_ids"] == [rom_b.id]
# with_siblings alone must not pull in files.
assert items[rom_a.id]["files"] == []
def test_get_rom_content_requires_auth(client: TestClient, rom: Rom, rom_file):
response = client.get(f"/api/roms/{rom.id}/content/test_rom.zip")
assert response.status_code == status.HTTP_403_FORBIDDEN

View File

@@ -53,7 +53,9 @@ def test_heartbeat(client):
@pytest.mark.parametrize("authorization_header", ["Bearer ", "Foo", "a b c"])
def test_heartbeat_with_malformed_authorization_header(client, authorization_header: str):
def test_heartbeat_with_malformed_authorization_header(
client, authorization_header: str
):
response = client.get(
"/api/heartbeat", headers={"Authorization": authorization_header}
)

View File

@@ -6,7 +6,7 @@ export type Body_add_collection_api_collections_post = {
/**
* Collection artwork file.
*/
artwork?: (Blob | null);
artwork?: (string | null);
name?: string;
description?: string;
/**

View File

@@ -3,6 +3,6 @@
/* tslint:disable */
/* eslint-disable */
export type Body_add_firmware_api_firmware_post = {
files: Array<Blob>;
files: Array<string>;
};

View File

@@ -6,10 +6,10 @@ export type Body_add_save_api_saves_post = {
/**
* Save file to upload.
*/
saveFile: Blob;
saveFile: string;
/**
* Screenshot file associated with this save.
*/
screenshotFile?: (Blob | null);
screenshotFile?: (string | null);
};

View File

@@ -6,6 +6,6 @@ export type Body_add_screenshot_api_screenshots_post = {
/**
* Screenshot file to upload.
*/
screenshotFile: Blob;
screenshotFile: string;
};

View File

@@ -6,10 +6,10 @@ export type Body_add_state_api_states_post = {
/**
* State file to upload.
*/
stateFile: Blob;
stateFile: string;
/**
* Screenshot file associated with this state.
*/
screenshotFile?: (Blob | null);
screenshotFile?: (string | null);
};

View File

@@ -6,7 +6,7 @@ export type Body_update_collection_api_collections__id__put = {
/**
* Collection artwork file.
*/
artwork?: (Blob | null);
artwork?: (string | null);
/**
* Collection ROM IDs as a JSON array string (e.g. [1,2,3]).
*/

View File

@@ -6,7 +6,7 @@ export type Body_update_rom_api_roms__id__put = {
/**
* Custom artwork to set as cover.
*/
artwork?: (Blob | null);
artwork?: (string | null);
igdb_id?: (string | null);
sgdb_id?: (string | null);
moby_id?: (string | null);

View File

@@ -6,10 +6,10 @@ export type Body_update_save_api_saves__id__put = {
/**
* Updated save file content.
*/
saveFile?: (Blob | null);
saveFile?: (string | null);
/**
* Updated screenshot file.
*/
screenshotFile?: (Blob | null);
screenshotFile?: (string | null);
};

View File

@@ -6,10 +6,10 @@ export type Body_update_state_api_states__id__put = {
/**
* Updated state file content.
*/
stateFile?: (Blob | null);
stateFile?: (string | null);
/**
* Updated screenshot file.
*/
screenshotFile?: (Blob | null);
screenshotFile?: (string | null);
};

View File

@@ -90,9 +90,8 @@ export type DetailedRomSchema = {
rom_user: RomUserSchema;
merged_screenshots: Array<string>;
merged_ra_metadata: (RomRAMetadata | null);
siblings: Array<SiblingRomSchema>;
sibling_ids: Array<number>;
files: Array<RomFileSchema>;
siblings: Array<SiblingRomSchema>;
user_saves: Array<SaveSchema>;
user_states: Array<StateSchema>;
user_screenshots: Array<ScreenshotSchema>;

View File

@@ -23,6 +23,7 @@ export type SaveSchema = {
slot?: (string | null);
content_hash?: (string | null);
screenshot: (ScreenshotSchema | null);
origin_device_id?: (string | null);
device_syncs?: Array<DeviceSyncSchema>;
};

View File

@@ -85,8 +85,7 @@ export type SimpleRomSchema = {
rom_user: RomUserSchema;
merged_screenshots: Array<string>;
merged_ra_metadata: (RomRAMetadata | null);
sibling_ids: Array<number>;
files?: Array<RomFileSchema>;
siblings?: Array<SiblingRomSchema>;
files: Array<RomFileSchema>;
siblings: Array<SiblingRomSchema>;
};

View File

@@ -9,7 +9,7 @@ export type UserForm = {
role?: (string | null);
enabled?: (boolean | null);
ra_username?: (string | null);
avatar?: (Blob | null);
avatar?: (string | null);
ui_settings?: (string | null);
};

View File

@@ -6,5 +6,7 @@ export type ValidationError = {
loc: Array<(string | number)>;
msg: string;
type: string;
input?: any;
ctx?: Record<string, any>;
};

View File

@@ -374,10 +374,10 @@ onBeforeUnmount(() => {
<v-icon>mdi-check-decagram-outline</v-icon>
</v-chip>
<v-chip
v-if="rom.sibling_ids.length > 0 && showSiblings"
v-if="rom.siblings.length > 0 && showSiblings"
class="translucent mr-1 mb-1 px-1"
density="compact"
:title="`${rom.sibling_ids.length} sibling(s)`"
:title="`${rom.siblings.length} sibling(s)`"
>
<v-icon>mdi-card-multiple-outline</v-icon>
</v-chip>

View File

@@ -310,10 +310,10 @@ function updateOptions({ sortBy }: { sortBy: SortBy }) {
</v-avatar>
</v-chip>
<v-chip
v-if="item.sibling_ids.length > 0 && showSiblings"
v-if="item.siblings.length > 0 && showSiblings"
class="translucent mr-1 px-1 item-chip"
size="x-small"
:title="`${item.sibling_ids.length} sibling(s)`"
:title="`${item.siblings.length} sibling(s)`"
>
<v-icon>mdi-card-multiple-outline</v-icon>
</v-chip>