File size: 2,601 Bytes
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f38e611
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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()