From cd724b7d1abe22aa466886b83ad598eb012a99cd Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 28 Jan 2025 23:47:09 -0500 Subject: [PATCH] migrate collections over to join table --- backend/alembic/env.py | 6 +- .../0034_virtual_collections_db_view.py | 96 +++++++++++++++---- backend/endpoints/collections.py | 2 + backend/endpoints/responses/rom.py | 4 +- backend/endpoints/rom.py | 12 +-- .../handler/database/collections_handler.py | 20 +--- backend/models/collection.py | 36 +++++-- backend/models/rom.py | 21 ++-- .../__generated__/models/DetailedRomSchema.ts | 4 +- .../src/__generated__/models/RomSchema.ts | 2 +- .../__generated__/models/SimpleRomSchema.ts | 2 +- .../src/components/Details/Info/GameInfo.vue | 2 +- .../AppBar/Search/PlatformSelector.vue | 2 +- .../Gallery/AppBar/Search/SearchTextField.vue | 2 +- frontend/src/stores/galleryFilter.ts | 2 +- frontend/src/stores/roms.ts | 2 +- frontend/src/views/Gallery/Collection.vue | 2 +- frontend/src/views/Gallery/Platform.vue | 4 +- frontend/src/views/Gallery/Search.vue | 2 +- 19 files changed, 138 insertions(+), 85 deletions(-) diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 8cd4677fe..f1884b74c 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -6,6 +6,7 @@ from alembic import context from config.config_manager import ConfigManager from models.assets import Save, Screenshot, State # noqa from models.base import BaseModel +from models.collection import VirtualCollection from models.firmware import Firmware # noqa from models.platform import Platform # noqa from models.rom import Rom, SiblingRom # noqa @@ -35,7 +36,10 @@ target_metadata = BaseModel.metadata # Ignore specific models when running migrations def include_object(object, name, type_, reflected, compare_to): - if type_ == "table" and name in [SiblingRom.__tablename__]: # Virtual table + if type_ == "table" and name in [ + SiblingRom.__tablename__, + VirtualCollection.__tablename__, + ]: # Virtual table return False return True diff --git a/backend/alembic/versions/0034_virtual_collections_db_view.py b/backend/alembic/versions/0034_virtual_collections_db_view.py index c2a5fcaa7..6847565b8 100644 --- a/backend/alembic/versions/0034_virtual_collections_db_view.py +++ b/backend/alembic/versions/0034_virtual_collections_db_view.py @@ -8,8 +8,7 @@ Create Date: 2024-08-08 12:00:00.000000 import sqlalchemy as sa from alembic import op -from sqlalchemy.dialects import postgresql as sa_pg -from utils.database import is_postgresql +from utils.database import CustomJSON, is_postgresql # revision identifiers, used by Alembic. revision = "0034_virtual_collections_db_view" @@ -19,17 +18,43 @@ depends_on = None def upgrade() -> None: - with op.batch_alter_table("collections", schema=None) as batch_op: - batch_op.alter_column( - "roms", - new_column_name="rom_ids", - existing_type=sa.JSON().with_variant( - sa_pg.JSONB(astext_type=sa.Text()), "postgresql" - ), - ) + op.create_table( + "collections_roms", + sa.Column("collection_id", sa.Integer(), nullable=False), + sa.Column("rom_id", sa.Integer(), nullable=False), + sa.Column( + "created_at", + sa.TIMESTAMP(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.TIMESTAMP(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.ForeignKeyConstraint( + ["collection_id"], ["collections.id"], ondelete="CASCADE" + ), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("collection_id", "rom_id"), + sa.UniqueConstraint("collection_id", "rom_id", name="unique_collection_rom"), + ) connection = op.get_bind() + if is_postgresql(connection): + connection.execute( + sa.text( + """ + INSERT INTO collection_roms (collection_id, rom_id) + SELECT c.id, rom_id::INT, NOW(), NOW() + FROM collections c, + LATERAL jsonb_array_elements_text(c.roms) AS rom_id + """ + ) + ) connection.execute( sa.text( """ @@ -111,6 +136,16 @@ def upgrade() -> None: ), ) else: + connection.execute( + sa.text( + """ + INSERT INTO collections_roms (collection_id, rom_id, created_at, updated_at) + SELECT c.id, jt.rom_id, NOW(), NOW() + FROM collections c + JOIN JSON_TABLE(c.roms, '$[*]' COLUMNS (rom_id INT PATH '$')) AS jt + """ + ) + ) connection.execute( sa.text( """ @@ -223,18 +258,45 @@ def upgrade() -> None: ), ) + op.drop_column("collections", "roms") + def downgrade() -> None: with op.batch_alter_table("collections", schema=None) as batch_op: - batch_op.alter_column( - "rom_ids", - new_column_name="roms", - existing_type=sa.JSON().with_variant( - sa_pg.JSONB(astext_type=sa.Text()), "postgresql" - ), - ) + batch_op.add_column(sa.Column("roms", CustomJSON(), nullable=False)) connection = op.get_bind() + if is_postgresql(connection): + connection.execute( + sa.text( + """ + UPDATE collections c + SET roms = ( + SELECT jsonb_agg(rom_id) + FROM collections_roms cr + WHERE cr.collection_id = c.id + ); + """ + ) + ) + else: + connection.execute( + sa.text( + """ + UPDATE collections c + JOIN ( + SELECT collection_id, JSON_ARRAYAGG(rom_id) as roms + FROM collections_roms + GROUP BY collection_id + ) cr + ON c.id = cr.collection_id + SET c.roms = cr.roms; + """ + ) + ) + + sa.drop_table("collections_roms") + connection.execute( sa.text( """ diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index c57e0dd4d..95c7d144c 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -216,6 +216,8 @@ async def update_collection( "user_id": request.user.id, } + # TODO: update this + if remove_cover: cleaned_data.update(fs_resource_handler.remove_cover(collection)) cleaned_data.update({"url_cover": ""}) diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 25a07c67d..c6ca71efd 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -146,7 +146,7 @@ class RomSchema(BaseModel): alternative_names: list[str] genres: list[str] franchises: list[str] - collections: list[str] + meta_collections: list[str] companies: list[str] game_modes: list[str] age_ratings: list[str] @@ -233,7 +233,7 @@ class DetailedRomSchema(RomSchema): if s.user_id == user_id ] db_rom.user_collections = CollectionSchema.for_user( # type: ignore - user_id, [c for c in db_rom.get_collections()] + user_id, db_rom.collections ) return cls.model_validate(db_rom) diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index e1bd5007d..edef8f310 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -21,7 +21,7 @@ from exceptions.fs_exceptions import RomAlreadyExistsException from fastapi import HTTPException, Request, UploadFile, status from fastapi.responses import Response from handler.auth.constants import Scope -from handler.database import db_collection_handler, db_platform_handler, db_rom_handler +from handler.database import db_platform_handler, db_rom_handler from handler.filesystem import fs_resource_handler, fs_rom_handler from handler.filesystem.base_handler import CoverSize from handler.metadata import meta_igdb_handler, meta_moby_handler @@ -599,16 +599,6 @@ async def delete_roms( log.info(f"Deleting {rom.fs_name} from database") db_rom_handler.delete_rom(id) - # Update collections to remove the deleted rom - collections = db_collection_handler.get_collections_by_rom_id(id) - for collection in collections: - collection.rom_ids = { - rom_id for rom_id in collection.rom_ids if rom_id != id - } - db_collection_handler.update_collection( - collection.id, {"roms": collection.rom_ids} - ) - try: rmtree(f"{RESOURCES_BASE_PATH}/{rom.fs_resources_path}") except FileNotFoundError: diff --git a/backend/handler/database/collections_handler.py b/backend/handler/database/collections_handler.py index 3c23cbcee..c28e4dac7 100644 --- a/backend/handler/database/collections_handler.py +++ b/backend/handler/database/collections_handler.py @@ -1,11 +1,9 @@ -from typing import Any, Sequence +from typing import Sequence from decorators.database import begin_session from models.collection import Collection, VirtualCollection from sqlalchemy import delete, literal, or_, select, update from sqlalchemy.orm import Session -from sqlalchemy.sql import ColumnExpressionArgument -from utils.database import json_array_contains_value from .base_handler import DBBaseHandler @@ -64,22 +62,6 @@ class DBCollectionsHandler(DBBaseHandler): .all() ) - @begin_session - def get_collections_by_rom_id( - self, - rom_id: int, - *, - order_by: Sequence[str | ColumnExpressionArgument[Any]] | None = None, - session: Session = None, - ) -> Sequence[Collection]: - query = select(Collection).filter( - json_array_contains_value(Collection.rom_ids, rom_id, session=session) - ) - if order_by is not None: - query = query.order_by(*order_by) - - return session.scalars(query).all() - @begin_session def update_collection( self, id: int, data: dict, session: Session = None diff --git a/backend/models/collection.py b/backend/models/collection.py index 69637745e..934c10d5e 100644 --- a/backend/models/collection.py +++ b/backend/models/collection.py @@ -2,7 +2,6 @@ from __future__ import annotations import base64 import json -from typing import Sequence from config import FRONTEND_RESOURCES_PATH from models.base import BaseModel @@ -27,26 +26,28 @@ class Collection(BaseModel): Text, default="", doc="URL to cover image stored in IGDB" ) - rom_ids: Mapped[set[int]] = mapped_column( - CustomJSON(), default=[], doc="Rom IDs that belong to this collection" + roms: Mapped[list[Rom]] = relationship( + "Rom", + secondary="collections_roms", + collection_class=set, + back_populates="collections", + lazy="joined", ) user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE")) user: Mapped[User] = relationship(lazy="joined", back_populates="collections") - @property - def roms(self) -> Sequence[Rom]: - from handler.database import db_rom_handler - - return db_rom_handler.get_roms(collection_id=self.id) - @property def user__username(self) -> str: return self.user.username + @property + def rom_ids(self) -> list[int]: + return [r.id for r in self.roms] + @property def rom_count(self) -> int: - return len(self.rom_ids) + return len(self.roms) @property def fs_resources_path(self) -> str: @@ -92,6 +93,21 @@ class Collection(BaseModel): return self.name +class CollectionRom(BaseModel): + __tablename__ = "collections_roms" + + collection_id: Mapped[int] = mapped_column( + ForeignKey("collections.id", ondelete="CASCADE"), primary_key=True + ) + rom_id: Mapped[int] = mapped_column( + ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True + ) + + __table_args__ = ( + UniqueConstraint("collection_id", "rom_id", name="unique_collection_rom"), + ) + + class VirtualCollection(BaseModel): __tablename__ = "virtual_collections" diff --git a/backend/models/rom.py b/backend/models/rom.py index f21b518ec..3d00c3bcd 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -3,7 +3,7 @@ from __future__ import annotations import enum from datetime import datetime from functools import cached_property -from typing import TYPE_CHECKING, Any, Sequence +from typing import TYPE_CHECKING, Any from config import FRONTEND_RESOURCES_PATH from models.base import BaseModel @@ -17,7 +17,6 @@ from sqlalchemy import ( String, Text, UniqueConstraint, - func, ) from sqlalchemy.orm import Mapped, mapped_column, relationship from utils.database import CustomJSON, safe_float, safe_int @@ -130,6 +129,14 @@ class Rom(BaseModel): screenshots: Mapped[list[Screenshot]] = relationship(back_populates="rom") rom_users: Mapped[list[RomUser]] = relationship(back_populates="rom") + collections: Mapped[list[Collection]] = relationship( + "Collection", + secondary="collections_roms", + collection_class=set, + back_populates="roms", + lazy="joined", + ) + @property def platform_slug(self) -> str: return self.platform.slug @@ -195,14 +202,6 @@ class Rom(BaseModel): def is_unidentified(self) -> bool: return not self.igdb_id and not self.moby_id - def get_collections(self) -> Sequence[Collection]: - from handler.database import db_collection_handler - - return db_collection_handler.get_collections_by_rom_id( - self.id, - order_by=[func.lower("name")], - ) - # Metadata fields @property def youtube_video_id(self) -> str: @@ -257,7 +256,7 @@ class Rom(BaseModel): return [] @property - def collections(self) -> list[str]: + def meta_collections(self) -> list[str]: if self.igdb_metadata: return self.igdb_metadata.get("collections", []) return [] diff --git a/frontend/src/__generated__/models/DetailedRomSchema.ts b/frontend/src/__generated__/models/DetailedRomSchema.ts index 8ad9f5a28..ab9bcf1a0 100644 --- a/frontend/src/__generated__/models/DetailedRomSchema.ts +++ b/frontend/src/__generated__/models/DetailedRomSchema.ts @@ -12,7 +12,6 @@ import type { SaveSchema } from './SaveSchema'; import type { ScreenshotSchema } from './ScreenshotSchema'; import type { StateSchema } from './StateSchema'; import type { UserNotesSchema } from './UserNotesSchema'; -import type { VirtualCollectionSchema } from './VirtualCollectionSchema'; export type DetailedRomSchema = { id: number; igdb_id: (number | null); @@ -39,7 +38,7 @@ export type DetailedRomSchema = { alternative_names: Array; genres: Array; franchises: Array; - collections: Array; + meta_collections: Array; companies: Array; game_modes: Array; age_ratings: Array; @@ -69,7 +68,6 @@ export type DetailedRomSchema = { user_screenshots: Array; user_notes: Array; user_collections: Array; - virtual_collections: Array; readonly sort_comparator: string; }; diff --git a/frontend/src/__generated__/models/RomSchema.ts b/frontend/src/__generated__/models/RomSchema.ts index 8f2674bd6..71de447b5 100644 --- a/frontend/src/__generated__/models/RomSchema.ts +++ b/frontend/src/__generated__/models/RomSchema.ts @@ -31,7 +31,7 @@ export type RomSchema = { alternative_names: Array; genres: Array; franchises: Array; - collections: Array; + meta_collections: Array; companies: Array; game_modes: Array; age_ratings: Array; diff --git a/frontend/src/__generated__/models/SimpleRomSchema.ts b/frontend/src/__generated__/models/SimpleRomSchema.ts index 5936d50a1..314c121e8 100644 --- a/frontend/src/__generated__/models/SimpleRomSchema.ts +++ b/frontend/src/__generated__/models/SimpleRomSchema.ts @@ -33,7 +33,7 @@ export type SimpleRomSchema = { alternative_names: Array; genres: Array; franchises: Array; - collections: Array; + meta_collections: Array; companies: Array; game_modes: Array; age_ratings: Array; diff --git a/frontend/src/components/Details/Info/GameInfo.vue b/frontend/src/components/Details/Info/GameInfo.vue index 6232608bf..6a47563d2 100644 --- a/frontend/src/components/Details/Info/GameInfo.vue +++ b/frontend/src/components/Details/Info/GameInfo.vue @@ -21,7 +21,7 @@ const router = useRouter(); const filters = [ { value: "genres", name: t("rom.genres") }, { value: "franchises", name: t("rom.franchises") }, - { value: "collections", name: t("rom.collections") }, + { value: "meta_collections", name: t("rom.collections") }, { value: "companies", name: t("rom.companies") }, ] as const; const galleryViewStore = storeGalleryView(); diff --git a/frontend/src/components/Gallery/AppBar/Search/PlatformSelector.vue b/frontend/src/components/Gallery/AppBar/Search/PlatformSelector.vue index c3a2ecaec..e69a81d45 100644 --- a/frontend/src/components/Gallery/AppBar/Search/PlatformSelector.vue +++ b/frontend/src/components/Gallery/AppBar/Search/PlatformSelector.vue @@ -48,7 +48,7 @@ function setFilters() { galleryFilterStore.setFilterCollections([ ...new Set( romsStore.filteredRoms - .flatMap((rom) => rom.collections.map((collection) => collection)) + .flatMap((rom) => rom.meta_collections.map((collection) => collection)) .sort(), ), ]); diff --git a/frontend/src/components/Gallery/AppBar/Search/SearchTextField.vue b/frontend/src/components/Gallery/AppBar/Search/SearchTextField.vue index a9435dcfb..fa1a6c8a7 100644 --- a/frontend/src/components/Gallery/AppBar/Search/SearchTextField.vue +++ b/frontend/src/components/Gallery/AppBar/Search/SearchTextField.vue @@ -50,7 +50,7 @@ function setFilters() { galleryFilterStore.setFilterCollections([ ...new Set( romsStore.filteredRoms - .flatMap((rom) => rom.collections.map((collection) => collection)) + .flatMap((rom) => rom.meta_collections.map((collection) => collection)) .sort(), ), ]); diff --git a/frontend/src/stores/galleryFilter.ts b/frontend/src/stores/galleryFilter.ts index 33937eea1..1ce4623f8 100644 --- a/frontend/src/stores/galleryFilter.ts +++ b/frontend/src/stores/galleryFilter.ts @@ -7,7 +7,7 @@ export type Platform = PlatformSchema; const filters = [ "genres", "franchises", - "collections", + "meta_collections", "companies", "age_ratings", "status", diff --git a/frontend/src/stores/roms.ts b/frontend/src/stores/roms.ts index 24a9277bc..ba0e016b7 100644 --- a/frontend/src/stores/roms.ts +++ b/frontend/src/stores/roms.ts @@ -274,7 +274,7 @@ export default defineStore("roms", { const byCollection = new Set( this.filteredRoms .filter((rom) => - rom.collections.some( + rom.meta_collections.some( (collection) => collection === collectionToFilter, ), ) diff --git a/frontend/src/views/Gallery/Collection.vue b/frontend/src/views/Gallery/Collection.vue index aa6545ace..fa5e25323 100644 --- a/frontend/src/views/Gallery/Collection.vue +++ b/frontend/src/views/Gallery/Collection.vue @@ -112,7 +112,7 @@ function setFilters() { galleryFilterStore.setFilterCollections([ ...new Set( romsStore.filteredRoms - .flatMap((rom) => rom.collections.map((collection) => collection)) + .flatMap((rom) => rom.meta_collections.map((collection) => collection)) .sort(), ), ]); diff --git a/frontend/src/views/Gallery/Platform.vue b/frontend/src/views/Gallery/Platform.vue index 2db721f55..dc3f14ac0 100644 --- a/frontend/src/views/Gallery/Platform.vue +++ b/frontend/src/views/Gallery/Platform.vue @@ -103,7 +103,7 @@ function setFilters() { galleryFilterStore.setFilterCollections([ ...new Set( romsStore.filteredRoms - .flatMap((rom) => rom.collections.map((collection) => collection)) + .flatMap((rom) => rom.meta_collections.map((collection) => collection)) .sort(), ), ]); @@ -208,7 +208,7 @@ function resetGallery() { const filterToSetFilter: Record = { genres: galleryFilterStore.setSelectedFilterGenre, franchises: galleryFilterStore.setSelectedFilterFranchise, - collections: galleryFilterStore.setSelectedFilterCollection, + meta_collections: galleryFilterStore.setSelectedFilterCollection, companies: galleryFilterStore.setSelectedFilterCompany, age_ratings: galleryFilterStore.setSelectedFilterAgeRating, status: galleryFilterStore.setSelectedFilterStatus, diff --git a/frontend/src/views/Gallery/Search.vue b/frontend/src/views/Gallery/Search.vue index be123da1b..3a6967f17 100644 --- a/frontend/src/views/Gallery/Search.vue +++ b/frontend/src/views/Gallery/Search.vue @@ -65,7 +65,7 @@ function setFilters() { galleryFilterStore.setFilterCollections([ ...new Set( romsStore.filteredRoms - .flatMap((rom) => rom.collections.map((collection) => collection)) + .flatMap((rom) => rom.meta_collections.map((collection) => collection)) .sort(), ), ]);