Files
romm/backend/models/collection.py
Michael Manganiello 3f4a36a5ce feat: PostgreSQL compatibility
This change introduces PostgreSQL compatibility, by implementing the
following changes:

* Use `JSONB` instead of `JSON` for PostgreSQL databases. This is
  achieved by creating a custom `CustomJSON` type that uses `JSONB` on
  PostgreSQL and `JSON` on other databases, leveraging the variant
  mechanism of SQLAlchemy.
* Add `is_postgresql` function to check if the current database is
  PostgreSQL. Commonly used for migrations, but can be used to determine
  how to build queries based on the database engine.
* Add `json_array_contains_value` function to check if a JSON array
  includes a specific value. This function is needed as it's
  engine-specific.

Support for PostgreSQL is on a best-effort basis, and it relies on the
community for continued support and testing. The project's main database
is MariaDB.

Closes #667.
2024-12-31 12:36:33 -03:00

53 lines
1.6 KiB
Python

from __future__ import annotations
from functools import cached_property
from models.base import BaseModel
from models.user import User
from sqlalchemy import ForeignKey, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from utils.database import CustomJSON
class Collection(BaseModel):
__tablename__ = "collections"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(length=400))
description: Mapped[str | None] = mapped_column(Text)
path_cover_l: Mapped[str | None] = mapped_column(Text, default="")
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
url_cover: Mapped[str | None] = mapped_column(
Text, default="", doc="URL to cover image stored in IGDB"
)
roms: Mapped[set[int]] = mapped_column(
CustomJSON(), default=[], doc="Rom id's that belong to this collection"
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
is_public: Mapped[bool] = mapped_column(default=False)
user: Mapped[User] = relationship(lazy="joined", back_populates="collections")
@property
def user__username(self) -> str:
return self.user.username
@property
def rom_count(self) -> int:
return len(self.roms)
@cached_property
def has_cover(self) -> bool:
return bool(self.path_cover_s or self.path_cover_l)
@property
def fs_resources_path(self) -> str:
return f"collections/{str(self.id)}"
def __repr__(self) -> str:
return self.name