From 98cbde8cbd47ce566baefa08db5e8a7fa772ae9d Mon Sep 17 00:00:00 2001 From: ai-bot Date: Fri, 2 Oct 2026 06:26:50 +0000 Subject: [PATCH] Create the health check index only when the indexed column exists --- database.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/database.py b/database.py index d4a15e3..06bc628 100644 --- a/database.py +++ b/database.py @@ -80,7 +80,6 @@ SCHEMA_STATEMENTS = ( UNIQUE (health_check_id, provider) ) """, - "CREATE INDEX IF NOT EXISTS idx_health_checks_checked_at ON health_checks(checked_at DESC)", ) OPTIONAL_COLUMNS = ( ("key_checks", "address_verified", "INTEGER CHECK (address_verified IN (0, 1))"), @@ -88,6 +87,13 @@ OPTIONAL_COLUMNS = ( ("health_checks", "software_comments", "TEXT"), ("key_checks", "seed_backup_verified", "INTEGER CHECK (seed_backup_verified IN (0, 1))"), ) +INDEX_STATEMENTS = ( + ( + "health_checks", + "checked_at", + "CREATE INDEX IF NOT EXISTS idx_health_checks_checked_at ON health_checks(checked_at DESC)", + ), +) def initialize_database(database_path="data/helsesjekk.sqlite3"): @@ -109,6 +115,8 @@ def initialize_database(database_path="data/helsesjekk.sqlite3"): connection.execute(statement) for table, column, definition in OPTIONAL_COLUMNS: _ensure_column(connection, table, column, definition) + for table, column, statement in INDEX_STATEMENTS: + _ensure_index(connection, table, column, statement) connection.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") connection.commit() except Exception: @@ -127,6 +135,18 @@ def _ensure_column(connection, table, column, definition): connection.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}") +def _ensure_index(connection, table, column, statement): + """Create an index only when its table has the indexed column. + + A partially migrated database can contain the table without the column, and + creating the index would then fail. Such a database cannot serve health + checks until the column exists, so the index is skipped instead. + """ + columns = {row[1] for row in connection.execute(f"PRAGMA table_info({table})")} + if column in columns: + connection.execute(statement) + + def seed_fixed_keys(database_path="data/helsesjekk.sqlite3"): """Ensure the three fixed key profiles exist without overwriting custom names.""" connection = sqlite3.connect(database_path, timeout=5)