"""decouple musicians: standalone table, join table for references, fk for learned_from Revision ID: 2bd4f3ff0ccc Revises: ea4bb85f9908 Create Date: 2026-06-09 """ from alembic import op import sqlalchemy as sa revision = "2bd4f3ff0ccc" down_revision = "ea4bb85f9908" branch_labels = None depends_on = None def upgrade() -> None: # 1. Drop the old musicians table (string PK, tied to references) op.drop_table("musicians") # 2. Create standalone musicians table with integer PK op.create_table( "musicians", sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False), sa.Column("name", sa.String(), nullable=False), ) # 3. Create reference_musicians join table (many-to-many) op.create_table( "reference_musicians", sa.Column("reference_id", sa.Integer(), sa.ForeignKey("references.id", ondelete="CASCADE"), nullable=False), sa.Column("musician_id", sa.Integer(), sa.ForeignKey("musicians.id", ondelete="CASCADE"), nullable=False), sa.PrimaryKeyConstraint("reference_id", "musician_id"), ) # 4. Add learned_from_id FK to banjo and fiddle (keep old learned_from text # column for the downgrade path, then drop it) op.add_column("banjo", sa.Column("learned_from_id", sa.Integer(), sa.ForeignKey("musicians.id", ondelete="SET NULL"), nullable=True)) op.add_column("fiddle", sa.Column("learned_from_id", sa.Integer(), sa.ForeignKey("musicians.id", ondelete="SET NULL"), nullable=True)) op.drop_column("banjo", "learned_from") op.drop_column("fiddle", "learned_from") def downgrade() -> None: op.add_column("banjo", sa.Column("learned_from", sa.String(), nullable=True)) op.add_column("fiddle", sa.Column("learned_from", sa.String(), nullable=True)) op.drop_column("banjo", "learned_from_id") op.drop_column("fiddle", "learned_from_id") op.drop_table("reference_musicians") op.drop_table("musicians") # Recreate original musicians table op.create_table( "musicians", sa.Column("name", sa.String(), primary_key=True, nullable=False), sa.Column("reference_id", sa.Integer(), sa.ForeignKey("references.id", ondelete="CASCADE"), nullable=True), )