import os import sqlite3 from pathlib import Path # Base directory paths BASE_DIR = Path(__file__).resolve().parent.parent DB_PATH = Path(os.environ.get("DATABASE_PATH", str(BASE_DIR / "financial_risk.db"))) SCHEMA_PATH = BASE_DIR / "db" / "schema.sql" def get_db_connection(db_path=DB_PATH): """Establishes and returns a connection to the SQLite database with WAL and 30s timeout.""" conn = sqlite3.connect(db_path, timeout=30.0) conn.row_factory = sqlite3.Row # Enable foreign keys in SQLite conn.execute("PRAGMA foreign_keys = ON;") # Enable WAL mode in SQLite to handle concurrent reads/writes conn.execute("PRAGMA journal_mode = WAL;") return conn def init_db(db_path=DB_PATH, schema_path=SCHEMA_PATH): """Initializes the database using the schema.sql script.""" if not os.path.exists(schema_path): raise FileNotFoundError(f"Schema file not found at: {schema_path}") print(f"Initializing database at: {db_path}") conn = get_db_connection(db_path) try: with open(schema_path, "r", encoding="utf-8") as f: schema_sql = f.read() conn.executescript(schema_sql) conn.commit() print("Database initialized successfully.") except Exception as e: conn.rollback() print(f"Error initializing database: {e}") raise e finally: conn.close() def ensure_columns(conn, table, columns): """Adds any missing columns to an existing table. CREATE TABLE IF NOT EXISTS is a no-op once the table exists, so a schema that grows a column leaves already-deployed databases behind and every query naming it fails with "no such column". This closes that gap on startup. columns: list of (name, "TYPE ...") pairs. """ try: cursor = conn.cursor() cursor.execute(f"PRAGMA table_info({table})") existing = {row[1] for row in cursor.fetchall()} except Exception: # Postgres has no PRAGMA; the shim returns nothing and the ALTERs below # are guarded individually, so this stays safe on both backends. existing = set() added = [] for name, decl in columns: if name in existing: continue try: conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}") added.append(name) except Exception: pass # already present, or the backend reports it differently if added: conn.commit() print(f"Migrated {table}: added {', '.join(added)}") return added if __name__ == "__main__": init_db()