---
type: "Source File"
title: "\"\"\"SQLite database module for CopeCheck Funding site.\"\"\""
description: "\"\"\"SQLite database module for CopeCheck Funding site.\"\"\" import sqlite3 import os from datetime import datetime DB_PATH = os.environ.get( \"FUNDING_DB_PATH\", os.path.join(os.path.dirname(os.path.abspath(__file__))."
resource: "https://funding.copecheck.com"
tags: ["copecheck", "funding", "source-file", "py"]
timestamp: "2026-05-02T13:48:24Z"
site: "funding"
source_path: "copecheck-funding/db.py"
---

# """SQLite database module for CopeCheck Funding site."""

Source path: `copecheck-funding/db.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-02T13:48:24Z`

```py
"""SQLite database module for CopeCheck Funding site."""

import sqlite3
import os
from datetime import datetime

DB_PATH = os.environ.get(
    "FUNDING_DB_PATH",
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "funding.db"),
)


def get_db():
    """Get a database connection with row factory."""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys=ON")
    return conn


def init_db():
    """Create tables if they don't exist and seed grant targets."""
    conn = get_db()
    cur = conn.cursor()

    cur.execute("""
        CREATE TABLE IF NOT EXISTS applications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            organisation TEXT NOT NULL,
            date_applied TEXT NOT NULL,
            amount_requested TEXT,
            status TEXT NOT NULL DEFAULT 'pending',
            response_url TEXT,
            notes TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)

    cur.execute("""
        CREATE TABLE IF NOT EXISTS targets (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            organisation TEXT NOT NULL,
            relevance TEXT,
            grant_range TEXT,
            application_url TEXT,
            status TEXT NOT NULL DEFAULT 'planned',
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)

    cur.execute("""
        CREATE TABLE IF NOT EXISTS suggestions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            organisation TEXT NOT NULL,
            url TEXT,
            relevance TEXT,
            email TEXT,
            approved INTEGER NOT NULL DEFAULT 0,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
    """)

    # Seed grant targets if table is empty
    count = cur.execute("SELECT COUNT(*) FROM targets").fetchone()[0]
    if count == 0:
        seed_targets = [
            (
                "Mozilla Foundation",
                "Technology and society grants focused on internet health, AI accountability, and open-source infrastructure — directly aligned with CopeCheck's transparent, automated approach to labour market monitoring.",
                "$10,000 – $100,000",
                "https://foundation.mozilla.org/en/what-we-fund/",
                "planned",
            ),
            (
                "Open Society Foundations",
                "Fund democratic governance and economic justice initiatives. CopeCheck's transparent labour market data supports informed policy debate on AI disruption.",
                "$25,000 – $250,000",
                "https://www.opensocietyfoundations.org/grants",
                "planned",
            ),
            (
                "Ford Foundation – Future of Work",
                "Dedicated programme examining how technology reshapes work and economic opportunity — a near-exact match for CopeCheck's mission.",
                "$50,000 – $500,000",
                "https://www.fordfoundation.org/work/challenging-inequality/future-of-work-ers/",
                "planned",
            ),
            (
                "Omidyar Network",
                "Invests in responsible technology and governance innovation. CopeCheck's framework-driven, data-first approach fits their emphasis on tech accountability.",
                "$25,000 – $250,000",
                "https://omidyar.com/",
                "planned",
            ),
            (
                "Open Philanthropy",
                "Major funder in AI safety and policy. CopeCheck's empirical tracking of AI's actual labour market impact complements speculative risk analysis with ground-truth data.",
                "$50,000 – $500,000+",
                "https://www.openphilanthropy.org/how-to-apply/",
                "planned",
            ),
            (
                "Luminate",
                "Part of the Omidyar Group, focused on technology and society — specifically civic empowerment and data-driven accountability.",
                "$25,000 – $150,000",
                "https://luminategroup.com/",
                "planned",
            ),
            (
                "Rockefeller Foundation",
                "Economic opportunity and equitable growth programmes. CopeCheck's cross-country labour market data supports evidence-based policy on technological transitions.",
                "$50,000 – $250,000",
                "https://www.rockefellerfoundation.org/grants/",
                "planned",
            ),
            (
                "Knight Foundation",
                "Funds informed and engaged communities through technology and journalism. CopeCheck's public data dashboards serve as civic infrastructure for understanding AI's workforce impact.",
                "$25,000 – $150,000",
                "https://knightfoundation.org/apply/",
                "planned",
            ),
            (
                "MacArthur Foundation",
                "Technology in the public interest grants. CopeCheck's open, automated monitoring of AI's labour market effects is a natural fit for their civic tech portfolio.",
                "$50,000 – $500,000",
                "https://www.macfound.org/info-grantseekers/grantmaking-guidelines",
                "planned",
            ),
            (
                "European Cultural Foundation",
                "Supports democratic culture and civic engagement across Europe. CopeCheck's EU-specific site and cross-country analysis serve European policy needs.",
                "€10,000 – €50,000",
                "https://culturalfoundation.eu/grants/",
                "planned",
            ),
            (
                "Nesta",
                "UK innovation foundation focused on how technology shapes society. CopeCheck's UK-specific site and data-driven approach align with Nesta's evidence-based mission.",
                "£10,000 – £100,000",
                "https://www.nesta.org.uk/",
                "planned",
            ),
            (
                "Joseph Rowntree Foundation",
                "UK foundation studying poverty, work, and economic insecurity. CopeCheck's labour market disruption data directly informs their research on precarious work and inequality.",
                "£10,000 – £80,000",
                "https://www.jrf.org.uk/about-us/grants-and-partnerships",
                "planned",
            ),
            (
                "Nuffield Foundation",
                "Funds research on social wellbeing across education, welfare, and justice in the UK. CopeCheck's empirical tracking of employment disruption supports evidence-based welfare policy.",
                "£10,000 – £150,000",
                "https://www.nuffieldfoundation.org/funding",
                "planned",
            ),
            (
                "Reset.tech",
                "Counters digital threats to democracy. CopeCheck's transparent methodology and automated analysis model responsible tech practices in a space dominated by opaque corporate research.",
                "$25,000 – $100,000",
                "https://www.reset.tech/",
                "planned",
            ),
            (
                "AI Safety / EA-adjacent Grants",
                "Effective Altruism and AI safety funders increasingly recognise that near-term labour disruption is a concrete, measurable AI risk. CopeCheck provides the empirical evidence base.",
                "$10,000 – $200,000",
                "https://funds.effectivealtruism.org/",
                "planned",
            ),
            (
                "Shuttleworth Foundation",
                "Fellowship programme for openness advocates. CopeCheck's fully transparent, open methodology and public data align with Shuttleworth's commitment to open knowledge infrastructure.",
                "$100,000 – $275,000 (fellowship)",
                "https://shuttleworthfoundation.org/apply/",
                "planned",
            ),
        ]
        cur.executemany(
            "INSERT INTO targets (organisation, relevance, grant_range, application_url, status) VALUES (?, ?, ?, ?, ?)",
            seed_targets,
        )

    conn.commit()
    conn.close()


def get_applications(page=1, per_page=20):
    """Get paginated applications."""
    conn = get_db()
    offset = (page - 1) * per_page
    total = conn.execute("SELECT COUNT(*) FROM applications").fetchone()[0]
    rows = conn.execute(
        "SELECT * FROM applications ORDER BY date_applied DESC LIMIT ? OFFSET ?",
        (per_page, offset),
    ).fetchall()
    conn.close()
    return rows, total


def get_targets():
    """Get all grant targets."""
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM targets ORDER BY organisation ASC"
    ).fetchall()
    conn.close()
    return rows


def add_suggestion(organisation, url, relevance, email):
    """Add a funding suggestion."""
    conn = get_db()
    conn.execute(
        "INSERT INTO suggestions (organisation, url, relevance, email) VALUES (?, ?, ?, ?)",
        (organisation, url, relevance, email),
    )
    conn.commit()
    conn.close()


def get_approved_suggestions():
    """Get approved suggestions."""
    conn = get_db()
    rows = conn.execute(
        "SELECT * FROM suggestions WHERE approved = 1 ORDER BY created_at DESC"
    ).fetchall()
    conn.close()
    return rows
```
