"""Add unique constraint on audio_versions.nc_file_path. Prevents duplicate imports when concurrent scans race on the same file. Revision ID: 0009_av_nc_path_uq Revises: 0008_drop_nc_columns Create Date: 2026-04-12 """ from alembic import op revision = "0009_av_nc_path_uq" down_revision = "0008_drop_nc_columns" branch_labels = None depends_on = None def upgrade() -> None: # Remove any existing duplicates first (keep the oldest version per path) op.execute(""" DELETE FROM audio_versions WHERE id NOT IN ( SELECT DISTINCT ON (nc_file_path) id FROM audio_versions ORDER BY nc_file_path, uploaded_at ASC ) """) op.create_unique_constraint( "uq_audio_version_nc_file_path", "audio_versions", ["nc_file_path"], ) def downgrade() -> None: op.drop_constraint("uq_audio_version_nc_file_path", "audio_versions", type_="unique")