migrate collections over to join table

This commit is contained in:
Georges-Antoine Assi
2025-01-28 23:47:09 -05:00
parent 60ec728e55
commit cd724b7d1a
19 changed files with 138 additions and 85 deletions

View File

@@ -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

View File

@@ -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(
"""

View File

@@ -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": ""})

View File

@@ -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)

View File

@@ -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:

View File

@@ -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

View File

@@ -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"

View File

@@ -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 []

View File

@@ -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<string>;
genres: Array<string>;
franchises: Array<string>;
collections: Array<string>;
meta_collections: Array<string>;
companies: Array<string>;
game_modes: Array<string>;
age_ratings: Array<string>;
@@ -69,7 +68,6 @@ export type DetailedRomSchema = {
user_screenshots: Array<ScreenshotSchema>;
user_notes: Array<UserNotesSchema>;
user_collections: Array<CollectionSchema>;
virtual_collections: Array<VirtualCollectionSchema>;
readonly sort_comparator: string;
};

View File

@@ -31,7 +31,7 @@ export type RomSchema = {
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;
collections: Array<string>;
meta_collections: Array<string>;
companies: Array<string>;
game_modes: Array<string>;
age_ratings: Array<string>;

View File

@@ -33,7 +33,7 @@ export type SimpleRomSchema = {
alternative_names: Array<string>;
genres: Array<string>;
franchises: Array<string>;
collections: Array<string>;
meta_collections: Array<string>;
companies: Array<string>;
game_modes: Array<string>;
age_ratings: Array<string>;

View File

@@ -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();

View File

@@ -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(),
),
]);

View File

@@ -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(),
),
]);

View File

@@ -7,7 +7,7 @@ export type Platform = PlatformSchema;
const filters = [
"genres",
"franchises",
"collections",
"meta_collections",
"companies",
"age_ratings",
"status",

View File

@@ -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,
),
)

View File

@@ -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(),
),
]);

View File

@@ -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<FilterType, Function> = {
genres: galleryFilterStore.setSelectedFilterGenre,
franchises: galleryFilterStore.setSelectedFilterFranchise,
collections: galleryFilterStore.setSelectedFilterCollection,
meta_collections: galleryFilterStore.setSelectedFilterCollection,
companies: galleryFilterStore.setSelectedFilterCompany,
age_ratings: galleryFilterStore.setSelectedFilterAgeRating,
status: galleryFilterStore.setSelectedFilterStatus,

View File

@@ -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(),
),
]);