"""Promote nonce_hex to PK on musehub_auth_challenges; drop challenge_id. The nonce_hex column IS the natural identity of a challenge row — it was already UNIQUE and was the lookup key in all service code. challenge_id was a redundant UUID surrogate that provided no additional information. Revision ID: 0022 Revises: 0021 """ from __future__ import annotations from alembic import op import sqlalchemy as sa revision = "0022" down_revision = "0021" branch_labels = None depends_on = None def upgrade() -> None: from sqlalchemy import inspect as sa_inspect conn = op.get_bind() insp = sa_inspect(conn) if not insp.has_table("musehub_auth_challenges"): # Table was never created on this instance — create it with the final # schema (nonce_hex as PK, no challenge_id surrogate). op.create_table( "musehub_auth_challenges", sa.Column("nonce_hex", sa.String(64), primary_key=True), sa.Column("public_key", sa.Text, nullable=False), sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False), ) op.create_index( "ix_musehub_auth_challenges_expires_at", "musehub_auth_challenges", ["expires_at"], ) return # Drop the old UUID primary key op.drop_constraint("musehub_auth_challenges_pkey", "musehub_auth_challenges", type_="primary") op.drop_column("musehub_auth_challenges", "challenge_id") # Drop the now-redundant unique constraint on nonce_hex (PK implies uniqueness) op.drop_constraint( "uq_musehub_auth_challenges_nonce_hex", "musehub_auth_challenges", type_="unique" ) # Make nonce_hex the primary key op.create_primary_key("musehub_auth_challenges_pkey", "musehub_auth_challenges", ["nonce_hex"]) def downgrade() -> None: from sqlalchemy import inspect as sa_inspect conn = op.get_bind() insp = sa_inspect(conn) if not insp.has_table("musehub_auth_challenges"): return # nothing to undo cols = {c["name"] for c in insp.get_columns("musehub_auth_challenges")} if "challenge_id" not in cols: # Table was created fresh by upgrade (the if-not-exists branch) — drop it entirely. op.drop_table("musehub_auth_challenges") return # Restore the surrogate PK (new UUIDs — existing rows get new random IDs) op.drop_constraint("musehub_auth_challenges_pkey", "musehub_auth_challenges", type_="primary") op.add_column( "musehub_auth_challenges", sa.Column( "challenge_id", sa.String(36), nullable=False, server_default=sa.text("gen_random_uuid()::text"), ), ) op.create_primary_key("musehub_auth_challenges_pkey", "musehub_auth_challenges", ["challenge_id"]) op.create_unique_constraint( "uq_musehub_auth_challenges_nonce_hex", "musehub_auth_challenges", ["nonce_hex"] )