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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgeQBXh6SJyxXVHSL5EuoF
This commit is contained in:
Sam Dornan
2026-09-07 14:04:01 +00:00
committed by Claude
parent 0ec3e5a22a
commit c3b32a7710
10 changed files with 34 additions and 33 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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