From 99565daafbbf93f35ef37d1da1b016e863963b5f Mon Sep 17 00:00:00 2001 From: steinhelge Date: Sat, 21 Mar 2026 09:48:26 +0100 Subject: [PATCH] Add migration for race_id column on existing passages table CREATE TABLE IF NOT EXISTS does not add new columns to existing tables. Use ALTER TABLE to migrate databases that predate this change. Co-Authored-By: Claude Sonnet 4.6 --- backend/profile_db.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/backend/profile_db.py b/backend/profile_db.py index 5e6b90c..18da011 100644 --- a/backend/profile_db.py +++ b/backend/profile_db.py @@ -51,17 +51,30 @@ async def init_db(db: aiosqlite.Connection) -> None: ); CREATE INDEX IF NOT EXISTS idx_passages_profile ON passages(profile_id); - CREATE INDEX IF NOT EXISTS idx_passages_race ON passages(race_id); CREATE INDEX IF NOT EXISTS idx_passages_station ON passages(station); CREATE INDEX IF NOT EXISTS idx_passages_needs_review ON passages(needs_review); CREATE INDEX IF NOT EXISTS idx_passage_images_passage ON passage_images(passage_id); """) await db.commit() + # Migrer eksisterende tabeller + await _migrate(db) + from race_db import init_race_tables await init_race_tables(db) +async def _migrate(db: aiosqlite.Connection) -> None: + """Legg til nye kolonner i eksisterende tabeller ved oppgradering.""" + async with db.execute("PRAGMA table_info(passages)") as cur: + columns = {row[1] for row in await cur.fetchall()} + + if "race_id" not in columns: + await db.execute("ALTER TABLE passages ADD COLUMN race_id TEXT REFERENCES races(race_id)") + await db.execute("CREATE INDEX IF NOT EXISTS idx_passages_race ON passages(race_id)") + await db.commit() + + async def get_db() -> aiosqlite.Connection: db = await aiosqlite.connect(DB_PATH) db.row_factory = aiosqlite.Row