"""Add CASCADE delete to foreign keys Revision ID: 003 Revises: 002_add_timezone_to_datetime Create Date: 2025-11-30 """ from typing import Sequence, Union from alembic import op # revision identifiers, used by Alembic. revision: str = '003' down_revision: Union[str, None] = '002' branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: # Submissions table - add CASCADE delete op.drop_constraint('submissions_user_id_fkey', 'submissions', type_='foreignkey') op.drop_constraint('submissions_problem_id_fkey', 'submissions', type_='foreignkey') op.drop_constraint('submissions_contest_id_fkey', 'submissions', type_='foreignkey') op.create_foreign_key( 'submissions_user_id_fkey', 'submissions', 'users', ['user_id'], ['id'], ondelete='CASCADE' ) op.create_foreign_key( 'submissions_problem_id_fkey', 'submissions', 'problems', ['problem_id'], ['id'], ondelete='CASCADE' ) op.create_foreign_key( 'submissions_contest_id_fkey', 'submissions', 'contests', ['contest_id'], ['id'], ondelete='CASCADE' ) # ContestParticipants table - add CASCADE delete op.drop_constraint('contest_participants_contest_id_fkey', 'contest_participants', type_='foreignkey') op.drop_constraint('contest_participants_user_id_fkey', 'contest_participants', type_='foreignkey') op.create_foreign_key( 'contest_participants_contest_id_fkey', 'contest_participants', 'contests', ['contest_id'], ['id'], ondelete='CASCADE' ) op.create_foreign_key( 'contest_participants_user_id_fkey', 'contest_participants', 'users', ['user_id'], ['id'], ondelete='CASCADE' ) def downgrade() -> None: # Submissions table - remove CASCADE delete op.drop_constraint('submissions_user_id_fkey', 'submissions', type_='foreignkey') op.drop_constraint('submissions_problem_id_fkey', 'submissions', type_='foreignkey') op.drop_constraint('submissions_contest_id_fkey', 'submissions', type_='foreignkey') op.create_foreign_key( 'submissions_user_id_fkey', 'submissions', 'users', ['user_id'], ['id'] ) op.create_foreign_key( 'submissions_problem_id_fkey', 'submissions', 'problems', ['problem_id'], ['id'] ) op.create_foreign_key( 'submissions_contest_id_fkey', 'submissions', 'contests', ['contest_id'], ['id'] ) # ContestParticipants table - remove CASCADE delete op.drop_constraint('contest_participants_contest_id_fkey', 'contest_participants', type_='foreignkey') op.drop_constraint('contest_participants_user_id_fkey', 'contest_participants', type_='foreignkey') op.create_foreign_key( 'contest_participants_contest_id_fkey', 'contest_participants', 'contests', ['contest_id'], ['id'] ) op.create_foreign_key( 'contest_participants_user_id_fkey', 'contest_participants', 'users', ['user_id'], ['id'] )