---
type: "Source File"
title: "\"\"\"Database layer for EU CopeCheck.\"\"\""
description: "\"\"\"Database layer for EU CopeCheck.\"\"\" import sqlite3 import json import os import logging from datetime import datetime log = logging.getLogger(\"eu_db\") DB_PATH =."
resource: "https://eu.copecheck.com"
tags: ["copecheck", "eu", "source-file", "py"]
timestamp: "2026-05-15T10:00:32Z"
site: "eu"
source_path: "copecheck-eu/db.py"
---

# """Database layer for EU CopeCheck."""

Source path: `copecheck-eu/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-15T10:00:32Z`

```py
"""Database layer for EU CopeCheck."""
import sqlite3
import json
import os
import logging
from datetime import datetime

log = logging.getLogger("eu_db")
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "copecheck_eu.db")


def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn


def init_db():
    conn = get_db()
    conn.executescript("""
    CREATE TABLE IF NOT EXISTS eu_countries (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        code TEXT UNIQUE NOT NULL,
        name TEXT NOT NULL,
        flag TEXT DEFAULT '',
        leader_name TEXT DEFAULT '',
        leader_title TEXT DEFAULT '',
        eu_join_year INTEGER DEFAULT 0,
        economy_type TEXT DEFAULT 'Mixed',
        key_sectors TEXT DEFAULT '',
        population_m REAL DEFAULT 0,
        median_age REAL DEFAULT 0,
        youth_unemployment REAL DEFAULT 0,
        net_migration_k REAL DEFAULT 0,
        youth_emigration_pct REAL DEFAULT 0,
        services_pct REAL DEFAULT 0,
        unit_labour_cost_idx REAL DEFAULT 0,
        gdp_per_capita REAL DEFAULT 0,
        preparedness_score REAL DEFAULT 0,
        leader_cope_score REAL DEFAULT 0,
        exposure_score REAL DEFAULT 0,
        demographic_score REAL DEFAULT 0,
        overall_score REAL DEFAULT 0,
        screwed_score REAL DEFAULT 0,
        screwed_rationale TEXT DEFAULT '',
        description TEXT DEFAULT '',
        leader_quotes TEXT DEFAULT '[]',
        policy_summary TEXT DEFAULT '',
        demographic_analysis TEXT DEFAULT '',
        ai_model TEXT DEFAULT '',
        scored_at TEXT DEFAULT '',
        created_at TEXT DEFAULT (datetime('now')),
        updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS eu_laws (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        celex_id TEXT UNIQUE,
        title TEXT NOT NULL,
        law_type TEXT DEFAULT 'regulation',
        status TEXT DEFAULT 'in_force',
        date_adopted TEXT DEFAULT '',
        date_in_force TEXT DEFAULT '',
        summary TEXT DEFAULT '',
        full_text_url TEXT DEFAULT '',
        unit_cost_score REAL DEFAULT 0,
        unit_cost_analysis TEXT DEFAULT '',
        prisoner_dilemma_score REAL DEFAULT 0,
        prisoner_dilemma_analysis TEXT DEFAULT '',
        sorites_score REAL DEFAULT 0,
        sorites_analysis TEXT DEFAULT '',
        overall_cope_score REAL DEFAULT 0,
        verdict TEXT DEFAULT '',
        ai_analysis TEXT DEFAULT '',
        ai_model TEXT DEFAULT '',
        scored_at TEXT DEFAULT '',
        created_at TEXT DEFAULT (datetime('now')),
        updated_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS eu_institutions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT UNIQUE NOT NULL,
        inst_type TEXT DEFAULT 'body',
        head_name TEXT DEFAULT '',
        head_title TEXT DEFAULT '',
        description TEXT DEFAULT '',
        cope_score REAL DEFAULT 0,
        cope_quotes TEXT DEFAULT '[]',
        cope_analysis TEXT DEFAULT '',
        ai_model TEXT DEFAULT '',
        scored_at TEXT DEFAULT '',
        created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS eu_stats_cache (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        country_code TEXT NOT NULL,
        dataset TEXT NOT NULL,
        indicator TEXT NOT NULL,
        value REAL,
        period TEXT DEFAULT '',
        fetched_at TEXT DEFAULT (datetime('now')),
        UNIQUE(country_code, dataset, indicator, period)
    );

    CREATE TABLE IF NOT EXISTS eu_country_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        country_id INTEGER NOT NULL,
        month TEXT NOT NULL,
        overall_score REAL DEFAULT 0,
        preparedness_score REAL DEFAULT 0,
        leader_cope_score REAL DEFAULT 0,
        exposure_score REAL DEFAULT 0,
        demographic_score REAL DEFAULT 0,
        screwed_score REAL DEFAULT 0,
        archived_at TEXT DEFAULT (datetime('now')),
        UNIQUE(country_id, month),
        FOREIGN KEY (country_id) REFERENCES eu_countries(id)
    );

    CREATE TABLE IF NOT EXISTS oracle_questions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        question TEXT NOT NULL,
        answer TEXT DEFAULT '',
        model TEXT DEFAULT '',
[redacted secret-like line]
        created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS eu_articles (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        url TEXT UNIQUE,
        source TEXT DEFAULT '',
        snippet TEXT DEFAULT '',
        cope_score REAL DEFAULT 0,
        cope_type TEXT DEFAULT '',
        analysis TEXT DEFAULT '',
        ai_model TEXT DEFAULT '',
        scored_at TEXT DEFAULT '',
        created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS eu_economic_data (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        country_code TEXT NOT NULL,
        indicator TEXT NOT NULL,
        value REAL,
        period TEXT NOT NULL,
        dataset TEXT DEFAULT '',
        fetched_at TEXT DEFAULT (datetime('now')),
        UNIQUE(country_code, indicator, period)
    );

    CREATE INDEX IF NOT EXISTS idx_econ_country ON eu_economic_data(country_code);
    CREATE INDEX IF NOT EXISTS idx_econ_indicator ON eu_economic_data(indicator);

    CREATE TABLE IF NOT EXISTS eu_meta (
        key TEXT PRIMARY KEY,
        value TEXT DEFAULT '',
        updated_at TEXT DEFAULT (datetime('now'))
    );
    """)
    conn.commit()
    conn.close()
    log.info("Database initialized")


# ── Country operations ──

def get_all_countries(order_by="overall_score DESC"):
    conn = get_db()
    rows = conn.execute(f"SELECT * FROM eu_countries ORDER BY {order_by}").fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_country(country_id):
    conn = get_db()
    row = conn.execute("SELECT * FROM eu_countries WHERE id=?", (country_id,)).fetchone()
    conn.close()
    return dict(row) if row else None


def get_country_by_code(code):
    conn = get_db()
    row = conn.execute("SELECT * FROM eu_countries WHERE code=?", (code.upper(),)).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_country(data):
    conn = get_db()
    existing = conn.execute("SELECT id FROM eu_countries WHERE code=?", (data['code'],)).fetchone()
    if existing:
        sets = ", ".join(f"{k}=?" for k in data if k != 'code')
        vals = [data[k] for k in data if k != 'code'] + [data['code']]
        conn.execute(f"UPDATE eu_countries SET {sets}, updated_at=datetime('now') WHERE code=?", vals)
    else:
        cols = ", ".join(data.keys())
        placeholders = ", ".join("?" * len(data))
        conn.execute(f"INSERT INTO eu_countries ({cols}) VALUES ({placeholders})", list(data.values()))
    conn.commit()
    conn.close()


def update_country_scores(country_id, scores):
    conn = get_db()
    conn.execute("""UPDATE eu_countries SET
        preparedness_score=?, leader_cope_score=?, exposure_score=?, demographic_score=?,
        overall_score=?, screwed_score=?, screwed_rationale=?,
        description=?, leader_quotes=?, policy_summary=?, demographic_analysis=?,
        ai_model=?, scored_at=datetime('now'), updated_at=datetime('now')
        WHERE id=?""",
        (scores.get('preparedness_score', 0), scores.get('leader_cope_score', 0),
         scores.get('exposure_score', 0), scores.get('demographic_score', 0),
         scores.get('overall_score', 0), scores.get('screwed_score', 0),
         scores.get('screwed_rationale', ''), scores.get('description', ''),
         json.dumps(scores.get('leader_quotes', [])), scores.get('policy_summary', ''),
         scores.get('demographic_analysis', ''), scores.get('ai_model', ''), country_id))
    conn.commit()
    conn.close()


# ── Law operations ──

def get_all_laws(order_by="overall_cope_score DESC"):
    conn = get_db()
    rows = conn.execute(f"SELECT * FROM eu_laws ORDER BY {order_by}").fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_law(law_id):
    conn = get_db()
    row = conn.execute("SELECT * FROM eu_laws WHERE id=?", (law_id,)).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_law(data):
    conn = get_db()
    if data.get('celex_id'):
        existing = conn.execute("SELECT id FROM eu_laws WHERE celex_id=?", (data['celex_id'],)).fetchone()
    else:
        existing = None
    if existing:
        sets = ", ".join(f"{k}=?" for k in data if k != 'celex_id')
        vals = [data[k] for k in data if k != 'celex_id'] + [data['celex_id']]
        conn.execute(f"UPDATE eu_laws SET {sets}, updated_at=datetime('now') WHERE celex_id=?", vals)
        law_id = existing['id']
    else:
        cols = ", ".join(data.keys())
        placeholders = ", ".join("?" * len(data))
        conn.execute(f"INSERT INTO eu_laws ({cols}) VALUES ({placeholders})", list(data.values()))
        law_id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
    conn.commit()
    conn.close()
    return law_id


def update_law_scores(law_id, scores):
    conn = get_db()
    conn.execute("""UPDATE eu_laws SET
        unit_cost_score=?, unit_cost_analysis=?,
        prisoner_dilemma_score=?, prisoner_dilemma_analysis=?,
        sorites_score=?, sorites_analysis=?,
        overall_cope_score=?, verdict=?, ai_analysis=?,
        ai_model=?, scored_at=datetime('now'), updated_at=datetime('now')
        WHERE id=?""",
        (scores.get('unit_cost_score', 0), scores.get('unit_cost_analysis', ''),
         scores.get('prisoner_dilemma_score', 0), scores.get('prisoner_dilemma_analysis', ''),
         scores.get('sorites_score', 0), scores.get('sorites_analysis', ''),
         scores.get('overall_cope_score', 0), scores.get('verdict', ''),
         scores.get('ai_analysis', ''), scores.get('ai_model', ''), law_id))
    conn.commit()
    conn.close()


# ── Institution operations ──

def get_all_institutions():
    conn = get_db()
    rows = conn.execute("SELECT * FROM eu_institutions ORDER BY cope_score DESC").fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_institution(inst_id):
    conn = get_db()
    row = conn.execute("SELECT * FROM eu_institutions WHERE id=?", (inst_id,)).fetchone()
    conn.close()
    return dict(row) if row else None


def upsert_institution(data):
    conn = get_db()
    existing = conn.execute("SELECT id FROM eu_institutions WHERE name=?", (data['name'],)).fetchone()
    if existing:
        sets = ", ".join(f"{k}=?" for k in data if k != 'name')
        vals = [data[k] for k in data if k != 'name'] + [data['name']]
        conn.execute(f"UPDATE eu_institutions SET {sets} WHERE name=?", vals)
    else:
        cols = ", ".join(data.keys())
        placeholders = ", ".join("?" * len(data))
        conn.execute(f"INSERT INTO eu_institutions ({cols}) VALUES ({placeholders})", list(data.values()))
    conn.commit()
    conn.close()


# ── Stats cache ──

def cache_stat(country_code, dataset, indicator, value, period=""):
    conn = get_db()
    conn.execute("""INSERT OR REPLACE INTO eu_stats_cache
        (country_code, dataset, indicator, value, period, fetched_at)
        VALUES (?, ?, ?, ?, ?, datetime('now'))""",
        (country_code, dataset, indicator, value, period))
    conn.commit()
    conn.close()


def get_cached_stats(country_code):
    conn = get_db()
    rows = conn.execute("SELECT * FROM eu_stats_cache WHERE country_code=? ORDER BY dataset, indicator", (country_code,)).fetchall()
    conn.close()
    return [dict(r) for r in rows]


# ── History ──

def archive_current_scores(month=None):
    if not month:
        month = datetime.utcnow().strftime("%Y-%m")
    conn = get_db()
    countries = conn.execute("SELECT * FROM eu_countries").fetchall()
    for c in countries:
        conn.execute("""INSERT OR REPLACE INTO eu_country_history
            (country_id, month, overall_score, preparedness_score, leader_cope_score,
             exposure_score, demographic_score, screwed_score)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
            (c['id'], month, c['overall_score'], c['preparedness_score'],
             c['leader_cope_score'], c['exposure_score'], c['demographic_score'],
             c['screwed_score']))
    conn.commit()
    conn.close()
    log.info("Archived scores for %s", month)


def get_history_months():
    conn = get_db()
    rows = conn.execute("SELECT DISTINCT month FROM eu_country_history ORDER BY month DESC").fetchall()
    conn.close()
    return [r['month'] for r in rows]


def get_history_for_month(month):
    conn = get_db()
    rows = conn.execute("""SELECT h.*, c.name, c.flag, c.code, c.description
        FROM eu_country_history h JOIN eu_countries c ON h.country_id = c.id
        WHERE h.month=? ORDER BY h.overall_score DESC""", (month,)).fetchall()
    conn.close()
    return [dict(r) for r in rows]


# ── Oracle Q&A ──

[redacted secret-like line]
    conn = get_db()
[redacted secret-like line]
[redacted secret-like line]
    conn.commit()
    qid = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
    conn.close()
    return qid


def get_recent_questions(limit=10):
    conn = get_db()
    rows = conn.execute("SELECT * FROM oracle_questions ORDER BY created_at DESC LIMIT ?", (limit,)).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_question(qid):
    conn = get_db()
    row = conn.execute("SELECT * FROM oracle_questions WHERE id=?", (qid,)).fetchone()
    conn.close()
    return dict(row) if row else None


# ── Articles ──

def save_article(data):
    conn = get_db()
    try:
        conn.execute("""INSERT OR IGNORE INTO eu_articles (title, url, source, snippet, cope_score, cope_type, analysis, ai_model, scored_at)
            VALUES (?,?,?,?,?,?,?,?,datetime('now'))""",
            (data.get('title',''), data.get('url',''), data.get('source',''),
             data.get('snippet',''), data.get('cope_score',0), data.get('cope_type',''),
             data.get('analysis',''), data.get('ai_model','')))
        conn.commit()
    except Exception as e:
        log.warning("Save article failed: %s", e)
    conn.close()


def get_recent_articles(limit=50):
    conn = get_db()
    rows = conn.execute("SELECT * FROM eu_articles ORDER BY created_at DESC LIMIT ?", (limit,)).fetchall()
    conn.close()
    return [dict(r) for r in rows]

def get_article_by_id(article_id):
    conn = get_db()
    row = conn.execute("SELECT * FROM eu_articles WHERE id = ?", (article_id,)).fetchone()
    conn.close()
    return dict(row) if row else None


# ── Economic Data (Eurostat) ──

def upsert_economic_data(country_code, indicator, value, period, dataset=""):
    """Insert or update an economic data point."""
    conn = get_db()
    conn.execute("""INSERT OR REPLACE INTO eu_economic_data
        (country_code, indicator, value, period, dataset, fetched_at)
        VALUES (?, ?, ?, ?, ?, datetime('now'))""",
        (country_code.upper(), indicator, value, period, dataset))
    conn.commit()
    conn.close()


def get_latest_economic_data(country_code):
    """Get the latest value for each indicator for a country."""
    conn = get_db()
    rows = conn.execute("""
        SELECT e.* FROM eu_economic_data e
        INNER JOIN (
            SELECT country_code, indicator, MAX(period) as max_period
            FROM eu_economic_data
            WHERE country_code = ?
            GROUP BY country_code, indicator
        ) latest ON e.country_code = latest.country_code
            AND e.indicator = latest.indicator
            AND e.period = latest.max_period
        ORDER BY e.indicator
    """, (country_code.upper(),)).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_economic_history(country_code, indicator, limit=24):
    """Get time series for an indicator for a country, ordered oldest first."""
    conn = get_db()
    rows = conn.execute("""
        SELECT * FROM eu_economic_data
        WHERE country_code = ? AND indicator = ?
        ORDER BY period ASC
        LIMIT ?
    """, (country_code.upper(), indicator, limit)).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_all_latest_indicators():
    """Get latest indicators for ALL countries (for economics page / leaderboard).
    Returns dict of {country_code: {indicator: {value, period}}}."""
    conn = get_db()
    rows = conn.execute("""
        SELECT e.country_code, e.indicator, e.value, e.period
        FROM eu_economic_data e
        INNER JOIN (
            SELECT country_code, indicator, MAX(period) as max_period
            FROM eu_economic_data
            GROUP BY country_code, indicator
        ) latest ON e.country_code = latest.country_code
            AND e.indicator = latest.indicator
            AND e.period = latest.max_period
        ORDER BY e.country_code, e.indicator
    """).fetchall()
    conn.close()
    result = {}
    for r in rows:
        cc = r['country_code']
        if cc not in result:
            result[cc] = {}
        result[cc][r['indicator']] = {"value": r['value'], "period": r['period']}
    return result


def get_economic_data_for_chart(country_code, indicator):
    """Get time series data formatted for Chart.js."""
    history = get_economic_history(country_code, indicator, limit=60)
    return {
        "labels": [h["period"] for h in history],
        "values": [h["value"] for h in history]
    }


def set_meta(key, value):
    """Set a metadata key-value pair."""
    conn = get_db()
    conn.execute("""INSERT OR REPLACE INTO eu_meta (key, value, updated_at)
        VALUES (?, ?, datetime('now'))""", (key, str(value)))
    conn.commit()
    conn.close()


def get_meta(key):
    """Get a metadata value."""
    conn = get_db()
    row = conn.execute("SELECT value FROM eu_meta WHERE key=?", (key,)).fetchone()
    conn.close()
    return row['value'] if row else None
```
