DEV Community

Cover image for Mirror a CSV dataset to DoltHub every week with its write API
Elliot Marsh
Elliot Marsh

Posted on

Mirror a CSV dataset to DoltHub every week with its write API

We publish an open dataset of food festivals with the dates of their next editions (CC BY 4.0). It lives as CSV and JSON in a GitHub repository and as a citable record on Zenodo. Both are good for downloading; neither lets someone ask a question without downloading first. DoltHub fills that gap: it hosts Dolt databases, which are MySQL-compatible and versioned like Git, so anyone can run SQL in the browser or over HTTP, and every weekly refresh becomes a commit with a diff.

You do not need the dolt CLI to publish there. This post shows how we mirror the dataset weekly with nothing but HTTP calls from Python.

The shape of the write API

DoltHub's v1alpha1 API has a few properties worth knowing before you write code:

  • Reads are a GET with the SQL in q: GET /api/v1alpha1/{owner}/{db}/{ref}?q=.... Public databases need no token.
  • Writes are asynchronous. POST /api/v1alpha1/{owner}/{db}/write/{from_branch}/{to_branch} with the SQL in a JSON body returns an operation name. You poll GET /api/v1alpha1/{owner}/{db}/write?operationName=... until it says done.
  • The write creates the target branch from the source branch if it does not exist. Posting to the same endpoint with no query merges the branches.
  • Auth is a header: authorization: token <your token>, with a token created in your DoltHub settings.

Reading needs nothing

Before writing anything, this is what a reader gets, no key required:

curl -s -G "https://www.dolthub.com/api/v1alpha1/tablejourney/food-festivals/main" \
  --data-urlencode "q=SELECT month, COUNT(*) AS festivals FROM festivals GROUP BY month ORDER BY festivals DESC LIMIT 3"
Enter fullscreen mode Exit fullscreen mode
"rows": [{"month": "October", "festivals": "197"},
         {"month": "September", "festivals": "190"},
         {"month": "November", "festivals": "161"}]
Enter fullscreen mode Exit fullscreen mode

Note that numbers come back as strings.

A small client

One function handles every call, including the polling. The detail that took a bug to find: a write that DoltHub rejects outright (a SQL syntax error, say) answers HTTP 400 with an empty operation name. If you only poll when an operation exists, that failure looks like success. Treat a missing operation on a write as an error:

import json, os, time, urllib.error, urllib.parse, urllib.request

API = "https://www.dolthub.com/api/v1alpha1"
TOKEN = os.environ["DOLTHUB_TOKEN"]  # an API token from your DoltHub settings

def dolt(method, path, params=None, body=None, token=TOKEN):
    url = f"{API}{path}" + (f"?{urllib.parse.urlencode(params)}" if params else "")
    req = urllib.request.Request(
        url,
        data=json.dumps(body).encode() if body is not None else None,
        method=method,
        headers={"authorization": f"token {token}", "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            res = json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        res = json.loads(e.read() or b"{}")
    if method == "POST" and "/write/" in path:
        op = res.get("operation_name")
        if not op:  # rejected before an operation was queued
            raise RuntimeError(res.get("query_execution_message") or res)
        owner_db = path.split("/write/")[0]
        for _ in range(100):
            time.sleep(3)
            st = dolt("GET", f"{owner_db}/write", {"operationName": op})
            if st.get("done"):
                det = st.get("res_details") or {}
                if det.get("query_execution_status") != "Success":
                    raise RuntimeError(det)
                return det
        raise RuntimeError("write did not finish")
    return res
Enter fullscreen mode Exit fullscreen mode

Create the database once

probe = dolt("GET", "/tablejourney/food-festivals/main", {"q": "SHOW TABLES"})
if probe.get("query_execution_status") != "Success":
    dolt("POST", "/database", body={
        "ownerName": "tablejourney",
        "repoName": "food-festivals",
        "visibility": "public",
        "description": "Open calendar of food festivals worldwide with next dates (CC BY 4.0)",
    })
Enter fullscreen mode Exit fullscreen mode

Refresh on a dated branch, then merge

Writing straight to main in several steps would leave readers looking at a half-loaded table between steps. Instead, each refresh writes to a branch named for the day and merges at the end, so main moves in one step:

branch = f"refresh-{dt.date.today().isoformat()}"
w = f"/tablejourney/food-festivals/write/main/{branch}"

dolt("POST", w, body={"query": CREATE_TABLE})          # CREATE TABLE IF NOT EXISTS ...
dolt("POST", w, body={"query": "DELETE FROM festivals"})
for i in range(0, len(rows), 150):
    values = ",\n".join("(" + ", ".join(sql(r[f]) for f in FIELDS) + ")" for r in rows[i:i + 150])
    dolt("POST", w, body={"query": f"INSERT INTO festivals ({', '.join(FIELDS)}) VALUES {values}"})

dolt("POST", f"/tablejourney/food-festivals/write/{branch}/main")   # no query: merge
Enter fullscreen mode Exit fullscreen mode

A full replace keeps the code simple, and Dolt's diff still shows exactly which rows changed between weeks, because it compares content, not the statements that produced it. Batches of 150 rows kept each statement comfortably small.

Values: there are no bound parameters

The write API takes SQL text, so values must be escaped by you. Keep it to one small, boring function and send nothing through it that you did not produce yourself:

def sql(v):
    if v is None or v == "":
        return "NULL"
    if isinstance(v, bool):
        return "TRUE" if v else "FALSE"
    return "'" + str(v).replace("\\", "\\\\").replace("'", "\\'") + "'"
Enter fullscreen mode Exit fullscreen mode

Linters flag string-built SQL, and they are right to. Here the input is our own export, and the comment beside the call says why there is no alternative.

README and licence travel with the data

Dolt keeps documentation in a system table, so the dataset card and licence ship with the database and show on its DoltHub page:

for doc, text in (("README.md", readme), ("LICENSE.md", licence)):
    dolt("POST", w, body={"query": f"REPLACE INTO dolt_docs (doc_name, doc_text) VALUES ({sql(doc)}, {sql(text)})"})
Enter fullscreen mode Exit fullscreen mode

Skip the week when nothing changed

The job runs weekly, but a week can pass with no data change. We hash the CSV and compare with the last published hash, stored with the date it was last checked. The check date matters for monitoring: a separate health check reads it, so a quiet week is not mistaken for a dead job.

digest = hashlib.sha256(csv_bytes).hexdigest()
if last.get("sha") == digest:
    save("dolthub-dataset", {**last, "checked": today})
    return
Enter fullscreen mode Exit fullscreen mode

Hash the rows only. Our README carries the snapshot date, so hashing it too made every week look changed.

Verify from the outside

After the first publish, check with a public, unauthenticated read, which is what your users will do:

curl -s -G "https://www.dolthub.com/api/v1alpha1/tablejourney/food-festivals/main" \
  --data-urlencode "q=SELECT COUNT(*) AS n FROM festivals"
Enter fullscreen mode Exit fullscreen mode

The database is public at https://www.dolthub.com/repositories/tablejourney/food-festivals, and the summary of what is in it is at https://tablejourney.com/festivals/statistics/. If you publish open data, a SQL-queryable mirror is a small amount of code for a large gain in what people can do with it.

Top comments (0)