---
type: "Source File"
title: "\"\"\"SQLite storage for CopeCheck Careers — jobs, degrees, cope scores.\"\"\""
description: "\"\"\"SQLite storage for CopeCheck Careers — jobs, degrees, cope scores.\"\"\" import os, sqlite3, math, hashlib from contextlib import contextmanager from pathlib import Path from datetime import datetime, timezone from."
resource: "https://careers.copecheck.com"
tags: ["copecheck", "careers", "source-file", "py"]
timestamp: "2026-08-24T13:09:16Z"
site: "careers"
source_path: "copecheck-careers/db.py"
---

# """SQLite storage for CopeCheck Careers — jobs, degrees, cope scores."""

Source path: `copecheck-careers/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T13:09:16Z`

```py
"""SQLite storage for CopeCheck Careers — jobs, degrees, cope scores."""
import os, sqlite3, math, hashlib
from contextlib import contextmanager
from pathlib import Path
from datetime import datetime, timezone

from canonical_identity import (
    canonical_url,
    exact_statement_match,
    new_event_fingerprint,
    provenance_key,
    same_event,
)

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

SCHEMA = """
CREATE TABLE IF NOT EXISTS jobs (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    category TEXT,
    description TEXT,
    median_salary_usd INTEGER,
    median_salary_gbp INTEGER,
    uk_employment INTEGER,
    us_employment INTEGER,
    automation_prob REAL,
    ai_exposure_score REAL,
    cope_score REAL DEFAULT 50.0,
    prev_score REAL DEFAULT 50.0,
    total_entries INTEGER DEFAULT 0,
    last_cope_type TEXT,
    last_scored TEXT,
    photo_url TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS degrees (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    category TEXT,
    description TEXT,
    avg_starting_salary_usd INTEGER,
    avg_starting_salary_gbp INTEGER,
    uk_graduates_annual INTEGER,
    us_graduates_annual INTEGER,
    primary_career_paths TEXT,
    ai_exposure_score REAL,
    cope_score REAL DEFAULT 50.0,
    prev_score REAL DEFAULT 50.0,
    total_entries INTEGER DEFAULT 0,
    last_cope_type TEXT,
    last_scored TEXT,
    photo_url TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS cope_entries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    quote TEXT NOT NULL,
    source_url TEXT,
    source_title TEXT,
    cope_score REAL NOT NULL,
    cope_type TEXT,
    analysis_md TEXT,
    model TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_cope_entity ON cope_entries(entity_type, entity_id, created_at DESC);

CREATE TABLE IF NOT EXISTS submissions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    entity_type TEXT,
    entity_id TEXT,
    url TEXT,
    text_body TEXT,
    status TEXT DEFAULT 'pending',
[redacted secret-like line]
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS feedback (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    email TEXT,
    message TEXT NOT NULL,
[redacted secret-like line]
    created_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 get_jobs_leaderboard():
    with conn() as c:
        return [dict(r) for r in c.execute("SELECT * FROM jobs ORDER BY ai_exposure_score DESC, cope_score DESC").fetchall()]

def get_degrees_leaderboard():
    with conn() as c:
        return [dict(r) for r in c.execute("SELECT * FROM degrees ORDER BY ai_exposure_score DESC, cope_score DESC").fetchall()]

def get_job(job_id):
    with conn() as c:
        r = c.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
        return dict(r) if r else None

def get_degree(deg_id):
    with conn() as c:
        r = c.execute("SELECT * FROM degrees WHERE id = ?", (deg_id,)).fetchone()
        return dict(r) if r else None


def _as_datetime(value):
    try:
        return datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
    except ValueError:
        return None


def _within_event_window(left, right, days=7):
    left_dt, right_dt = _as_datetime(left), _as_datetime(right)
    if not left_dt or not right_dt:
        return False
    if left_dt.tzinfo is None:
        left_dt = left_dt.replace(tzinfo=timezone.utc)
    if right_dt.tzinfo is None:
        right_dt = right_dt.replace(tzinfo=timezone.utc)
    return abs((left_dt - right_dt).total_seconds()) <= days * 86400


EVIDENCE_COLUMNS = """
entity_type, entity_id, quote, source_url, source_title, cope_score,
cope_type, analysis_md, model, created_at
"""


def _evidence_rows(c, entity_type=None, entity_id=None):
    """Read live representatives and archived repeat captures as one ledger."""
    where = ""
    params = []
    if entity_type is not None and entity_id is not None:
        where = " WHERE entity_type=? AND entity_id=?"
        params = [entity_type, entity_id]
    selects = [
        f"""SELECT id, {EVIDENCE_COLUMNS}, 0 AS archived_duplicate
              FROM cope_entries{where}"""
    ]
    all_params = list(params)
    archive_exists = c.execute(
        """SELECT 1 FROM sqlite_master
             WHERE type='table' AND name='cope_entries_duplicate_archive'"""
    ).fetchone()
    if archive_exists:
        selects.append(
            f"""SELECT original_id AS id, {EVIDENCE_COLUMNS},
                       1 AS archived_duplicate
                  FROM cope_entries_duplicate_archive{where}"""
        )
        all_params.extend(params)
    query = (
        "SELECT * FROM (" + " UNION ALL ".join(selects) + ") "
        "ORDER BY created_at DESC, id DESC"
    )
    return c.execute(query, all_params).fetchall()


def group_evidence_events(rows):
    """Group observations into underlying evidence events without deleting provenance.

    URL equality is timeless.  Text similarity is restricted to a seven-day
    window, except for a genuinely identical statement.  Entity identity is
    always part of the key, so one source discussing several careers remains
    distinct evidence for each career.
    """
    groups = []
    for raw in rows:
        row = dict(raw)
        row_canonical = canonical_url(row.get("source_url"))
        matched = None
        for event in groups:
            if (
                event.get("entity_type") != row.get("entity_type")
                or event.get("entity_id") != row.get("entity_id")
            ):
                continue
            exact_url = bool(row_canonical and row_canonical == event["canonical_url"])
            timeless = exact_statement_match(
                row.get("source_title") or "",
                row.get("quote") or "",
                event.get("source_title") or "",
                event.get("quote") or "",
            )
            fuzzy = _within_event_window(row.get("created_at"), event.get("created_at")) and same_event(
                canonical_a=row_canonical,
                title_a=row.get("source_title") or "",
                quote_a=row.get("quote") or "",
                canonical_b=event["canonical_url"],
                title_b=event.get("source_title") or "",
                quote_b=event.get("quote") or "",
            )
            if exact_url or timeless or fuzzy:
                matched = event
                break

        observation = {
            "id": row.get("id"),
            "source_url": row.get("source_url"),
            "canonical_url": row_canonical,
            "source_title": row.get("source_title"),
            "quote": row.get("quote"),
            "cope_score": row.get("cope_score"),
            "cope_type": row.get("cope_type"),
            "model": row.get("model"),
            "created_at": row.get("created_at"),
            "archived_duplicate": bool(row.get("archived_duplicate")),
        }
        observation["provenance_key"] = provenance_key(
            row_canonical,
            row.get("source_title") or "",
            row.get("quote") or "",
        )

        if matched is None:
            row["canonical_url"] = row_canonical
            row["event_fingerprint"] = new_event_fingerprint(
                f"{row.get('entity_type')}:{row.get('entity_id')}",
                row.get("source_title"),
                row.get("quote"),
                row.get("created_at") or "",
            )
            row["observations"] = [observation]
            row["provenance"] = [observation]
            row["observation_count"] = 1
            row["archived_observation_count"] = int(
                observation["archived_duplicate"]
            )
            row["source_count"] = 1 if row_canonical else 0
            groups.append(row)
            continue

        matched["observations"].append(observation)
        matched["observation_count"] = len(matched["observations"])
        matched["archived_observation_count"] = sum(
            int(item.get("archived_duplicate") or 0)
            for item in matched["observations"]
        )
        if not any(
            item["provenance_key"] == observation["provenance_key"]
            for item in matched["provenance"]
        ):
            matched["provenance"].append(observation)
        matched["source_count"] = len({
            item["canonical_url"]
            for item in matched["provenance"]
            if item["canonical_url"]
        })
    return groups

def get_entries(entity_type, entity_id, limit=50):
    with conn() as c:
        rows = _evidence_rows(c, entity_type, entity_id)
        return group_evidence_events(rows)[:limit]

def get_recent_entries(limit=40):
    with conn() as c:
        rows = _evidence_rows(c)
        return group_evidence_events(rows)[:limit]

[redacted secret-like line]
    return hashlib.sha256((ip or "").encode()).hexdigest()[:16]

def get_stats():
    with conn() as c:
        rows = _evidence_rows(c)
        events = group_evidence_events(rows)
        return {
            'total_jobs': c.execute("SELECT COUNT(*) FROM jobs").fetchone()[0],
            'total_degrees': c.execute("SELECT COUNT(*) FROM degrees").fetchone()[0],
            'total_entries': len(events),
            'total_observations': len(rows),
            'duplicate_observations': len(rows) - len(events),
        }

def get_jobs_paginated(page=1, per_page=20):
    offset = (page - 1) * per_page
    with conn() as c:
        total = c.execute("SELECT COUNT(*) FROM jobs").fetchone()[0]
        rows = c.execute(
            "SELECT * FROM jobs ORDER BY ai_exposure_score DESC, cope_score DESC LIMIT ? OFFSET ?",
            (per_page, offset)).fetchall()
        return [dict(r) for r in rows], total

def get_degrees_paginated(page=1, per_page=20):
    offset = (page - 1) * per_page
    with conn() as c:
        total = c.execute("SELECT COUNT(*) FROM degrees").fetchone()[0]
        rows = c.execute(
            "SELECT * FROM degrees ORDER BY ai_exposure_score DESC, cope_score DESC LIMIT ? OFFSET ?",
            (per_page, offset)).fetchall()
        return [dict(r) for r in rows], total
```
