diff --git a/backend/alembic/versions/0068_save_sync.py b/backend/alembic/versions/0068_save_sync.py index fad22deb0..0936ae0a2 100644 --- a/backend/alembic/versions/0068_save_sync.py +++ b/backend/alembic/versions/0068_save_sync.py @@ -9,6 +9,8 @@ Create Date: 2026-01-17 import sqlalchemy as sa from alembic import op +from utils.database import is_postgresql + revision = "0068_save_sync" down_revision = "0067_romfile_category_enum_cheat" branch_labels = None @@ -103,16 +105,40 @@ def upgrade(): def downgrade(): + conn = op.get_bind() + fk_names: list[str] = [] + + if not is_postgresql(conn): + # MariaDB won't let us drop an index that backs a FK constraint, so we + # need to temporarily drop the FK on saves.rom_id first. + fk_rows = conn.execute( + sa.text( + "SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE " + "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'saves' " + "AND COLUMN_NAME = 'rom_id' AND REFERENCED_TABLE_NAME IS NOT NULL" + ) + ).fetchall() + fk_names = [row[0] for row in fk_rows] + for fk_name in fk_names: + op.drop_constraint(fk_name, "saves", type_="foreignkey") + op.drop_index("ix_saves_rom_user_hash", "saves", if_exists=True) op.drop_index("ix_saves_slot", "saves", if_exists=True) - op.drop_index("ix_device_save_sync_save_id", "device_save_sync", if_exists=True) - op.drop_index("ix_devices_last_seen", "devices", if_exists=True) - op.drop_index("ix_devices_user_id", "devices", if_exists=True) + + if not is_postgresql(conn): + # Re-create the FK (MariaDB will auto-create an implicit index for it) + for fk_name in fk_names: + op.create_foreign_key( + fk_name, "saves", "roms", ["rom_id"], ["id"], ondelete="CASCADE" + ) with op.batch_alter_table("saves", schema=None) as batch_op: batch_op.drop_column("content_hash", if_exists=True) batch_op.drop_column("slot", if_exists=True) + # drop_table handles indexes and FK constraints, no need to drop them separately op.drop_table("device_save_sync", if_exists=True) op.drop_table("devices", if_exists=True) - op.execute("DROP TYPE IF EXISTS syncmode") + + if is_postgresql(op.get_bind()): + op.execute("DROP TYPE IF EXISTS syncmode") diff --git a/backend/alembic/versions/0072_client_tokens.py b/backend/alembic/versions/0072_client_tokens.py index 2064ba482..6316d878d 100644 --- a/backend/alembic/versions/0072_client_tokens.py +++ b/backend/alembic/versions/0072_client_tokens.py @@ -57,7 +57,4 @@ def upgrade() -> None: def downgrade() -> None: - with op.batch_alter_table("client_tokens") as batch_op: - batch_op.drop_index(batch_op.f("ix_client_tokens_user_id"), if_exists=True) - batch_op.drop_index(batch_op.f("ix_client_tokens_hashed_token"), if_exists=True) op.drop_table("client_tokens", if_exists=True)