UMBRA/backend/alembic/versions/030_add_user_id_to_calendars.py
Kyle Pope 72ac1d53fb Fix migration 030 failing on fresh DB with no admin user
Migration 006 seeds default calendar rows. On a fresh install, no users
exist when migration 030 runs, so the backfill SELECT returns NULL and
SET NOT NULL fails. Now deletes orphan calendars before enforcing the
constraint — account setup will recreate defaults for new users.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 04:49:57 +08:00

41 lines
1.4 KiB
Python

"""Add user_id FK to calendars table.
Revision ID: 030
Revises: 029
Create Date: 2026-02-26
"""
from alembic import op
import sqlalchemy as sa
revision = "030"
down_revision = "029"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("calendars", sa.Column("user_id", sa.Integer(), nullable=True))
# Backfill existing calendars to first admin user
op.execute(
"UPDATE calendars SET user_id = ("
" SELECT id FROM users WHERE role = 'admin' ORDER BY id LIMIT 1"
")"
)
# On fresh installs no users exist yet, so seeded calendars still have
# NULL user_id. Remove them — account setup will recreate defaults.
op.execute("DELETE FROM calendars WHERE user_id IS NULL")
op.create_foreign_key(
"fk_calendars_user_id", "calendars", "users",
["user_id"], ["id"], ondelete="CASCADE"
)
op.alter_column("calendars", "user_id", nullable=False)
op.create_index("ix_calendars_user_id", "calendars", ["user_id"])
op.create_index("ix_calendars_user_default", "calendars", ["user_id", "is_default"])
def downgrade() -> None:
op.drop_index("ix_calendars_user_default", table_name="calendars")
op.drop_index("ix_calendars_user_id", table_name="calendars")
op.drop_constraint("fk_calendars_user_id", "calendars", type_="foreignkey")
op.drop_column("calendars", "user_id")