---
type: "Source File"
title: "\"\"\"SQLite storage for CopeCheck Data — time series economic data + Oracle commentary.\"\"\""
description: "\"\"\"SQLite storage for CopeCheck Data — time series economic data + Oracle commentary.\"\"\" import os, sqlite3, hashlib from contextlib import contextmanager from pathlib import Path from datetime import datetime."
resource: "https://data.copecheck.com"
tags: ["copecheck", "data", "source-file", "py"]
timestamp: "2026-09-21T19:51:03Z"
site: "data"
source_path: "copecheck-data/db.py"
---

# """SQLite storage for CopeCheck Data — time series economic data + Oracle commentary."""

Source path: `copecheck-data/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-21T19:51:03Z`

```py
"""SQLite storage for CopeCheck Data — time series economic data + Oracle commentary."""
import os, sqlite3, hashlib
from contextlib import contextmanager
from pathlib import Path
from datetime import datetime, timezone

DB_PATH = os.environ.get(
    "COPECHECK_DB",
    str(Path(__file__).parent / "data" / "copecheck_data.db"),
)
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)

SCHEMA = """
CREATE TABLE IF NOT EXISTS data_series (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT,
    category TEXT,
    unit TEXT,
    source TEXT,
    source_url TEXT,
    frequency TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS data_points (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    series_id TEXT NOT NULL,
    country TEXT NOT NULL,
    date TEXT NOT NULL,
    value REAL,
    raw_json TEXT,
    fetched_at TEXT DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(series_id, country, date)
);
CREATE INDEX IF NOT EXISTS idx_dp_series ON data_points(series_id, country, date DESC);

CREATE TABLE IF NOT EXISTS oracle_commentary (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    series_id TEXT,
    country TEXT,
    trigger_type TEXT,
    headline TEXT NOT NULL,
    commentary_md TEXT NOT NULL,
    cope_score REAL,
    cope_type TEXT,
    data_snapshot TEXT,
    model TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_oc_series ON oracle_commentary(series_id, country, created_at DESC);

CREATE TABLE IF NOT EXISTS fetch_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    source TEXT,
    series_id TEXT,
    status TEXT,
    records_added INTEGER DEFAULT 0,
    error_msg TEXT,
    fetched_at TEXT DEFAULT CURRENT_TIMESTAMP
);
"""

@contextmanager
def conn():
    c = sqlite3.connect(DB_PATH, timeout=30)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    try:
        yield c
        c.commit()
    finally:
        c.close()

def init():
    with conn() as c:
        c.executescript(SCHEMA)


def upsert_data_point(c, series_id, country, date, value, raw_json=None):
    c.execute("""INSERT INTO data_points (series_id, country, date, value, raw_json)
        VALUES (?, ?, ?, ?, ?)
        ON CONFLICT(series_id, country, date) DO UPDATE SET
            value=excluded.value, raw_json=excluded.raw_json, fetched_at=CURRENT_TIMESTAMP""",
        (series_id, country, date, value, raw_json))

def get_series_data(series_id, country=None, limit=100):
    with conn() as c:
        if country:
            return [dict(r) for r in c.execute(
                "SELECT * FROM data_points WHERE series_id=? AND country=? ORDER BY date DESC LIMIT ?",
                (series_id, country, limit)).fetchall()]
        return [dict(r) for r in c.execute(
            "SELECT * FROM data_points WHERE series_id=? ORDER BY date DESC LIMIT ?",
            (series_id, limit)).fetchall()]

def get_latest_by_country(series_id):
    with conn() as c:
        return [dict(r) for r in c.execute("""
            SELECT dp.* FROM data_points dp
            INNER JOIN (SELECT country, MAX(date) as max_date FROM data_points
                        WHERE series_id=? GROUP BY country) latest
            ON dp.country = latest.country AND dp.date = latest.max_date AND dp.series_id = ?
            ORDER BY dp.value DESC""", (series_id, series_id)).fetchall()]

def get_commentary(series_id=None, country=None, limit=20):
    with conn() as c:
        q = "SELECT * FROM oracle_commentary WHERE 1=1"
        params = []
        if series_id:
            q += " AND series_id=?"
            params.append(series_id)
        if country:
            q += " AND country=?"
            params.append(country)
        q += " ORDER BY created_at DESC LIMIT ?"
        params.append(limit)
        return [dict(r) for r in c.execute(q, params).fetchall()]

def get_all_commentary(limit=40):
    with conn() as c:
        return [dict(r) for r in c.execute(
            "SELECT * FROM oracle_commentary ORDER BY created_at DESC LIMIT ?", (limit,)).fetchall()]

def get_commentary_by_slug(slug):
    """Fetch a single scored report by its permalink slug."""
    with conn() as c:
        r = c.execute(
            "SELECT * FROM oracle_commentary WHERE slug=?", (slug,)).fetchone()
        return dict(r) if r else None

def get_report_slugs():
    """All commentary rows that have a permalink slug, newest first."""
    with conn() as c:
        return [dict(r) for r in c.execute(
            "SELECT slug, title, created_at FROM oracle_commentary "
            "WHERE slug IS NOT NULL ORDER BY created_at DESC").fetchall()]

def get_series_list():
    with conn() as c:
        return [dict(r) for r in c.execute(
            "SELECT * FROM data_series ORDER BY category, name").fetchall()]

def get_countries_for_series(series_id):
    with conn() as c:
        return [r[0] for r in c.execute(
            "SELECT DISTINCT country FROM data_points WHERE series_id=? ORDER BY country",
            (series_id,)).fetchall()]

def get_stats():
    with conn() as c:
        return {
            'total_series': c.execute("SELECT COUNT(*) FROM data_series").fetchone()[0],
            'total_data_points': c.execute("SELECT COUNT(*) FROM data_points").fetchone()[0],
            'total_commentary': c.execute("SELECT COUNT(*) FROM oracle_commentary").fetchone()[0],
            'countries': c.execute("SELECT COUNT(DISTINCT country) FROM data_points").fetchone()[0],
        }

def get_series_freshness():
    """Return {series_id: {source, latest_date}} for all series."""
    with conn() as c:
        series_info = {r['id']: {'source': r['source'], 'frequency': r['frequency']}
                       for r in c.execute('SELECT id, source, frequency FROM data_series').fetchall()}
        latest_dates = {r['series_id']: r['latest']
                        for r in c.execute(
                            'SELECT series_id, MAX(date) as latest FROM data_points GROUP BY series_id'
                        ).fetchall()}
        result = {}
        for sid, info in series_info.items():
            result[sid] = {
                'source': info['source'],
                'frequency': info['frequency'],
                'latest_date': latest_dates.get(sid, 'N/A'),
            }
        return result
```
