---
type: "Source File"
title: "import sqlite3"
description: "import sqlite3 import uuid import os from datetime import datetime, date DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'quiz.db') def conn(): c = sqlite3.connect(DB_PATH) c.row_factory =."
resource: "https://quiz.copecheck.com"
tags: ["copecheck", "quiz", "source-file", "py"]
timestamp: "2026-05-03T18:57:43Z"
site: "quiz"
source_path: "copecheck-quiz/db.py"
---

# import sqlite3

Source path: `copecheck-quiz/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-03T18:57:43Z`

```py
import sqlite3
import uuid
import os
from datetime import datetime, date

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

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

def init():
    c = conn()
    c.executescript("""
    CREATE TABLE IF NOT EXISTS quiz_sessions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        session_id TEXT UNIQUE NOT NULL,
        started_at TEXT,
        completed_at TEXT,
[redacted secret-like line]
        cope_score REAL,
        cope_type TEXT,
        spectrum_figure TEXT,
        spectrum_name TEXT,
        screwed_job TEXT,
        screwed_industry TEXT,
        screwed_experience TEXT,
        screwed_computer_pct INTEGER,
        screwed_worry INTEGER,
        comments_text TEXT,
        oracle_response TEXT,
        argue_count INTEGER DEFAULT 0,
        display_name TEXT,
        leaderboard_visible INTEGER DEFAULT 0
    );
    CREATE TABLE IF NOT EXISTS quiz_answers (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        session_id TEXT NOT NULL,
        question_num INTEGER,
        answer_index INTEGER,
        cope_points INTEGER,
        cope_type TEXT
    );
    CREATE TABLE IF NOT EXISTS quiz_stats (
        date TEXT PRIMARY KEY,
        quizzes_completed INTEGER DEFAULT 0,
        avg_cope_score REAL DEFAULT 0
    );
    CREATE INDEX IF NOT EXISTS idx_sessions_sid ON quiz_sessions(session_id);
    CREATE INDEX IF NOT EXISTS idx_answers_sid ON quiz_answers(session_id);
    """)
    c.commit()
    c.close()

SPECTRUM = [
    (12, "geoff-hinton", "Geoff Hinton", "You see the discontinuity."),
    (25, "eliezer-yudkowsky", "Eliezer Yudkowsky", "Doomer with receipts."),
    (38, "daron-acemoglu", "Daron Acemoglu", "Cautious economist, data-first."),
    (50, "yuval-harari", "Yuval Noah Harari", "Philosopher of displacement."),
    (62, "satya-nadella", "Satya Nadella", "Optimistic but hedging."),
    (75, "sam-altman", "Sam Altman", "Trust the process. Probably."),
    (88, "marc-andreessen", "Marc Andreessen", "Software eats world. That's good."),
    (100, "adam-dangelo", "Adam D'Angelo", "Maximum cope. Nothing to see here."),
]

def get_spectrum(score):
    for threshold, slug, name, desc in SPECTRUM:
        if score <= threshold:
            return slug, name, desc
    return SPECTRUM[-1][1], SPECTRUM[-1][2], SPECTRUM[-1][3]

[redacted secret-like line]
    sid = str(uuid.uuid4())
    score = min(data.get('cope_score', 0), 100)
    cope_type = data.get('primary_cope_type', 'unknown')
    slug, name, desc = get_spectrum(score)

    c = conn()
    c.execute("""
        INSERT INTO quiz_sessions
[redacted secret-like line]
         spectrum_figure, spectrum_name, screwed_job, screwed_industry,
         screwed_experience, screwed_computer_pct, screwed_worry, comments_text)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    """, (
[redacted secret-like line]
        score, cope_type, slug, name,
        data.get('screwed_job'), data.get('screwed_industry'),
        data.get('screwed_experience'), data.get('screwed_computer_pct'),
        data.get('screwed_worry'), data.get('comments_text')
    ))

    for ans in data.get('answers', []):
        c.execute("""
            INSERT INTO quiz_answers (session_id, question_num, answer_index, cope_points, cope_type)
            VALUES (?,?,?,?,?)
        """, (sid, ans['question_num'], ans['answer_index'], ans['cope_points'], ans['cope_type']))

    # Update daily stats
    today = date.today().isoformat()
    row = c.execute("SELECT * FROM quiz_stats WHERE date=?", (today,)).fetchone()
    if row:
        new_count = row['quizzes_completed'] + 1
        new_avg = ((row['avg_cope_score'] * row['quizzes_completed']) + score) / new_count
        c.execute("UPDATE quiz_stats SET quizzes_completed=?, avg_cope_score=? WHERE date=?",
                  (new_count, new_avg, today))
    else:
        c.execute("INSERT INTO quiz_stats (date, quizzes_completed, avg_cope_score) VALUES (?,?,?)",
                  (today, 1, score))

    c.commit()
    c.close()
    return sid, score, slug, name, desc, cope_type

def get_session(sid):
    c = conn()
    row = c.execute("SELECT * FROM quiz_sessions WHERE session_id=?", (sid,)).fetchone()
    if not row:
        c.close()
        return None
    answers = c.execute("SELECT * FROM quiz_answers WHERE session_id=? ORDER BY question_num", (sid,)).fetchall()
    c.close()
    return dict(row), [dict(a) for a in answers]

def update_oracle(sid, response):
    c = conn()
    c.execute("UPDATE quiz_sessions SET oracle_response=? WHERE session_id=?", (response, sid))
    c.commit()
    c.close()

def increment_argue(sid):
    c = conn()
    c.execute("UPDATE quiz_sessions SET argue_count = argue_count + 1 WHERE session_id=?", (sid,))
    c.commit()
    row = c.execute("SELECT argue_count FROM quiz_sessions WHERE session_id=?", (sid,)).fetchone()
    c.close()
    return row['argue_count'] if row else 0

def get_leaderboard():
    c = conn()
    most_coped = c.execute(
        "SELECT session_id, cope_score, spectrum_name, cope_type, completed_at, display_name FROM quiz_sessions WHERE leaderboard_visible=1 ORDER BY cope_score DESC LIMIT 20"
    ).fetchall()
    most_lucid = c.execute(
        "SELECT session_id, cope_score, spectrum_name, cope_type, completed_at, display_name FROM quiz_sessions WHERE leaderboard_visible=1 ORDER BY cope_score ASC LIMIT 20"
    ).fetchall()
    type_counts = c.execute(
        "SELECT cope_type, COUNT(*) as cnt FROM quiz_sessions GROUP BY cope_type ORDER BY cnt DESC"
    ).fetchall()
    stats = c.execute(
        "SELECT date, quizzes_completed, avg_cope_score FROM quiz_stats ORDER BY date DESC LIMIT 30"
    ).fetchall()
    c.close()
    return [dict(r) for r in most_coped], [dict(r) for r in most_lucid], [dict(r) for r in type_counts], [dict(r) for r in stats]

def get_recent(page=1, per_page=20):
    c = conn()
    offset = (page - 1) * per_page
    total = c.execute("SELECT COUNT(*) FROM quiz_sessions").fetchone()[0]
    rows = c.execute(
        "SELECT session_id, cope_score, spectrum_name, spectrum_figure, completed_at FROM quiz_sessions ORDER BY completed_at DESC LIMIT ? OFFSET ?",
        (per_page, offset)
    ).fetchall()
    c.close()
    return [dict(r) for r in rows], total

def get_stats():
    c = conn()
    total = c.execute("SELECT COUNT(*) FROM quiz_sessions").fetchone()[0]
    avg = c.execute("SELECT AVG(cope_score) FROM quiz_sessions").fetchone()[0] or 0
    top_type = c.execute(
        "SELECT cope_type, COUNT(*) as cnt FROM quiz_sessions GROUP BY cope_type ORDER BY cnt DESC LIMIT 1"
    ).fetchone()
    c.close()
    return {
        'total_quizzes': total,
        'avg_score': round(avg, 1),
        'top_cope_type': dict(top_type) if top_type else None
    }

def submit_to_leaderboard(sid, display_name):
    """Mark a session as visible on leaderboard with display name."""
    c = conn()
    c.execute(
        "UPDATE quiz_sessions SET display_name=?, leaderboard_visible=1 WHERE session_id=?",
        (display_name, sid)
    )
    c.commit()
    c.close()

init()
```
