---
type: "Source File"
title: "\"\"\"Database module for Countries CopeCheck.\"\"\""
description: "\"\"\"Database module for Countries CopeCheck.\"\"\" import sqlite3 import os import json import hashlib import time from datetime import datetime DB_PATH = os.path.join(os.path.dirname(__file__), 'copecheck_countries.db')."
resource: "https://countries.copecheck.com"
tags: ["copecheck", "countries", "source-file", "py"]
timestamp: "2026-08-24T09:34:56Z"
site: "countries"
source_path: "copecheck-countries/db.py"
---

# """Database module for Countries CopeCheck."""

Source path: `copecheck-countries/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T09:34:56Z`

```py
"""Database module for Countries CopeCheck."""

import sqlite3
import os
import json
import hashlib
import time
from datetime import datetime

DB_PATH = os.path.join(os.path.dirname(__file__), 'copecheck_countries.db')


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


def init_db():
    conn = get_db()
    conn.executescript("""
        CREATE TABLE IF NOT EXISTS countries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT UNIQUE NOT NULL,
            code TEXT,
            flag TEXT,
            leader_name TEXT,
            leader_title TEXT,
            economy_type TEXT,
            gdp_usd TEXT,
            key_sectors TEXT,
            description TEXT,
            preparedness_score REAL,
            leader_cope_score REAL,
            exposure_score REAL,
            overall_score REAL,
            screwed_score REAL,
            leader_quotes TEXT,
            policy_summary TEXT,
            scored_at TIMESTAMP,
            category TEXT DEFAULT 'country',
            submitted_by TEXT DEFAULT 'system'
        );
    """)
    # Add columns if they don't exist (migration)
    try:
        conn.execute("ALTER TABLE countries ADD COLUMN screwed_score REAL")
    except sqlite3.OperationalError:
        pass
    try:
        conn.execute("ALTER TABLE countries ADD COLUMN submitted_by TEXT DEFAULT 'system'")
    except sqlite3.OperationalError:
        pass
    conn.commit()
    conn.close()


def get_leaderboard():
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM countries WHERE submitted_by = 'system' ORDER BY overall_score DESC"
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_archive():
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM countries WHERE submitted_by = 'user' ORDER BY scored_at DESC"
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


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


def get_country_by_name(name):
    conn = get_db()
    row = conn.execute(
        "SELECT * FROM countries WHERE LOWER(name) = LOWER(?)", (name,)
    ).fetchone()
    conn.close()
    return dict(row) if row else None


def get_country_by_code(code):
    conn = get_db()
    row = conn.execute(
        "SELECT * FROM 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 countries WHERE name = ?", (data['name'],)
    ).fetchone()

    if existing:
        conn.execute("""
            UPDATE countries SET
                code=?, flag=?, leader_name=?, leader_title=?,
                economy_type=?, gdp_usd=?, key_sectors=?, description=?,
                preparedness_score=?, leader_cope_score=?, exposure_score=?,
                overall_score=?, screwed_score=?, leader_quotes=?, policy_summary=?,
                scored_at=?, submitted_by=?
            WHERE name=?
        """, (
            data.get('code'), data.get('flag'), data.get('leader_name'),
            data.get('leader_title'), data.get('economy_type'),
            data.get('gdp_usd'), data.get('key_sectors'),
            data.get('description'), data.get('preparedness_score'),
            data.get('leader_cope_score'), data.get('exposure_score'),
            data.get('overall_score'), data.get('screwed_score'),
            json.dumps(data.get('leader_quotes', [])),
            data.get('policy_summary'),
            datetime.utcnow().isoformat(),
            data.get('submitted_by', 'system'),
            data['name']
        ))
        cid = existing[0]
    else:
        cur = conn.execute("""
            INSERT INTO countries
                (name, code, flag, leader_name, leader_title, economy_type,
                 gdp_usd, key_sectors, description, preparedness_score,
                 leader_cope_score, exposure_score, overall_score, screwed_score,
                 leader_quotes, policy_summary, scored_at, submitted_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            data['name'], data.get('code'), data.get('flag'),
            data.get('leader_name'), data.get('leader_title'),
            data.get('economy_type'), data.get('gdp_usd'),
            data.get('key_sectors'), data.get('description'),
            data.get('preparedness_score'), data.get('leader_cope_score'),
            data.get('exposure_score'), data.get('overall_score'),
            data.get('screwed_score'),
            json.dumps(data.get('leader_quotes', [])),
            data.get('policy_summary'),
            datetime.utcnow().isoformat(),
            data.get('submitted_by', 'system')
        ))
        cid = cur.lastrowid

    conn.commit()
    conn.close()
    return cid


def get_country_count():
    conn = get_db()
    count = conn.execute("SELECT COUNT(*) FROM countries WHERE submitted_by = 'system'").fetchone()[0]
    conn.close()
    return count


def get_system_freshness():
    """Return the scored-at range for the published system baseline."""
    conn = get_db()
    row = conn.execute("""
        SELECT MIN(scored_at) AS first_scored_at,
               MAX(scored_at) AS last_scored_at,
               COUNT(*) AS row_count
        FROM countries
        WHERE submitted_by = 'system'
    """).fetchone()
    conn.close()
    return dict(row) if row else {
        'first_scored_at': None,
        'last_scored_at': None,
        'row_count': 0,
    }


def get_archive_count():
    conn = get_db()
    count = conn.execute("SELECT COUNT(*) FROM countries WHERE submitted_by = 'user'").fetchone()[0]
    conn.close()
    return count




def get_leaderboard_paginated(page=1, per_page=20):
    """Return leaderboard page + total count."""
    conn = get_db()
    total = conn.execute("SELECT COUNT(*) FROM countries WHERE submitted_by = 'system'").fetchone()[0]
    offset = (page - 1) * per_page
    rows = conn.execute(
        "SELECT * FROM countries WHERE submitted_by = 'system' ORDER BY overall_score DESC LIMIT ? OFFSET ?",
        (per_page, offset)
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows], total


def get_archive_paginated(page=1, per_page=20):
    """Return archive page + total count."""
    conn = get_db()
    total = conn.execute("SELECT COUNT(*) FROM countries WHERE submitted_by = 'user'").fetchone()[0]
    offset = (page - 1) * per_page
    rows = conn.execute(
        "SELECT * FROM countries WHERE submitted_by = 'user' ORDER BY scored_at DESC LIMIT ? OFFSET ?",
        (per_page, offset)
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows], total


def get_history_for_month_paginated(month, page=1, per_page=20):
    """Return history month page + total count."""
    conn = get_db()
    total = conn.execute(
        "SELECT COUNT(*) FROM country_history WHERE month = ?", (month,)
    ).fetchone()[0]
    offset = (page - 1) * per_page
    rows = conn.execute(
        "SELECT * FROM country_history WHERE month = ? ORDER BY overall_score DESC LIMIT ? OFFSET ?",
        (month, per_page, offset)
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows], total

# --- Rate limiting ---
_rate_store = {}

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
        wait = int(window - (now - oldest)) + 1
        return False, max(1, wait // 60)
    return True, 0

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]


# --- Monthly Archive ---

def init_history():
    """Create monthly history table if it doesn't exist."""
    conn = get_db()
    conn.execute("""
        CREATE TABLE IF NOT EXISTS country_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            country_name TEXT NOT NULL,
            month TEXT NOT NULL,
            preparedness_score REAL,
            leader_cope_score REAL,
            exposure_score REAL,
            overall_score REAL,
            screwed_score REAL,
            leader_quotes TEXT,
            policy_summary TEXT,
            description TEXT,
            scored_at TIMESTAMP
        )
    """)
    conn.execute("""
        CREATE INDEX IF NOT EXISTS idx_history_country_month
        ON country_history(country_name, month)
    """)
    conn.commit()
    conn.close()


def archive_current_scores(month_label=None):
    """Snapshot all current system country scores into history."""
    from datetime import datetime
    if not month_label:
        month_label = datetime.utcnow().strftime("%Y-%m")
    conn = get_db()
    countries = conn.execute(
        "SELECT * FROM countries WHERE submitted_by = 'system'"
    ).fetchall()
    for c in countries:
        c = dict(c)
        existing = conn.execute(
            "SELECT id FROM country_history WHERE country_name = ? AND month = ?",
            (c['name'], month_label)
        ).fetchone()
        if existing:
            continue
        conn.execute("""
            INSERT INTO country_history
                (country_name, month, preparedness_score, leader_cope_score,
                 exposure_score, overall_score, screwed_score, leader_quotes,
                 policy_summary, description, scored_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            c['name'], month_label, c['preparedness_score'],
            c['leader_cope_score'], c['exposure_score'],
            c['overall_score'], c['screwed_score'],
            c['leader_quotes'], c['policy_summary'],
            c['description'], c['scored_at']
        ))
    conn.commit()
    conn.close()
    return len(countries)


def get_history_months():
    """Get list of months that have archived data."""
    conn = get_db()
    rows = conn.execute(
        "SELECT DISTINCT month FROM country_history ORDER BY month DESC"
    ).fetchall()
    conn.close()
    return [r[0] for r in rows]


def get_history_for_month(month):
    """Get all country scores for a given month."""
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM country_history WHERE month = ? ORDER BY overall_score DESC",
        (month,)
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]


def get_country_history(country_name):
    """Get all monthly scores for a specific country, chronologically."""
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM country_history WHERE country_name = ? ORDER BY month ASC",
        (country_name,)
    ).fetchall()
    conn.close()
    return [dict(r) for r in rows]
```
