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>
This commit is contained in:
Kyle 2026-02-27 04:49:57 +08:00
parent cbf4663e8d
commit 72ac1d53fb

View File

@ -15,11 +15,15 @@ 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"