Files
romm/backend/alembic/env.py
nendo 70e583b9a0 Add music favorites and playlists API
Spotify-style library features for soundtrack tracks: per-user favorites
(liked songs) and user-owned playlists with manual ordering and optional
public read-only sharing.

Track references are stored as (rom_id, md5_hash) rather than rom_file_id:
scans purge and re-insert rom_files rows, so file ids churn while rom ids
and content hashes are stable. Entries survive rescans and renames, and
resolve to the current file at query time; entries whose content is gone
are omitted from listings until the file returns.

To make the content hash reliably present, soundtrack audio files are now
always hashed individually during scans (including NON_HASHABLE_PLATFORMS
and SKIP_HASH_CALCULATION, whose file-size concerns don't apply to audio),
and soundtrack uploads compute crc/md5/sha1 on write. Existing libraries
backfill via a HASHES scan; adding an unhashed track returns 400.

New playlists.read/playlists.write scopes are wired through the granular
permission system (PermEntity.PLAYLISTS); the migration mirrors every
group's collections grants onto the playlists entity so existing groups
keep working without admin intervention.

Endpoints under /api/music: favorites GET/POST/DELETE, is_favorite and
md5_hash on track rows, playlists CRUD, playlist tracks GET/POST/DELETE
and PUT /tracks/order.
2026-07-23 15:32:32 +09:00

117 lines
3.3 KiB
Python

import sys
from pathlib import Path
from alembic import context
from sqlalchemy import create_engine
from config.config_manager import ConfigManager
from logger.logger import unify_logger
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.music import MusicFavoriteTrack, MusicPlaylist, MusicPlaylistTrack # noqa
from models.platform import Platform # noqa
from models.rom import Rom, RomFacets, RomMetadata, SiblingRom # noqa
from models.user import User # noqa
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
unify_logger("alembic")
# add your model's MetaData object here
# for 'autogenerate' support
sys.path.append(f"{Path(__file__).parent.parent.resolve()}")
target_metadata = BaseModel.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
# Ignore specific models when running migrations
def include_object(object, name, type_, reflected, compare_to):
if type_ == "table" and name in [
SiblingRom.__tablename__,
VirtualCollection.__tablename__,
RomMetadata.__tablename__,
]: # Virtual table
return False
# Skip DB-specific search indexes in autogenerate
# to avoid false drop/create operations
if type_ == "index" and name in (
"idx_roms_name_fs_name_fulltext",
"idx_roms_name_trgm",
"idx_roms_fs_name_trgm",
):
return False
# generated_* are STORED generated columns backing views.
# They are maintained in raw SQL (dialect-specific expressions) rather
# than the ORM model, so hide them from autogenerate to avoid false drops.
if type_ == "column" and name.startswith("generated_"):
return False
return True
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(
url=ConfigManager.get_db_engine(),
target_metadata=target_metadata,
render_as_batch=True,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
include_object=include_object,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(ConfigManager.get_db_engine())
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
compare_type=True,
include_object=include_object,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()