From c3b32a77100e90b273e32fc2b4e28c71d3a2d000 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Mon, 7 Sep 2026 14:04:01 +0000 Subject: [PATCH] fix(backend): make the 0122 downgrade work on MariaDB, and trim comments Adding a composite index that leads with a foreign-key column lets InnoDB re-point the constraint at it and discard the implicit single-column index. Reversing 0122 then failed with "Cannot drop index 'ix_rom_user_user_rom': needed in a foreign key constraint" on `rom_user.user_id`, and would have on `screenshots.rom_id`. The downgrade now restores those two implicit indexes first, and a full up/down/up cycle leaves the schema byte-identical to a database that never ran the migration. Also sets `path_separator = os` in alembic.ini, silencing the deprecation warning about the legacy space/comma/colon path splitting. `prepend_sys_path` holds a single entry, so the behaviour is unchanged. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF --- backend/alembic.ini | 5 +++++ backend/alembic/env.py | 4 +--- .../versions/0122_gallery_and_fk_indexes.py | 18 +++++++++++++++++- backend/models/assets.py | 3 +-- backend/models/collection.py | 10 ++-------- backend/models/device.py | 1 - backend/models/platform.py | 5 +---- backend/models/play_session.py | 3 +-- backend/models/rom.py | 10 +++------- backend/utils/database.py | 8 +++----- 10 files changed, 34 insertions(+), 33 deletions(-) diff --git a/backend/alembic.ini b/backend/alembic.ini index 78c10646c..f46e869a9 100644 --- a/backend/alembic.ini +++ b/backend/alembic.ini @@ -10,6 +10,11 @@ script_location = alembic # for all available tokens # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# character used to split the path lists in this file (prepend_sys_path, +# version_locations). Without it alembic warns and falls back to splitting on +# spaces, commas and colons. +path_separator = os + # sys.path path, will be prepended to sys.path if present. # defaults to the current working directory. prepend_sys_path = . diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 35af9ceef..07308280b 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -55,9 +55,7 @@ def include_object(object, name, type_, reflected, compare_to): ]: # Virtual table return False - # Dialect-specific indexes no model can declare: the per-backend search - # indexes, and the PostgreSQL-only foreign-key indexes that MariaDB/MySQL - # already provide implicitly. + # Dialect-specific indexes that no model can declare. if type_ == "index" and name in AUTOGENERATE_EXEMPT_INDEX_NAMES: return False diff --git a/backend/alembic/versions/0122_gallery_and_fk_indexes.py b/backend/alembic/versions/0122_gallery_and_fk_indexes.py index ae3f9f729..9e48d4435 100644 --- a/backend/alembic/versions/0122_gallery_and_fk_indexes.py +++ b/backend/alembic/versions/0122_gallery_and_fk_indexes.py @@ -50,6 +50,13 @@ PORTABLE_INDEXES = ( ("roms", "idx_roms_platform_name_sort_key", ["platform_id", "name_sort_key"]), ) +# Implicit MariaDB/MySQL foreign-key indexes that the composites above absorb, +# named as InnoDB names them. Only needed to reverse this migration. +DISPLACED_FK_INDEXES = ( + ("screenshots", "rom_id", ["rom_id"]), + ("rom_user", "user_id", ["user_id"]), +) + def upgrade() -> None: for table, name, columns in PORTABLE_INDEXES: @@ -61,9 +68,18 @@ def upgrade() -> None: def downgrade() -> None: - if is_postgresql(op.get_bind()): + bind = op.get_bind() + + if is_postgresql(bind): for table, name, _columns in reversed(POSTGRESQL_FK_INDEXES): op.drop_index(name, table_name=table, if_exists=True) + else: + # Adding a composite that leads with a foreign-key column lets InnoDB + # re-point the constraint at it and discard the implicit single-column + # index. Put those back before dropping the composites, or the drop + # fails with "needed in a foreign key constraint". + for table, name, columns in DISPLACED_FK_INDEXES: + op.create_index(name, table, columns, unique=False, if_not_exists=True) for table, name, _columns in reversed(PORTABLE_INDEXES): op.drop_index(name, table_name=table, if_exists=True) diff --git a/backend/models/assets.py b/backend/models/assets.py index b15e9ff1d..0f368c2cd 100644 --- a/backend/models/assets.py +++ b/backend/models/assets.py @@ -71,8 +71,7 @@ class RomAsset(BaseAsset): class Screenshot(RomAsset): __tablename__ = "screenshots" __table_args__ = ( - # `Save.screenshot` / `State.screenshot` resolve a thumbnail per row, so - # this lookup runs once per card on the continue-playing rail. + # `Save.screenshot` / `State.screenshot` hit this once per rendered card. Index("ix_screenshots_rom_user", "rom_id", "user_id"), Index("idx_screenshots_public", "is_public"), {"extend_existing": True}, diff --git a/backend/models/collection.py b/backend/models/collection.py index a43f5e035..acf7920c4 100644 --- a/backend/models/collection.py +++ b/backend/models/collection.py @@ -19,10 +19,7 @@ if TYPE_CHECKING: class Collection(BaseModel): __tablename__ = "collections" - __table_args__ = ( - # Incremental sync (`updated_after`) for the mobile/device clients. - Index("ix_collections_updated_at", "updated_at"), - ) + __table_args__ = (Index("ix_collections_updated_at", "updated_at"),) id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) @@ -212,10 +209,7 @@ SMART_COLLECTION_MAX_COVERS = 5 class SmartCollection(BaseModel): __tablename__ = "smart_collections" - __table_args__ = ( - # Incremental sync (`updated_after`) for the mobile/device clients. - Index("ix_smart_collections_updated_at", "updated_at"), - ) + __table_args__ = (Index("ix_smart_collections_updated_at", "updated_at"),) id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) diff --git a/backend/models/device.py b/backend/models/device.py index 852397013..db6f18047 100644 --- a/backend/models/device.py +++ b/backend/models/device.py @@ -42,7 +42,6 @@ KNOWN_DEVICES: dict[str, DeviceType] = { class Device(BaseModel): __tablename__ = "devices" __table_args__ = ( - # Dedupes re-registrations of the same physical device. Index( "ix_devices_user_client_identifier", "user_id", diff --git a/backend/models/platform.py b/backend/models/platform.py index 8f42a5488..b7c15b591 100644 --- a/backend/models/platform.py +++ b/backend/models/platform.py @@ -22,10 +22,7 @@ DESCRIPTION_MAX_LENGTH = 65535 # TEXT class Platform(BaseModel): __tablename__ = "platforms" - __table_args__ = ( - # Incremental sync (`updated_after`) for the mobile/device clients. - Index("ix_platforms_updated_at", "updated_at"), - ) + __table_args__ = (Index("ix_platforms_updated_at", "updated_at"),) id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) igdb_id: Mapped[int | None] = mapped_column(Integer(), default=None) diff --git a/backend/models/play_session.py b/backend/models/play_session.py index 0b7f19bf3..d4f3f8879 100644 --- a/backend/models/play_session.py +++ b/backend/models/play_session.py @@ -25,8 +25,7 @@ if TYPE_CHECKING: class PlaySession(BaseModel): __tablename__ = "play_sessions" __table_args__ = ( - # A unique index rather than a unique constraint, matching how 0076 - # created it. Both enforce the same rule. + # A unique index, not a UniqueConstraint: that is what the schema has. Index( "uq_play_session_identity", "user_id", diff --git a/backend/models/rom.py b/backend/models/rom.py index 1c76e6101..7631501d5 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -547,9 +547,7 @@ class Rom(BaseModel): ), Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"), Index("idx_roms_missing_from_fs", "missing_from_fs", "name_sort_key"), - # The gallery is browsed one platform at a time and sorted by name, so - # the platform predicate and the sort have to come off one index or the - # whole platform is filesorted on every page. + # Serves the per-platform gallery page: predicate and sort in one index. Index("idx_roms_platform_name_sort_key", "platform_id", "name_sort_key"), Index("idx_roms_name", "name"), Index("idx_roms_name_sort_key", "name_sort_key"), @@ -579,7 +577,6 @@ class Rom(BaseModel): Index("idx_roms_md5_hash", "md5_hash"), Index("idx_roms_sha1_hash", "sha1_hash"), Index("idx_roms_ra_hash", "ra_hash"), - # Incremental sync (`updated_after`) for the mobile/device clients. Index("ix_roms_updated_at", "updated_at"), ) @@ -1136,9 +1133,8 @@ class RomUser(BaseModel): __tablename__ = "rom_user" __table_args__ = ( UniqueConstraint("rom_id", "user_id", name="unique_rom_user_props"), - # `unique_rom_user_props` covers the gallery's outer join, which drives - # from `roms`. These cover the other direction: scoping or sorting the - # gallery by a per-user column starts from this table instead. + # `unique_rom_user_props` leads with `rom_id` and so only covers the + # gallery's outer join; these cover starting from this table instead. Index("ix_rom_user_user_rom", "user_id", "rom_id"), Index("ix_rom_user_user_last_played", "user_id", "last_played"), ) diff --git a/backend/utils/database.py b/backend/utils/database.py index 7e3b67277..bdf47518d 100644 --- a/backend/utils/database.py +++ b/backend/utils/database.py @@ -7,9 +7,8 @@ from sqlalchemy.orm import Session from sqlalchemy.sql import ColumnElement, func # Foreign-key columns that MariaDB/MySQL index implicitly but PostgreSQL does -# not, so migration 0122 creates them there only. Shared with `alembic/env.py`, -# which hides them from autogenerate: a model declaration would give the other -# backends a duplicate index. +# not, so 0122 creates them there only. A model declaration would give the +# other backends a duplicate, hence the autogenerate exemption below. POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, list[str]], ...] = ( ("collections", "ix_collections_user_id", ["user_id"]), ("smart_collections", "ix_smart_collections_user_id", ["user_id"]), @@ -33,8 +32,7 @@ DIALECT_SEARCH_INDEX_NAMES = frozenset( } ) -# Indexes that exist in some databases but cannot be declared on a model, so -# autogenerate must not propose creating or dropping them. +# Indexes that exist in some databases but cannot be declared on a model. AUTOGENERATE_EXEMPT_INDEX_NAMES = ( DIALECT_SEARCH_INDEX_NAMES | POSTGRESQL_FK_INDEX_NAMES )