mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* feat(saves): add save channels and snapshots * feat(saves): close spec gaps in save channels and hash with sigil * feat(saves): play snapshots in the v2 player, which pushes snapshots * fix(saves): code review: authorization, retention losses, held-save sync, batched responses * refactor(saves): simplify pass * refactor(saves): review-polish pass * docs(saves): humanizer pass * feat(saves): run every EmulatorJS page on the v2 player * feat(saves): per-user snapshot pins * feat(sigil): store the identity a save restore needs and pin sigil 0f05f25 * fix(saves): meet type-aware lint in the v2 player * feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda * feat(saves): convert saves for a core on download and list save layouts * feat(saves): prune unreachable archival snapshots and empty detached channels on delete * feat(saves): device sync from the token, held snapshots and shared-card pushes * feat(saves): arc restores past abandoned snapshots and color channels by age * fix(saves): code-review and security-audit fixes * refactor(saves): simplify pass * chore(saves): review-polish pass * docs(saves): humanizer pass * fix(sync): file RetroArch autosave versions as their channel's next snapshot * fix(saves): address review findings and trim docstrings * fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock * test(saves): stub the detached-channels fetch in SaveDataTab stories * feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff * chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets * docs(saves): drop v2 wording now that one UI remains * chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets * fix(sigil): treat a file too short for its format as routine during scans * chore(migrations): renumber save channel migrations after upstream's 0154 * fix(snapshots): a hardcore switch on unchanged content makes a new current * fix(sync): decide a channel's slot from its history and the device's snapshot * chore(docker): pin sigil at 794d99f for PSP Store release save prefixes * refactor(db): squash the save channel migrations into 0161 Fold the slot linking (0162) and the rom_files sigil identity columns (0163) into 0161_save_channels, so the feature ships as one revision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): close visibility and input gaps found in review (pr-ready step 2) code-review --fix: - negotiate_sync drops channel slots on ROMs hidden from the caller - channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden - a push copying a save from a hidden ROM answers 404 - _own_device applies require_token_device to bound client tokens - adopting a legacy save syncs its sharing with the channel it joins security-audit follow-ups: - another user's detached public save or state is no longer downloadable - profile and option values must be a single path segment - companions are de-duplicated and capped at 8 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3) simplify: - readable_channel_or_404 and channels_on_files replace four copies of the channel 404 check and two copies of the file-fed channel listing - readable_rom_asset_or_404 serves both public save and state downloads - _own_device resolves through require_device; _clone_origin takes the source - reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy and uuidv7; neutral forms default their required pattern to the allowed one - RetroArch delete checks held rows in one query, a guarded upload lists the slot only without a channel head, and uploads are read off the event loop - snapshotSession builds push requests once; player comment cleanups Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(saves): trim two docstrings to two lines (pr-ready step 4) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): answer held RetroArch paths with 423, mirror slot labels - RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save and for a DELETE where only held rows sit at the path, instead of 409 and 404 - channelLabelForSlot returns null for blank and state_ slots, as the backend's channel_label does, so the player files them under no channel either - document that sharing a channel lets every user read and push into it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(docker): pin sigil at 85f88a8 for Switch .nup containers * fix(snapshots): a save pushed in another shape or format makes a new current * refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag Nothing reads it, and the SAVE_SYNC block's presence already tells a client the server speaks the snapshot API. Also trim the rom detail channel field comments to one line each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(frontend): use uuidv7 for every client-generated id Drop the randomToken wrapper and the notification inbox's Math.random tab id, so uuidv7 is the one helper that works outside a secure context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic API: - Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds. - GET /snapshots is history only (channel_id required); GET /channels serves currents. - A snapshot carries channel_id instead of an embedded channel. - POST /saves/{id}/content takes the same query parameters as the GET, plus container_path. Backend: - Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil identity-hash path, unused relationships and composite snapshot indexes. - One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and the shared reserve_version_name in the writer. - The writer takes a visibility filter and checks the channel and parent itself. - The restore handler picks per-game or merge; fewer wrapper types and tables. Frontend: - Channel delete uses the shared typed confirm; DeleteChannelDialog is gone. - Held offline pushes go through a per-channel SnapshotSession. - Remove the slot-based pending upload path. - The timeline shares the fan's badge logic. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(saves): release archival backups through module functions The saves and states handlers each built a private DBSnapshotsHandler to call release_backup and refresh_backup_digests, since they can't import the shared instance. Both only ever ran inside the caller's session, so they are now module functions taking it, like channel_for_slot. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(saves): share one deleted-assets handler instance The saves handler built its own DBDeletedAssetsHandler because it can't import the package's instance. The instance is now built in deleted_assets_handler.py and re-exported by the package, so both use it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1522 lines
56 KiB
Python
1522 lines
56 KiB
Python
"""Guard the models against drifting away from the migrated schema.
|
|
|
|
The test database is built from the migrations, so an index declared in one but
|
|
not the other goes unnoticed until autogenerate proposes dropping it.
|
|
"""
|
|
|
|
import importlib.util
|
|
import re
|
|
from pathlib import Path
|
|
from types import ModuleType
|
|
from typing import Any
|
|
|
|
import alembic.config
|
|
import pytest
|
|
import sqlalchemy as sa
|
|
from alembic.autogenerate import compare_metadata
|
|
from alembic.migration import MigrationContext
|
|
from alembic.operations import Operations
|
|
from sqlalchemy import DefaultClause, FetchedValue, Table, UniqueConstraint
|
|
from sqlalchemy.sql.schema import NULL_UNSPECIFIED
|
|
from tests.factories import make_platform, make_rom, make_save
|
|
|
|
import models
|
|
from config.config_manager import config_manager as cm
|
|
from handler.database import db_collection_handler, db_rom_handler
|
|
from handler.database.base_handler import sync_engine
|
|
from models.base import BaseModel
|
|
from models.collection import Collection, SmartCollection
|
|
from models.platform import Platform
|
|
from models.rom import FULL_PATH_HASH_LENGTH, Rom, RomFile, compute_full_path_hash
|
|
from models.user import User
|
|
from utils.database import (
|
|
AUTOGENERATE_EXEMPT_INDEX_NAMES,
|
|
HLTB_MAIN_STORY_COLUMN,
|
|
POSTGRESQL_FK_INDEXES,
|
|
ROMS_SEARCH_FULLTEXT_INDEX,
|
|
ROMS_SEARCH_TITLES_TRGM_INDEX,
|
|
SEARCH_TITLES_COLUMN,
|
|
SORTABLE_NULLABLE_ROM_COLUMNS,
|
|
exact_collation,
|
|
full_path_digest_sql,
|
|
has_column,
|
|
is_mariadb,
|
|
is_postgresql,
|
|
rom_desc_index_name,
|
|
rom_sort_index_name,
|
|
rom_unset_flag_column,
|
|
)
|
|
from utils.roms_columns import (
|
|
FULL_PATH_HASH_COLUMN,
|
|
ROMS_METADATA_VIEW_COLUMNS,
|
|
STEAM_FED_COLUMNS,
|
|
STEAM_METADATA_COLUMN,
|
|
drop_roms_columns,
|
|
ensure_roms_columns,
|
|
has_server_default,
|
|
rebuild_generated_columns,
|
|
steam_fed_columns,
|
|
)
|
|
|
|
# `compare_metadata` yields flat tuples for schema-level diffs, and a list of
|
|
# tuples for column-level ones. Only these two name an index.
|
|
INDEX_DIFF_OPS = frozenset({"add_index", "remove_index"})
|
|
|
|
|
|
def _leading_columns(table: Table) -> set[str]:
|
|
"""Names of the columns a lookup on this table can start from."""
|
|
groups = [list(table.primary_key.columns)]
|
|
groups += [list(index.columns) for index in table.indexes]
|
|
groups += [
|
|
list(constraint.columns)
|
|
for constraint in table.constraints
|
|
if isinstance(constraint, UniqueConstraint)
|
|
]
|
|
return {columns[0].name for columns in groups if columns}
|
|
|
|
|
|
def test_no_index_drift_between_models_and_migrations():
|
|
"""Every migrated index is declared on its model, and vice versa.
|
|
|
|
A failure names the index: declare it in the model's `__table_args__`, or in
|
|
`AUTOGENERATE_EXEMPT_INDEX_NAMES` if it is dialect-specific.
|
|
"""
|
|
models.load_all_models()
|
|
|
|
with sync_engine.connect() as connection:
|
|
context = MigrationContext.configure(connection)
|
|
drift = [
|
|
f"{diff[0]}: {diff[1].name} on {diff[1].table.name}"
|
|
for diff in compare_metadata(context, BaseModel.metadata)
|
|
if not isinstance(diff, list)
|
|
and diff[0] in INDEX_DIFF_OPS
|
|
and diff[1].name not in AUTOGENERATE_EXEMPT_INDEX_NAMES
|
|
]
|
|
|
|
assert drift == []
|
|
|
|
|
|
def test_no_column_drift_between_models_and_migrations():
|
|
"""Every mapped column exists in the migrated schema with the same nullability."""
|
|
models.load_all_models()
|
|
|
|
with sync_engine.connect() as connection:
|
|
inspector = sa.inspect(connection)
|
|
# A view reflects every column as nullable, whatever the model says.
|
|
views = set(inspector.get_view_names())
|
|
drift = []
|
|
for table in BaseModel.metadata.sorted_tables:
|
|
if table.name in views:
|
|
continue
|
|
reflected = {
|
|
column["name"]: column["nullable"]
|
|
for column in inspector.get_columns(table.name)
|
|
}
|
|
for column in table.columns:
|
|
if column.name not in reflected:
|
|
drift.append(f"missing: {table.name}.{column.name}")
|
|
elif column.nullable != reflected[column.name]:
|
|
drift.append(
|
|
f"nullable: {table.name}.{column.name} "
|
|
f"model={column.nullable} db={reflected[column.name]}"
|
|
)
|
|
|
|
assert drift == []
|
|
|
|
|
|
def _is_database_filled(value: object) -> bool:
|
|
# `DefaultClause` is a literal default the ORM could write itself.
|
|
return isinstance(value, FetchedValue) and not isinstance(value, DefaultClause)
|
|
|
|
|
|
def test_database_filled_columns_declare_their_nullability():
|
|
"""Every database-filled column passes `nullable=`, or autogenerate never compares it."""
|
|
models.load_all_models()
|
|
|
|
undeclared = [
|
|
f"{table.name}.{column.name}"
|
|
for table in BaseModel.metadata.sorted_tables
|
|
for column in table.columns
|
|
if any(
|
|
_is_database_filled(value)
|
|
for value in (column.server_default, column.server_onupdate)
|
|
)
|
|
# The same private flag alembic's `_nullability_might_be_unset` reads.
|
|
and column._user_defined_nullable is NULL_UNSPECIFIED
|
|
]
|
|
|
|
assert undeclared == []
|
|
|
|
|
|
def test_postgresql_fk_indexes_cover_every_unindexed_foreign_key():
|
|
"""`POSTGRESQL_FK_INDEXES` holds exactly the foreign keys that need it.
|
|
|
|
MariaDB and MySQL index a foreign key implicitly unless its column already
|
|
leads an index; PostgreSQL does not.
|
|
"""
|
|
models.load_all_models()
|
|
|
|
expected = {
|
|
(table.name, f"ix_{table.name}_{column}", column)
|
|
for table in BaseModel.metadata.tables.values()
|
|
for constraint in table.foreign_key_constraints
|
|
for column in [c.name for c in constraint.columns]
|
|
if len(constraint.columns) == 1 and column not in _leading_columns(table)
|
|
}
|
|
|
|
assert expected == set(POSTGRESQL_FK_INDEXES)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"fs_path,fs_name",
|
|
[
|
|
("roms/nes", "Game (USA).zip"),
|
|
("roms/nes/Hacks & Tra'nslations", "Zelda [T-Eng].nes"),
|
|
("roms/nes/Ünïcøde", "Pokémon Édition Rouge.gb"),
|
|
("", ""),
|
|
(None, None),
|
|
],
|
|
)
|
|
def test_the_migrated_full_path_digest_matches_the_models(
|
|
fs_path: str | None, fs_name: str | None
|
|
):
|
|
"""0126 backfills `full_path_hash` in SQL; the app writes it from Python.
|
|
|
|
A mismatch would make every pre-existing rom look new to the unique index.
|
|
"""
|
|
with sync_engine.connect() as connection:
|
|
digest: str = connection.execute(
|
|
sa.text(
|
|
f"SELECT {full_path_digest_sql(connection)} FROM "
|
|
"(SELECT :fs_path AS fs_path, :fs_name AS fs_name) AS one_rom"
|
|
),
|
|
{"fs_path": fs_path, "fs_name": fs_name},
|
|
).scalar_one()
|
|
|
|
assert digest == compute_full_path_hash(fs_path, fs_name)
|
|
|
|
|
|
def _load_migration(filename: str) -> ModuleType:
|
|
"""Import a revision by file name, which no package path can reach."""
|
|
path = Path(__file__).parent.parent / "alembic" / "versions" / filename
|
|
spec = importlib.util.spec_from_file_location(path.stem, path)
|
|
assert spec and spec.loader
|
|
migration = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(migration)
|
|
|
|
return migration
|
|
|
|
|
|
# Columns by nullability and indexes by (columns, uniqueness).
|
|
TableSchema = tuple[
|
|
dict[str, bool], dict[str | None, tuple[tuple[str | None, ...], bool]]
|
|
]
|
|
|
|
|
|
def _schema_of(connection: sa.Connection, table: str) -> TableSchema:
|
|
inspector = sa.inspect(connection)
|
|
return (
|
|
{column["name"]: column["nullable"] for column in inspector.get_columns(table)},
|
|
{
|
|
index["name"]: (tuple(index["column_names"]), bool(index["unique"]))
|
|
for index in inspector.get_indexes(table)
|
|
},
|
|
)
|
|
|
|
|
|
def _replay(connection: sa.Connection, filename: str) -> None:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
_load_migration(filename).upgrade()
|
|
|
|
|
|
# None of these is touched by a later revision, so replaying one over the
|
|
# migrated schema has to leave that schema exactly as it found it.
|
|
@pytest.mark.parametrize(
|
|
"filename,table",
|
|
[
|
|
("0111_physical_roms.py", "roms"),
|
|
("0120_container_adoptions.py", "streaming_container_adoptions"),
|
|
("0122_rom_similarity.py", "rom_similarity"),
|
|
("0126_unique_rom_full_path.py", "roms"),
|
|
("0128_hltb_main_story_column.py", "roms"),
|
|
("0130_notifications.py", "notifications"),
|
|
("0131_notification_channels.py", "notification_channels"),
|
|
("0132_audit_events.py", "audit_events"),
|
|
("0135_drop_play_session_sync_link.py", "play_sessions"),
|
|
("0136_deleted_assets.py", "deleted_assets"),
|
|
("0138_exact_save_slots.py", "saves"),
|
|
("0139_rom_user_pinned_media.py", "rom_user"),
|
|
("0140_device_save_sync_baseline.py", "device_save_sync"),
|
|
("0141_device_capabilities.py", "devices"),
|
|
("0142_state_core.py", "states"),
|
|
("0143_sibling_platform_names.py", "platforms"),
|
|
("0144_user_oidc_sub.py", "users"),
|
|
("0145_drop_derivable_columns.py", "rom_file_doc_meta"),
|
|
("0146_roms_search_aliases.py", "roms"),
|
|
("0147_rom_file_title_ids.py", "rom_files"),
|
|
("0148_rom_age_limits.py", "roms"),
|
|
("0148_rom_age_limits.py", "roms_facets"),
|
|
("0148_rom_age_limits.py", "permission_groups"),
|
|
("0148_rom_age_limits.py", "users"),
|
|
("0151_state_content_hash.py", "states"),
|
|
("0157_rom_custom_sort_key_flag.py", "roms"),
|
|
("0161_save_channels.py", "channels"),
|
|
("0161_save_channels.py", "snapshots"),
|
|
("0161_save_channels.py", "snapshot_states"),
|
|
("0161_save_channels.py", "snapshot_pins"),
|
|
("0161_save_channels.py", "device_channel_sync"),
|
|
("0161_save_channels.py", "saves"),
|
|
("0161_save_channels.py", "states"),
|
|
("0161_save_channels.py", "screenshots"),
|
|
("0161_save_channels.py", "rom_files"),
|
|
],
|
|
)
|
|
def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op(
|
|
filename: str, table: str
|
|
):
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, table)
|
|
_replay(connection, filename)
|
|
|
|
assert _schema_of(connection, table) == before
|
|
|
|
|
|
def test_the_rom_file_category_revision_adds_game_to_an_enum_made_without_it():
|
|
"""0062 upgrades a romfilecategory enum that has no GAME value."""
|
|
migration = _load_migration("0062_rom_file_category_enum.py")
|
|
|
|
with sync_engine.connect() as connection:
|
|
if not is_postgresql(connection):
|
|
pytest.skip("only PostgreSQL keeps the enum as a type of its own")
|
|
|
|
# A schema of its own, so the shared enum and table stay as migrated.
|
|
connection.execute(sa.text("CREATE SCHEMA pre_game_category"))
|
|
connection.execute(sa.text("SET search_path TO pre_game_category"))
|
|
connection.execute(
|
|
sa.text(
|
|
"CREATE TYPE romfilecategory AS ENUM ('DLC', 'HACK', 'MANUAL',"
|
|
" 'PATCH', 'UPDATE', 'MOD', 'DEMO', 'TRANSLATION', 'PROTOTYPE')"
|
|
)
|
|
)
|
|
connection.execute(sa.text("CREATE TABLE rom_files (category romfilecategory)"))
|
|
connection.execute(sa.text("INSERT INTO rom_files VALUES ('DLC')"))
|
|
connection.commit()
|
|
try:
|
|
context = MigrationContext.configure(connection)
|
|
with Operations.context(context), context.begin_transaction():
|
|
migration.upgrade()
|
|
|
|
labels: str = connection.execute(
|
|
sa.text("SELECT enum_range(NULL::romfilecategory)::text")
|
|
).scalar_one()
|
|
category: str = connection.execute(
|
|
sa.text("SELECT category::text FROM rom_files")
|
|
).scalar_one()
|
|
finally:
|
|
connection.rollback()
|
|
connection.execute(sa.text("RESET search_path"))
|
|
connection.execute(sa.text("DROP SCHEMA pre_game_category CASCADE"))
|
|
connection.commit()
|
|
|
|
# GAME lands ahead of DLC, where a fresh install has it.
|
|
assert labels.startswith("{GAME,DLC,")
|
|
assert category == "DLC"
|
|
|
|
|
|
def test_the_play_session_sync_link_revision_reverses_and_replays():
|
|
"""0135 drops a column whose constraint each dialect handles differently.
|
|
|
|
MariaDB and MySQL index the foreign key themselves and refuse to drop the
|
|
column while it stands; PostgreSQL takes both with the column and needs the
|
|
index 0124 made. Each step is guarded, so both directions replay.
|
|
"""
|
|
migration = _load_migration("0135_drop_play_session_sync_link.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "play_sessions")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert has_column(connection, "play_sessions", "sync_session_id")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert not has_column(connection, "play_sessions", "sync_session_id")
|
|
assert _schema_of(connection, "play_sessions") == before
|
|
|
|
|
|
def test_the_device_capabilities_revision_reverses_and_replays():
|
|
migration = _load_migration("0141_device_capabilities.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "devices")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "devices", "capabilities")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "devices") == before
|
|
|
|
|
|
def test_the_state_core_revision_reverses_and_replays():
|
|
migration = _load_migration("0142_state_core.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "states")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "states", "core")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "states") == before
|
|
|
|
|
|
def test_the_state_content_hash_revision_reverses_and_replays():
|
|
migration = _load_migration("0151_state_content_hash.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "states")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "states", "content_hash")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "states") == before
|
|
|
|
|
|
def test_the_cross_user_smart_scopes_revision_empties_only_those_caches(
|
|
admin_user: User, editor_user: User
|
|
):
|
|
migration = _load_migration("0152_cross_user_smart_scopes.py")
|
|
private, public = (
|
|
db_collection_handler.add_collection(
|
|
Collection(
|
|
name=name, description="", user_id=admin_user.id, is_public=is_public
|
|
)
|
|
)
|
|
for name, is_public in (("Secret", False), ("Shared", True))
|
|
)
|
|
borrowed, own, borrowed_public = (
|
|
db_collection_handler.add_smart_collection(
|
|
SmartCollection(
|
|
name="Scoped",
|
|
user_id=owner.id,
|
|
rom_ids=[1, 2],
|
|
path_covers_small=["cover"],
|
|
filter_criteria={"collection_id": scope.id},
|
|
)
|
|
)
|
|
for owner, scope in (
|
|
(editor_user, private),
|
|
(admin_user, private),
|
|
(editor_user, public),
|
|
)
|
|
)
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
|
|
cleared = db_collection_handler.get_smart_collection(borrowed.id)
|
|
assert cleared is not None
|
|
assert (cleared.rom_ids, cleared.path_covers_small) == ([], [])
|
|
for kept_id in (own.id, borrowed_public.id):
|
|
kept = db_collection_handler.get_smart_collection(kept_id)
|
|
assert kept is not None
|
|
assert (kept.rom_ids, kept.path_covers_small) == ([1, 2], ["cover"])
|
|
|
|
|
|
def test_the_user_oidc_sub_revision_reverses_and_replays():
|
|
migration = _load_migration("0144_user_oidc_sub.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "users")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "users", "oidc_sub")
|
|
assert not has_column(connection, "users", "oidc_issuer")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "users") == before
|
|
|
|
|
|
def test_the_derivable_columns_revision_reverses_and_replays(admin_user: User):
|
|
"""0145 drops a foreign key MariaDB and MySQL named for themselves in 0110."""
|
|
migration = _load_migration("0145_drop_derivable_columns.py")
|
|
tables = ("smart_collections", "rom_file_doc_meta")
|
|
smart = db_collection_handler.add_smart_collection(
|
|
SmartCollection(
|
|
name="Smart",
|
|
user_id=admin_user.id,
|
|
rom_ids=[1, 2, 3],
|
|
filter_criteria={},
|
|
)
|
|
)
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = {table: _schema_of(connection, table) for table in tables}
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
columns = {
|
|
(table, c["name"]): c
|
|
for table in tables
|
|
for c in sa.inspect(connection).get_columns(table)
|
|
}
|
|
assert not columns[("rom_file_doc_meta", "rom_id")]["nullable"]
|
|
assert columns[("smart_collections", "rom_count")]["default"] is None
|
|
rom_count: int = connection.execute(
|
|
sa.text("SELECT rom_count FROM smart_collections WHERE id = :id"),
|
|
{"id": smart.id},
|
|
).scalar_one()
|
|
assert rom_count == 3
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert {table: _schema_of(connection, table) for table in tables} == before
|
|
|
|
|
|
def test_the_search_titles_revision_reverses_replays_and_fills(platform: Platform):
|
|
"""0146 swaps the search index and fills existing rows, resuming a partial run."""
|
|
migration = _load_migration("0146_roms_search_aliases.py")
|
|
first = make_rom(
|
|
platform, "Final Fantasy VII", igdb_metadata={"alternative_names": ["FF7"]}
|
|
)
|
|
second = make_rom(platform, "Chrono Trigger")
|
|
|
|
def titles(connection: sa.Connection) -> dict[int, str | None]:
|
|
rows = connection.execute(
|
|
sa.text("SELECT id, search_titles FROM roms WHERE id IN (:a, :b)"),
|
|
{"a": first.id, "b": second.id},
|
|
)
|
|
return dict(rows.all())
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "roms")
|
|
expected = titles(connection)
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "roms", SEARCH_TITLES_COLUMN)
|
|
indexes = _schema_of(connection, "roms")[1]
|
|
assert ROMS_SEARCH_FULLTEXT_INDEX not in indexes
|
|
assert ROMS_SEARCH_TITLES_TRGM_INDEX not in indexes
|
|
migration.downgrade()
|
|
|
|
migration.upgrade()
|
|
assert titles(connection) == expected
|
|
|
|
connection.execute(
|
|
sa.text("UPDATE roms SET search_titles = NULL WHERE id = :id"),
|
|
{"id": second.id},
|
|
)
|
|
migration.upgrade()
|
|
assert titles(connection) == expected
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
assert expected[first.id] == "\x1ffinal fantasy vii\x1fff7\x1f"
|
|
|
|
|
|
def test_the_rom_file_title_ids_revision_reverses_and_replays():
|
|
migration = _load_migration("0147_rom_file_title_ids.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "rom_files")
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
assert not has_column(connection, "rom_files", "converto_read_at")
|
|
assert not has_column(connection, "rom_files", "title_id")
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "rom_files") == before
|
|
|
|
|
|
def test_the_save_channels_revision_reverses_and_replays():
|
|
migration = _load_migration("0161_save_channels.py")
|
|
tables = ("saves", "states", "screenshots", "rom_files")
|
|
created = (
|
|
"channels",
|
|
"snapshots",
|
|
"snapshot_states",
|
|
"snapshot_pins",
|
|
"device_channel_sync",
|
|
)
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = {table: _schema_of(connection, table) for table in tables + created}
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
inspector = sa.inspect(connection)
|
|
assert not any(inspector.has_table(table) for table in created)
|
|
assert not has_column(connection, "saves", "identity_hash")
|
|
assert not has_column(connection, "states", "emulator_version")
|
|
assert not has_column(connection, "screenshots", "save_id")
|
|
for column in (
|
|
"raw_serial",
|
|
"sigil_features",
|
|
"n64_header",
|
|
"n64_md5",
|
|
"n64_md5_n64",
|
|
"playlist_title_ids",
|
|
):
|
|
assert not has_column(connection, "rom_files", column)
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
after = {table: _schema_of(connection, table) for table in tables + created}
|
|
|
|
assert after == before
|
|
|
|
|
|
def test_the_save_channels_revision_files_slotted_saves_under_channels(
|
|
rom: Rom, admin_user: User
|
|
):
|
|
migration = _load_migration("0161_save_channels.py")
|
|
db_rom_handler.add_rom_file(
|
|
RomFile(rom_id=rom.id, file_name="game.sfc", file_path="p", file_size_bytes=8)
|
|
)
|
|
autosave = make_save(rom, admin_user, "a.srm", slot="autosave")
|
|
tagged = make_save(rom, admin_user, "b.srm", slot="Run [2026-01-01_00-00-00]")
|
|
recased = make_save(rom, admin_user, "d.srm", slot="run [2026-02-01_00-00-00]")
|
|
backup = make_save(rom, admin_user, "c.srm", slot=None)
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(sa.text("UPDATE saves SET channel_id = NULL"))
|
|
connection.execute(sa.text("DELETE FROM channels"))
|
|
|
|
def links(connection: sa.Connection) -> dict[int, str | None]:
|
|
rows = connection.execute(
|
|
sa.text(
|
|
"SELECT s.id, c.label FROM saves s "
|
|
"LEFT JOIN channels c ON c.id = s.channel_id"
|
|
)
|
|
)
|
|
return dict(rows.all())
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
first = links(connection)
|
|
migration.upgrade()
|
|
channels: int = connection.execute(
|
|
sa.text("SELECT COUNT(*) FROM channels")
|
|
).scalar_one()
|
|
|
|
assert links(connection) == first
|
|
|
|
run_label = first[tagged.id]
|
|
assert run_label is not None and run_label.lower() == "run"
|
|
assert first == {
|
|
autosave.id: "default",
|
|
tagged.id: run_label,
|
|
recased.id: run_label,
|
|
backup.id: None,
|
|
}
|
|
assert channels == 2
|
|
|
|
|
|
def test_the_age_limits_revision_reverses_replays_and_fills(platform: Platform):
|
|
"""0148 rates existing ROMs and keeps mirroring the rating into roms_facets."""
|
|
migration = _load_migration("0148_rom_age_limits.py")
|
|
min_age_index = _load_migration("0156_roms_platform_min_age_index.py")
|
|
rated = make_rom(
|
|
platform,
|
|
"Rated",
|
|
igdb_metadata={"age_ratings": [{"category": "PEGI", "rating": "16"}]},
|
|
)
|
|
unrated = make_rom(platform, "Unrated")
|
|
|
|
def ages(connection: sa.Connection, table: str, key: str) -> dict[int, int | None]:
|
|
rows = connection.execute(
|
|
sa.text(
|
|
f"SELECT {key}, min_age FROM {table} WHERE {key} IN (:a, :b)"
|
|
), # nosec B608
|
|
{"a": rated.id, "b": unrated.id},
|
|
)
|
|
return dict(rows.all())
|
|
|
|
tables = ("roms", "roms_facets", "permission_groups", "users")
|
|
with sync_engine.begin() as connection:
|
|
before = {table: _schema_of(connection, table) for table in tables}
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
min_age_index.downgrade()
|
|
migration.downgrade()
|
|
assert not has_column(connection, "roms", "min_age")
|
|
assert not has_column(connection, "users", "age_limit")
|
|
migration.downgrade()
|
|
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
min_age_index.upgrade()
|
|
|
|
assert ages(connection, "roms", "id") == {rated.id: 16, unrated.id: None}
|
|
assert ages(connection, "roms_facets", "rom_id") == {
|
|
rated.id: 16,
|
|
unrated.id: None,
|
|
}
|
|
assert {table: _schema_of(connection, table) for table in tables} == before
|
|
|
|
# The rebuilt triggers still mirror a later write.
|
|
db_rom_handler.update_rom(
|
|
unrated.id,
|
|
{"ss_metadata": {"age_ratings": [{"category": "PEGI", "rating": "7"}]}},
|
|
)
|
|
with sync_engine.connect() as connection:
|
|
assert ages(connection, "roms_facets", "rom_id")[unrated.id] == 7
|
|
|
|
|
|
def _slot_collations(connection: sa.Connection) -> dict[str, str | None]:
|
|
inspector = sa.inspect(connection)
|
|
collations = {}
|
|
for table in ("saves", "deleted_assets"):
|
|
[slot_type] = [
|
|
column["type"]
|
|
for column in inspector.get_columns(table)
|
|
if column["name"] == "slot"
|
|
]
|
|
assert isinstance(slot_type, sa.String)
|
|
collations[table] = slot_type.collation
|
|
return collations
|
|
|
|
|
|
def test_save_slots_are_compared_exactly():
|
|
"""Both slot columns match as sync negotiation pairs them in Python."""
|
|
with sync_engine.connect() as connection:
|
|
expected = exact_collation(connection)
|
|
assert _slot_collations(connection) == {
|
|
"saves": expected,
|
|
"deleted_assets": expected,
|
|
}
|
|
|
|
|
|
def test_the_exact_save_slots_revision_reverses_and_replays():
|
|
migration = _load_migration("0138_exact_save_slots.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
exact = exact_collation(connection)
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
if exact is not None:
|
|
assert _slot_collations(connection)["saves"] != exact
|
|
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
assert _slot_collations(connection)["saves"] == exact
|
|
|
|
|
|
def test_the_exact_save_slots_revision_fixes_an_early_deleted_assets_table():
|
|
"""A deleted_assets slot left with the table's folding collation is made exact."""
|
|
migration = _load_migration("0138_exact_save_slots.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
exact = exact_collation(connection)
|
|
if exact is None:
|
|
pytest.skip("PostgreSQL compares slots exactly already")
|
|
with Operations.context(MigrationContext.configure(connection)) as op:
|
|
op.alter_column(
|
|
"deleted_assets",
|
|
"slot",
|
|
existing_type=sa.String(length=255),
|
|
type_=sa.String(length=255),
|
|
existing_nullable=False,
|
|
)
|
|
assert _slot_collations(connection)["deleted_assets"] != exact
|
|
|
|
migration.upgrade()
|
|
|
|
assert _slot_collations(connection)["deleted_assets"] == exact
|
|
|
|
|
|
def test_the_exact_save_slots_revision_rebuilds_no_table_already_exact():
|
|
"""A replay after a run that died partway skips the collations it finished."""
|
|
migration = _load_migration("0138_exact_save_slots.py")
|
|
statements: list[str] = []
|
|
|
|
with sync_engine.begin() as connection:
|
|
|
|
@sa.event.listens_for(connection, "before_cursor_execute")
|
|
def _record(_conn: Any, _cursor: Any, statement: str, *_args: Any) -> None:
|
|
if re.match(r"ALTER TABLE \S+ MODIFY", statement.lstrip(), re.I):
|
|
statements.append(statement)
|
|
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
|
|
assert statements == []
|
|
|
|
|
|
def test_the_rom_similarity_revision_fills_in_a_missing_index():
|
|
"""0122 meets its own table on a replay, with only some of its indexes.
|
|
|
|
Alembic issues those as their own statements after the table, so a run can
|
|
die between them.
|
|
"""
|
|
migration = _load_migration("0122_rom_similarity.py")
|
|
name, _ = migration.INDEXES[0]
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, migration.TABLE)
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
# The other one backs a foreign key, which MariaDB will not let go.
|
|
operations.drop_index(name, table_name=migration.TABLE)
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, migration.TABLE) == before
|
|
|
|
|
|
def test_the_memory_card_revision_replays_under_the_one_that_prunes_it():
|
|
"""0119 re-creates the index 0125 drops, so the pair has to replay together.
|
|
|
|
A real upgrade always runs 0125 after 0119; this pins that the second pass
|
|
still lands on the same schema.
|
|
"""
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "memory_card_versions")
|
|
_replay(connection, "0119_memory_cards.py")
|
|
_replay(connection, "0125_drop_redundant_indexes.py")
|
|
|
|
assert _schema_of(connection, "memory_card_versions") == before
|
|
|
|
|
|
def test_the_full_path_hash_migration_resumes_an_interrupted_run(rom: Rom):
|
|
"""0126 finishes a run that died right after its ADD COLUMN.
|
|
|
|
That run leaves the column with no digest, no NOT NULL and neither index.
|
|
"""
|
|
migration = _load_migration("0126_unique_rom_full_path.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
migration.downgrade()
|
|
operations.add_column(
|
|
"roms",
|
|
sa.Column(
|
|
migration.COLUMN_NAME, sa.String(length=FULL_PATH_HASH_LENGTH)
|
|
),
|
|
)
|
|
migration.upgrade()
|
|
|
|
columns, indexes = _schema_of(connection, "roms")
|
|
digest: str = connection.execute(
|
|
sa.text(
|
|
f"SELECT {migration.COLUMN_NAME} FROM roms WHERE id = :rom_id"
|
|
), # nosec B608
|
|
{"rom_id": rom.id},
|
|
).scalar_one()
|
|
|
|
assert not columns[migration.COLUMN_NAME]
|
|
assert indexes[migration.UNIQUE_INDEX_NAME][1]
|
|
assert not indexes[migration.LOOKUP_INDEX_NAME][1]
|
|
assert digest == compute_full_path_hash(rom.fs_path, rom.fs_name)
|
|
|
|
|
|
def test_the_hltb_migration_resumes_an_interrupted_run():
|
|
"""0128 keeps the generated column it already added and builds its index."""
|
|
migration = _load_migration("0128_hltb_main_story_column.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
operations.drop_index(migration.INDEX_NAME, table_name="roms")
|
|
migration.upgrade()
|
|
|
|
_, indexes = _schema_of(connection, "roms")
|
|
|
|
assert migration.INDEX_NAME in indexes
|
|
|
|
|
|
def test_has_column_reflects_the_migrated_schema():
|
|
"""The guard every replayed column add is skipped by."""
|
|
with sync_engine.connect() as connection:
|
|
assert has_column(connection, "roms", "generated_publishers")
|
|
assert not has_column(connection, "roms", "no_such_column")
|
|
|
|
|
|
def _roms_alters(connection: sa.Connection) -> list[str]:
|
|
"""Record every ALTER TABLE roms the connection issues from here on."""
|
|
statements: list[str] = []
|
|
|
|
@sa.event.listens_for(connection, "before_cursor_execute")
|
|
def _record(_conn: Any, _cursor: Any, statement: str, *_args: Any) -> None:
|
|
if re.match(r"ALTER TABLE roms\b", statement.lstrip(), re.IGNORECASE):
|
|
statements.append(statement)
|
|
|
|
return statements
|
|
|
|
|
|
def _generation_expressions(connection: sa.Connection) -> dict[str, str]:
|
|
"""The expression behind every generated column on `roms`."""
|
|
return {
|
|
column["name"]: column["computed"]["sqltext"]
|
|
for column in sa.inspect(connection).get_columns("roms")
|
|
if column.get("computed")
|
|
}
|
|
|
|
|
|
def test_the_roms_columns_helper_leaves_a_migrated_table_alone():
|
|
"""Every revision calls it, so all but the first must cost nothing."""
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "roms")
|
|
alters = _roms_alters(connection)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
assert alters == []
|
|
|
|
|
|
def test_the_roms_columns_helper_adds_every_missing_column_at_once():
|
|
"""A stored and a generated column missing together cost one table copy."""
|
|
hltb = _load_migration("0128_hltb_main_story_column.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "roms")
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
operations.drop_index(hltb.INDEX_NAME, table_name="roms")
|
|
operations.drop_column("roms", "upc")
|
|
operations.drop_column("roms", HLTB_MAIN_STORY_COLUMN)
|
|
alters = _roms_alters(connection)
|
|
|
|
ensure_roms_columns(connection)
|
|
# 0128 owns the index, so its replay finishes the schema.
|
|
_replay(connection, "0128_hltb_main_story_column.py")
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
assert len(alters) == 1
|
|
|
|
|
|
def test_the_roms_columns_helper_rebuilds_a_narrowed_sort_index():
|
|
"""PostgreSQL drops a `_sort` index with its column; MariaDB narrows it."""
|
|
# `roms_metadata` does not project this one, so PostgreSQL lets it go
|
|
# without the view being dropped first.
|
|
column = HLTB_MAIN_STORY_COLUMN
|
|
spanned = (rom_unset_flag_column(column), column, "id")
|
|
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(sa.text(f"ALTER TABLE roms DROP COLUMN {column}"))
|
|
assert _schema_of(connection, "roms")[1].get(rom_sort_index_name(column)) != (
|
|
spanned,
|
|
False,
|
|
)
|
|
|
|
ensure_roms_columns(connection)
|
|
# 0128 owns the value column's own index, so its replay finishes the schema.
|
|
_replay(connection, "0128_hltb_main_story_column.py")
|
|
|
|
assert _schema_of(connection, "roms")[1][rom_sort_index_name(column)] == (
|
|
spanned,
|
|
False,
|
|
)
|
|
|
|
|
|
def test_the_roms_columns_helper_rebuilds_the_search_index_with_the_titles_column():
|
|
"""A rebuild of the titles column must not leave the gallery search unindexed."""
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "roms")
|
|
connection.execute(
|
|
sa.text(f"ALTER TABLE roms DROP COLUMN {SEARCH_TITLES_COLUMN}")
|
|
)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
|
|
|
|
def test_dropping_the_roms_columns_takes_the_sort_indexes_with_them():
|
|
"""A descending sort index reads an inherited column, so nothing else drops it."""
|
|
# Those indexes are PostgreSQL's alone, and only its DDL rolls back, which
|
|
# is what keeps this teardown out of the schema the other tests share.
|
|
with sync_engine.connect() as connection:
|
|
if not is_postgresql(connection):
|
|
pytest.skip("descending sort indexes are PostgreSQL-only")
|
|
|
|
transaction = connection.begin()
|
|
try:
|
|
descending = {
|
|
rom_desc_index_name(column) for column in SORTABLE_NULLABLE_ROM_COLUMNS
|
|
}
|
|
assert descending <= set(_schema_of(connection, "roms")[1])
|
|
|
|
drop_roms_columns(connection)
|
|
|
|
assert descending & set(_schema_of(connection, "roms")[1]) == set()
|
|
finally:
|
|
transaction.rollback()
|
|
|
|
|
|
def test_the_roms_columns_helper_redefines_a_column_that_predates_steam():
|
|
"""0123 taught the metadata chains to read Steam; an older table is rebuilt."""
|
|
with sync_engine.begin() as connection:
|
|
pg = is_postgresql(connection)
|
|
before = _schema_of(connection, "roms")
|
|
genres = next(
|
|
column
|
|
for column in steam_fed_columns(pg, with_steam=False)
|
|
if column.name == "generated_genres"
|
|
)
|
|
rebuild_generated_columns(
|
|
connection,
|
|
add=[genres],
|
|
drop=[],
|
|
view_columns=ROMS_METADATA_VIEW_COLUMNS,
|
|
)
|
|
assert (
|
|
STEAM_METADATA_COLUMN
|
|
not in _generation_expressions(connection)["generated_genres"]
|
|
)
|
|
alters = _roms_alters(connection)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
assert len(alters) == 1
|
|
expressions = _generation_expressions(connection)
|
|
for column in STEAM_FED_COLUMNS:
|
|
assert STEAM_METADATA_COLUMN in expressions[column]
|
|
assert sa.inspect(connection).has_table("roms_metadata")
|
|
|
|
|
|
def _roms_schema(
|
|
connection: sa.Connection,
|
|
) -> tuple[TableSchema, dict[str, str], list[str]]:
|
|
"""`_schema_of` plus every generated expression and what the view projects."""
|
|
view = sa.inspect(connection).get_columns("roms_metadata")
|
|
return (
|
|
_schema_of(connection, "roms"),
|
|
_generation_expressions(connection),
|
|
[column["name"] for column in view],
|
|
)
|
|
|
|
|
|
def test_the_first_roms_columns_revision_downgrades_to_the_schema_it_found():
|
|
"""0108 adds every later revision's column, so alone it has to take them all back."""
|
|
migration = _load_migration("0126_unique_rom_full_path.py")
|
|
|
|
alembic.config.main(argv=["downgrade", "0107_roms_dedup_cover_index"])
|
|
try:
|
|
with sync_engine.connect() as connection:
|
|
before = _roms_schema(connection)
|
|
|
|
alembic.config.main(argv=["upgrade", "0108_roms_primary_region"])
|
|
# 0126 creates this before it is stamped, so a run that died right
|
|
# after leaves it for the downgrade to meet.
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)) as ops:
|
|
ops.create_index(
|
|
migration.UNIQUE_INDEX_NAME,
|
|
"roms",
|
|
["platform_id", FULL_PATH_HASH_COLUMN],
|
|
unique=True,
|
|
)
|
|
alembic.config.main(argv=["downgrade", "0107_roms_dedup_cover_index"])
|
|
|
|
with sync_engine.connect() as connection:
|
|
after = _roms_schema(connection)
|
|
finally:
|
|
alembic.config.main(argv=["upgrade", "head"])
|
|
|
|
assert after == before
|
|
|
|
|
|
def test_the_roms_columns_helper_puts_back_a_view_a_run_lost():
|
|
"""A run that died between the ALTER and the CREATE VIEW replays to the view."""
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(sa.text("DROP VIEW roms_metadata"))
|
|
alters = _roms_alters(connection)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
assert sa.inspect(connection).has_table("roms_metadata")
|
|
assert alters == []
|
|
|
|
|
|
def test_the_roms_columns_helper_drops_a_digest_default_a_run_left_behind():
|
|
"""MariaDB fills the digest through a DEFAULT the run removes right after."""
|
|
with sync_engine.begin() as connection:
|
|
if not is_mariadb(connection):
|
|
pytest.skip("only MariaDB gives the column a default")
|
|
connection.execute(
|
|
sa.text(
|
|
f"ALTER TABLE roms ALTER COLUMN {FULL_PATH_HASH_COLUMN} SET DEFAULT ''"
|
|
)
|
|
)
|
|
assert has_server_default(connection, FULL_PATH_HASH_COLUMN)
|
|
alters = _roms_alters(connection)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
assert not has_server_default(connection, FULL_PATH_HASH_COLUMN)
|
|
assert len(alters) == 1
|
|
|
|
|
|
def test_the_roms_columns_helper_fills_the_full_path_digest_where_it_can(rom: Rom):
|
|
"""MariaDB gets the digest in the same copy; the others leave it to 0126."""
|
|
migration = _load_migration("0126_unique_rom_full_path.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
before = _schema_of(connection, "roms")
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
operations.drop_index(migration.UNIQUE_INDEX_NAME, table_name="roms")
|
|
operations.drop_column("roms", FULL_PATH_HASH_COLUMN)
|
|
|
|
ensure_roms_columns(connection)
|
|
|
|
columns, _ = _schema_of(connection, "roms")
|
|
assert columns[FULL_PATH_HASH_COLUMN] is not is_mariadb(connection)
|
|
assert not has_server_default(connection, FULL_PATH_HASH_COLUMN)
|
|
if is_mariadb(connection):
|
|
digest: str = connection.execute(
|
|
sa.text(
|
|
f"SELECT {FULL_PATH_HASH_COLUMN} FROM roms WHERE id = :rom_id" # nosec B608
|
|
),
|
|
{"rom_id": rom.id},
|
|
).scalar_one()
|
|
assert digest == compute_full_path_hash(rom.fs_path, rom.fs_name)
|
|
|
|
migration.upgrade()
|
|
|
|
assert _schema_of(connection, "roms") == before
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"drop_column",
|
|
[False, True],
|
|
ids=["died before the index", "died before the column"],
|
|
)
|
|
def test_the_state_disc_file_migration_resumes_an_interrupted_run(drop_column: bool):
|
|
"""0121 completes whatever a run that died partway left behind.
|
|
|
|
Nothing else in the schema references these, so the interrupted states can
|
|
be built for real: the foreign key and index missing, or all three.
|
|
"""
|
|
migration = _load_migration("0121_state_disc_file.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)) as operations:
|
|
# The foreign key goes first: MariaDB refuses to drop a column it
|
|
# still needs, and an index it still sits on.
|
|
operations.drop_constraint(
|
|
"fk_states_disc_file_id", "states", type_="foreignkey"
|
|
)
|
|
operations.drop_index("ix_states_disc_file_id", table_name="states")
|
|
if drop_column:
|
|
operations.drop_column("states", "disc_file_id")
|
|
|
|
migration.upgrade()
|
|
|
|
inspector = sa.inspect(connection)
|
|
columns = {column["name"] for column in inspector.get_columns("states")}
|
|
index = inspector.has_index("states", "ix_states_disc_file_id")
|
|
foreign_keys = {key["name"] for key in inspector.get_foreign_keys("states")}
|
|
|
|
assert "disc_file_id" in columns
|
|
assert index
|
|
assert "fk_states_disc_file_id" in foreign_keys
|
|
|
|
|
|
def _is_system_sql(connection: sa.Connection) -> str:
|
|
# Before 0137 the seeded groups are flagged by `is_system`, after it by a key.
|
|
if has_column(connection, "permission_groups", "system_key"):
|
|
return "system_key IS NOT NULL"
|
|
return "is_system"
|
|
|
|
|
|
def _system_groups(connection: sa.Connection) -> dict[str, str]:
|
|
rows = connection.execute(
|
|
sa.text(
|
|
"SELECT name, description FROM permission_groups "
|
|
f"WHERE {_is_system_sql(connection)}"
|
|
)
|
|
)
|
|
return {name: description for name, description in rows}
|
|
|
|
|
|
def _system_keys(connection: sa.Connection) -> dict[str, str]:
|
|
rows = connection.execute(
|
|
sa.text(
|
|
"SELECT system_key, name FROM permission_groups "
|
|
"WHERE system_key IS NOT NULL"
|
|
)
|
|
)
|
|
return {key: name for key, name in rows}
|
|
|
|
|
|
GROUP_RENAME = _load_migration("0137_rename_system_groups.py")
|
|
|
|
|
|
def _upgrade_group_rename(connection: sa.Connection) -> None:
|
|
# MariaDB commits the column DDL implicitly, so tests restore head by hand
|
|
# rather than rolling back.
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
GROUP_RENAME.upgrade()
|
|
connection.commit()
|
|
|
|
|
|
def test_the_group_rename_round_trips_the_seeded_groups():
|
|
with sync_engine.connect() as connection:
|
|
renamed = _system_groups(connection)
|
|
try:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
GROUP_RENAME.downgrade()
|
|
legacy = _system_groups(connection)
|
|
finally:
|
|
_upgrade_group_rename(connection)
|
|
replayed = _system_groups(connection)
|
|
keys = _system_keys(connection)
|
|
flag_dropped = not has_column(connection, "permission_groups", "is_system")
|
|
|
|
assert set(renamed) == {"Viewer", "Editor"}
|
|
assert set(legacy) == {"Viewer (legacy)", "Editor (legacy)"}
|
|
assert "pre-upgrade" in legacy["Viewer (legacy)"]
|
|
assert replayed == renamed
|
|
assert keys == {"viewer": "Viewer", "editor": "Editor"}
|
|
assert flag_dropped
|
|
|
|
|
|
def test_the_group_rename_leaves_admin_changes_alone():
|
|
"""A taken name skips that group, and an edited description survives."""
|
|
with sync_engine.connect() as connection:
|
|
try:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
GROUP_RENAME.downgrade()
|
|
legacy = _system_groups(connection)
|
|
connection.execute(
|
|
sa.text(
|
|
"INSERT INTO permission_groups "
|
|
"(name, description, is_default, is_system, created_at, updated_at) "
|
|
"VALUES ('Viewer', '', false, false, "
|
|
"CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
|
)
|
|
)
|
|
connection.execute(
|
|
sa.text(
|
|
"UPDATE permission_groups SET description = 'Custom' "
|
|
"WHERE name = 'Editor (legacy)'"
|
|
)
|
|
)
|
|
_upgrade_group_rename(connection)
|
|
groups = _system_groups(connection)
|
|
keys = _system_keys(connection)
|
|
finally:
|
|
_, _, _, _, editor_description = GROUP_RENAME.RENAMES[1]
|
|
connection.execute(
|
|
sa.text(
|
|
"DELETE FROM permission_groups "
|
|
f"WHERE name = 'Viewer' AND NOT ({_is_system_sql(connection)})"
|
|
)
|
|
)
|
|
connection.execute(
|
|
sa.text(
|
|
"UPDATE permission_groups SET description = :description "
|
|
f"WHERE {_is_system_sql(connection)} AND description = 'Custom'"
|
|
),
|
|
{"description": editor_description},
|
|
)
|
|
_upgrade_group_rename(connection)
|
|
|
|
assert groups == {
|
|
"Viewer (legacy)": legacy["Viewer (legacy)"],
|
|
"Editor": "Custom",
|
|
}
|
|
assert keys == {"viewer": "Viewer (legacy)", "editor": "Editor"}
|
|
|
|
|
|
def test_the_sibling_platform_names_revision_renames_only_the_stale_name():
|
|
migration = _load_migration("0143_sibling_platform_names.py")
|
|
for name, slug, fs_slug in (
|
|
("Commodore 64", "c128", "c128"),
|
|
("Videopac G7000", "videopac-g7400", "videopac-g7400"),
|
|
("Commodore 64", "c64", "c64"),
|
|
("C128 (custom)", "c128", "c128-custom"),
|
|
):
|
|
make_platform(slug, name=name, fs_slug=fs_slug)
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
names = set(
|
|
connection.execute(sa.text("SELECT fs_slug, name FROM platforms")).all()
|
|
)
|
|
|
|
assert names == {
|
|
("c128", "Commodore 128"),
|
|
("videopac-g7400", "Videopac+ G7400"),
|
|
("c64", "Commodore 64"),
|
|
("c128-custom", "C128 (custom)"),
|
|
}
|
|
|
|
|
|
def test_the_retired_arcade_slugs_revision_moves_boards_to_arcade_and_back():
|
|
migration = _load_migration("0155_retired_arcade_slugs.py")
|
|
for slug, fs_slug in (
|
|
("cps2", "cps2"),
|
|
("CPS3", "CPS3"),
|
|
("system16", "sega16"),
|
|
("arcade", "arcade"),
|
|
("snes", "snes"),
|
|
):
|
|
make_platform(slug, fs_slug=fs_slug)
|
|
|
|
def slugs(connection: sa.Connection) -> set[tuple[str, str]]:
|
|
return set(connection.execute(sa.text("SELECT fs_slug, slug FROM platforms")))
|
|
|
|
with sync_engine.begin() as connection:
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
upgraded = slugs(connection)
|
|
migration.downgrade()
|
|
downgraded = slugs(connection)
|
|
|
|
assert upgraded == {
|
|
("cps2", "arcade"),
|
|
("CPS3", "arcade"),
|
|
("sega16", "arcade"),
|
|
("arcade", "arcade"),
|
|
("snes", "snes"),
|
|
}
|
|
assert downgraded == {
|
|
("cps2", "cps2"),
|
|
("CPS3", "cps3"),
|
|
("sega16", "arcade"),
|
|
("arcade", "arcade"),
|
|
("snes", "snes"),
|
|
}
|
|
|
|
|
|
_GROUPS = sa.table(
|
|
"permission_groups",
|
|
sa.column("id", sa.Integer),
|
|
sa.column("name", sa.String),
|
|
sa.column("description", sa.String),
|
|
sa.column("is_default", sa.Boolean),
|
|
sa.column("hide_unrated_roms", sa.Boolean),
|
|
)
|
|
_GRANTS = sa.table(
|
|
"permission_group_grants",
|
|
sa.column("group_id", sa.Integer),
|
|
sa.column("entity", sa.String),
|
|
sa.column("action", sa.String),
|
|
sa.column("own_only", sa.Boolean),
|
|
)
|
|
_OVERRIDES = sa.table(
|
|
"user_permission_overrides",
|
|
sa.column("user_id", sa.Integer),
|
|
sa.column("entity", sa.String),
|
|
sa.column("action", sa.String),
|
|
sa.column("granted", sa.Boolean),
|
|
sa.column("own_only", sa.Boolean),
|
|
)
|
|
|
|
|
|
_PLAY_ENTITIES = ("streaming", "emulation")
|
|
|
|
|
|
def _play_grants(connection: sa.Connection) -> set[tuple[int, str, str, bool]]:
|
|
return {
|
|
(row.group_id, row.entity, row.action, bool(row.own_only))
|
|
for row in connection.execute(
|
|
sa.select(
|
|
_GRANTS.c.group_id,
|
|
_GRANTS.c.entity,
|
|
_GRANTS.c.action,
|
|
_GRANTS.c.own_only,
|
|
).where(_GRANTS.c.entity.in_(_PLAY_ENTITIES))
|
|
)
|
|
}
|
|
|
|
|
|
def _play_overrides(connection: sa.Connection) -> int:
|
|
return connection.execute(
|
|
sa.select(sa.func.count())
|
|
.select_from(_OVERRIDES)
|
|
.where(_OVERRIDES.c.entity.in_(_PLAY_ENTITIES))
|
|
).scalar_one()
|
|
|
|
|
|
def test_the_play_permissions_revision_backfills_reverses_and_replays(
|
|
admin_user: User,
|
|
):
|
|
"""0153 grants streaming and emulation to every existing group and downgrades cleanly."""
|
|
migration = _load_migration("0153_play_permissions.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(
|
|
_GROUPS.insert().values(
|
|
name="Locked down",
|
|
description="",
|
|
is_default=False,
|
|
hide_unrated_roms=False,
|
|
)
|
|
)
|
|
connection.execute(
|
|
_OVERRIDES.insert(),
|
|
[
|
|
{
|
|
"user_id": admin_user.id,
|
|
"entity": entity,
|
|
"action": "write",
|
|
"granted": False,
|
|
"own_only": False,
|
|
}
|
|
for entity in _PLAY_ENTITIES
|
|
],
|
|
)
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
migration.downgrade()
|
|
assert _play_grants(connection) == set()
|
|
assert _play_overrides(connection) == 0
|
|
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
group_ids: set[int] = set(connection.execute(sa.select(_GROUPS.c.id)).scalars())
|
|
assert len(group_ids) >= 3
|
|
assert _play_grants(connection) == {
|
|
(group_id, entity, action, False)
|
|
for group_id in group_ids
|
|
for entity in _PLAY_ENTITIES
|
|
for action in ("read", "write")
|
|
}
|
|
connection.execute(_GROUPS.delete().where(_GROUPS.c.name == "Locked down"))
|
|
|
|
|
|
def test_the_ownerless_own_only_revision_keeps_each_rows_access(admin_user: User):
|
|
"""0154 rewrites own_only on owner-less entities to the access it gave."""
|
|
migration = _load_migration("0154_ownerless_own_only.py")
|
|
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(
|
|
_GROUPS.insert().values(
|
|
name="Legacy own",
|
|
description="",
|
|
is_default=False,
|
|
hide_unrated_roms=False,
|
|
)
|
|
)
|
|
group_id: int = connection.execute(
|
|
sa.select(_GROUPS.c.id).where(_GROUPS.c.name == "Legacy own")
|
|
).scalar_one()
|
|
connection.execute(
|
|
_GRANTS.insert(),
|
|
[
|
|
{"group_id": group_id, "entity": e, "action": a, "own_only": True}
|
|
for e, a in (
|
|
("users", "write"),
|
|
("users", "delete"),
|
|
("collections", "delete"),
|
|
)
|
|
],
|
|
)
|
|
connection.execute(
|
|
_OVERRIDES.insert(),
|
|
[
|
|
{
|
|
"user_id": admin_user.id,
|
|
"entity": e,
|
|
"action": a,
|
|
"granted": granted,
|
|
"own_only": True,
|
|
}
|
|
for e, a, granted in (
|
|
("tasks", "write", True),
|
|
("tasks", "delete", True),
|
|
("logs", "read", False),
|
|
("devices", "write", True),
|
|
)
|
|
],
|
|
)
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.upgrade()
|
|
migration.upgrade()
|
|
|
|
grants = {
|
|
(row.entity, row.action, bool(row.own_only))
|
|
for row in connection.execute(
|
|
sa.select(_GRANTS).where(_GRANTS.c.group_id == group_id)
|
|
)
|
|
}
|
|
overrides = {
|
|
(row.entity, row.action, bool(row.granted), bool(row.own_only))
|
|
for row in connection.execute(
|
|
sa.select(_OVERRIDES).where(_OVERRIDES.c.user_id == admin_user.id)
|
|
)
|
|
}
|
|
connection.execute(_GROUPS.delete().where(_GROUPS.c.id == group_id))
|
|
connection.execute(
|
|
_OVERRIDES.delete().where(_OVERRIDES.c.user_id == admin_user.id)
|
|
)
|
|
|
|
assert grants == {("users", "write", False), ("collections", "delete", True)}
|
|
assert overrides == {
|
|
("tasks", "write", True, False),
|
|
("tasks", "delete", False, False),
|
|
("logs", "read", False, False),
|
|
("devices", "write", True, True),
|
|
}
|
|
|
|
|
|
def test_the_custom_sort_key_revision_flags_keys_no_name_derives(
|
|
platform: Platform,
|
|
):
|
|
"""0157 marks a key custom when the legacy rule would not derive it."""
|
|
migration = _load_migration("0157_rom_custom_sort_key_flag.py")
|
|
derived = make_rom(platform, "Die Hard Arcade")
|
|
english = make_rom(platform, "Die Siedler")
|
|
custom = make_rom(platform, "Le Mans 24 Hours")
|
|
|
|
with sync_engine.begin() as connection:
|
|
connection.execute(
|
|
sa.text("UPDATE roms SET name_sort_key = :key WHERE id = :id"),
|
|
[
|
|
# Derived by the multilingual rule, and by 0084's English one.
|
|
{"id": derived.id, "key": "hard arcade"},
|
|
{"id": english.id, "key": "die siedler"},
|
|
{"id": custom.id, "key": "mans le 000000000024 hours"},
|
|
],
|
|
)
|
|
with Operations.context(MigrationContext.configure(connection)):
|
|
migration.downgrade()
|
|
migration.upgrade()
|
|
|
|
flags: dict[int, bool] = dict(
|
|
connection.execute(
|
|
sa.text(
|
|
"SELECT id, name_sort_key_custom FROM roms WHERE id IN (:a, :b, :c)"
|
|
),
|
|
{"a": derived.id, "b": english.id, "c": custom.id},
|
|
).all()
|
|
)
|
|
assert not flags[derived.id]
|
|
assert not flags[english.id]
|
|
assert flags[custom.id]
|
|
|
|
|
|
def test_the_sort_key_backfill_keeps_its_original_rule(mocker):
|
|
"""0084 fills keys the way it always has, whatever the configured articles."""
|
|
migration = _load_migration("0084_add_roms_search_index.py")
|
|
mocker.patch.object(cm.config, "SORT_ARTICLES", ["der", "die", "das"])
|
|
|
|
assert migration._sort_key("Die Hard Arcade") == "die hard arcade"
|
|
assert (
|
|
migration._sort_key("The Legend of Zelda 2") == "legend of zelda 000000000002"
|
|
)
|