From e536b5233d8ac041643c0939885bf54095930ca6 Mon Sep 17 00:00:00 2001
From: SpookyJumpyBeans <116844292+SpookyJumpyBeans@users.noreply.github.com>
Date: Sat, 3 Oct 2026 22:26:58 -0400
Subject: [PATCH 1/2] Run both engines in the browser with Pyodide
site/ is a static page: build.py bundles the tinyquery and tinydelta
sources with demo.py into packages.zip, and app.js unpacks that into
Pyodide and runs queries through demo.run() under EXPLAIN ANALYZE.
demo.py builds a shop whose tinydelta orders table has six versions
(three appends, an overwrite, a restore) and a customers table skewed so
that the first preset query shows a 25x misestimate.
Pyodide has no os.link, which tinydelta uses to publish a commit, so the
demo substitutes exclusive create plus copy when link is missing. That
is only safe because a browser tab runs one Python thread. demo.py has no
browser dependencies, so tests/test_site_demo.py runs it natively.
---
.gitignore | 1 +
README.md | 18 ++++
site/app.js | 139 +++++++++++++++++++++++++++++
site/build.py | 54 +++++++++++
site/demo.py | 192 ++++++++++++++++++++++++++++++++++++++++
site/index.html | 65 ++++++++++++++
site/style.css | 177 ++++++++++++++++++++++++++++++++++++
tests/test_site_demo.py | 98 ++++++++++++++++++++
8 files changed, 744 insertions(+)
create mode 100644 site/app.js
create mode 100644 site/build.py
create mode 100644 site/demo.py
create mode 100644 site/index.html
create mode 100644 site/style.css
create mode 100644 tests/test_site_demo.py
diff --git a/.gitignore b/.gitignore
index 7363050..55dc4f8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,4 @@ dist/
build/
.mypy_cache/
.ruff_cache/
+_site/
diff --git a/README.md b/README.md
index 25bbe41..ec80133 100644
--- a/README.md
+++ b/README.md
@@ -207,6 +207,24 @@ pip install -e ".[dev]"
pytest
```
+## In the browser
+
+`site/` is a static page that runs tinyquery and tinydelta in the browser with
+[Pyodide](https://pyodide.org). It builds a small shop -- a tinydelta `orders`
+table with six versions, plus customers and line items -- and runs every query
+under `EXPLAIN ANALYZE`.
+
+```bash
+pip install -e ".[delta]"
+python site/build.py
+python -m http.server -d _site
+```
+
+Pyodide has no hard links, and tinydelta publishes a commit by linking a
+finished temp file to its version name. The demo stands in with exclusive
+create plus copy, which is only safe because a browser tab runs one Python
+thread. Run natively, the real `link()` is used.
+
## How a query runs
```text
diff --git a/site/app.js b/site/app.js
new file mode 100644
index 0000000..6ccb460
--- /dev/null
+++ b/site/app.js
@@ -0,0 +1,139 @@
+// Loads Pyodide, unpacks tinyquery + tinydelta + demo.py from packages.zip,
+// builds the demo tables, and runs queries through demo.run().
+
+import { loadPyodide } from "https://cdn.jsdelivr.net/pyodide/v314.0.7/full/pyodide.mjs";
+
+const MAX_ROWS_SHOWN = 100;
+
+const el = {
+ sql: document.getElementById("sql"),
+ run: document.getElementById("run"),
+ status: document.getElementById("status"),
+ presets: document.getElementById("presets"),
+ plan: document.getElementById("plan"),
+ results: document.getElementById("results"),
+ history: document.getElementById("orders-history"),
+};
+
+let demo = null;
+
+function setStatus(text, isError = false) {
+ el.status.textContent = text;
+ el.status.classList.toggle("error", isError);
+}
+
+async function boot() {
+ const started = performance.now();
+ setStatus("Loading Python…");
+ const pyodide = await loadPyodide();
+
+ setStatus("Loading tinyquery and tinydelta…");
+ const response = await fetch("packages.zip");
+ if (!response.ok) throw new Error(`packages.zip: HTTP ${response.status}`);
+ pyodide.unpackArchive(await response.arrayBuffer(), "zip", { extractDir: "/lib" });
+ pyodide.runPython("import sys; sys.path.insert(0, '/lib')");
+ demo = pyodide.pyimport("demo");
+
+ setStatus("Building tables…");
+ renderHistory(JSON.parse(demo.setup("/data")));
+ renderPresets(JSON.parse(demo.presets()));
+
+ el.sql.disabled = false;
+ el.run.disabled = false;
+ setStatus(`Ready in ${((performance.now() - started) / 1000).toFixed(1)}s`);
+ runQuery();
+}
+
+function renderHistory(commits) {
+ const latest = commits[commits.length - 1];
+ el.history.textContent =
+ `${commits.length} versions (v0–v${latest.version}), ${latest.rows.toLocaleString()} rows at latest`;
+}
+
+function renderPresets(presets) {
+ el.presets.replaceChildren(
+ ...presets.map((preset, i) => {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.textContent = preset.name;
+ button.setAttribute("aria-pressed", String(i === 0));
+ button.addEventListener("click", () => {
+ for (const other of el.presets.children) other.setAttribute("aria-pressed", "false");
+ button.setAttribute("aria-pressed", "true");
+ el.sql.value = preset.sql;
+ runQuery();
+ });
+ return button;
+ }),
+ );
+ el.sql.value = presets[0].sql;
+}
+
+function runQuery() {
+ if (!demo) return;
+ const started = performance.now();
+ const result = JSON.parse(demo.run(el.sql.value));
+ const elapsed = performance.now() - started;
+
+ if (result.error) {
+ setStatus("Query failed", true);
+ const message = document.createElement("p");
+ message.className = "error-text";
+ message.textContent = result.error;
+ el.results.replaceChildren(message);
+ el.plan.textContent = "";
+ return;
+ }
+
+ const n = result.rows.length;
+ setStatus(`${n.toLocaleString()} row${n === 1 ? "" : "s"} in ${elapsed.toFixed(0)}ms, orders v${result.version}`);
+ el.plan.textContent = result.text;
+ renderRows(result.columns, result.rows);
+}
+
+function renderRows(columns, rows) {
+ const table = document.createElement("table");
+ const head = table.createTHead().insertRow();
+ columns.forEach((name, i) => {
+ const th = document.createElement("th");
+ th.scope = "col";
+ th.textContent = name;
+ if (rows.length && typeof rows[0][i] === "number") th.className = "num";
+ head.append(th);
+ });
+ const body = table.createTBody();
+ for (const row of rows.slice(0, MAX_ROWS_SHOWN)) {
+ const tr = body.insertRow();
+ for (const value of row) {
+ const td = tr.insertCell();
+ td.textContent = value === null ? "NULL" : formatValue(value);
+ if (typeof value === "number") td.className = "num";
+ }
+ }
+ const parts = [table];
+ if (rows.length > MAX_ROWS_SHOWN) {
+ const note = document.createElement("p");
+ note.className = "note";
+ note.textContent = `Showing ${MAX_ROWS_SHOWN} of ${rows.length.toLocaleString()} rows.`;
+ parts.push(note);
+ }
+ el.results.replaceChildren(...parts);
+}
+
+function formatValue(value) {
+ if (typeof value === "number" && !Number.isInteger(value)) return value.toFixed(2);
+ return String(value);
+}
+
+el.run.addEventListener("click", runQuery);
+el.sql.addEventListener("keydown", (event) => {
+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault();
+ runQuery();
+ }
+});
+
+boot().catch((error) => {
+ console.error(error);
+ setStatus(`Failed to start: ${error.message}`, true);
+});
diff --git a/site/build.py b/site/build.py
new file mode 100644
index 0000000..207ffe3
--- /dev/null
+++ b/site/build.py
@@ -0,0 +1,54 @@
+"""Assemble the static demo into _site/.
+
+Copies the page files and bundles what Pyodide needs into packages.zip:
+the tinyquery package from this repo, tinydelta from wherever Python imports
+it (so install the delta extra first), and demo.py. The page unpacks the zip
+into Pyodide's filesystem and imports from it like any installed package.
+
+Run:
+ pip install -e ".[delta]"
+ python site/build.py
+ python -m http.server -d _site
+"""
+
+from __future__ import annotations
+
+import argparse
+import shutil
+import zipfile
+from pathlib import Path
+
+SITE = Path(__file__).resolve().parent
+ROOT = SITE.parent
+PAGE_FILES = ("index.html", "style.css", "app.js")
+
+
+def build(out: Path) -> Path:
+ import tinydelta
+
+ if out.exists():
+ shutil.rmtree(out)
+ out.mkdir(parents=True)
+ for name in PAGE_FILES:
+ shutil.copy2(SITE / name, out / name)
+
+ bundle = out / "packages.zip"
+ with zipfile.ZipFile(bundle, "w", zipfile.ZIP_DEFLATED) as archive:
+ for package in (ROOT / "tinyquery", Path(tinydelta.__file__).parent):
+ for source in sorted(package.rglob("*.py")):
+ archive.write(source, source.relative_to(package.parent).as_posix())
+ archive.write(SITE / "demo.py", "demo.py")
+ return bundle
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--out", type=Path, default=ROOT / "_site")
+ args = parser.parse_args()
+ bundle = build(args.out)
+ print(f"built {args.out} ({bundle.stat().st_size:,} byte bundle)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/site/demo.py b/site/demo.py
new file mode 100644
index 0000000..bb34942
--- /dev/null
+++ b/site/demo.py
@@ -0,0 +1,192 @@
+"""The browser demo's Python side: build a small shop, then run queries on it.
+
+app.js unpacks this file into Pyodide next to the tinyquery and tinydelta
+sources, calls `setup()` once, and then `run()` for every query. Nothing here
+knows about the browser, so tests/test_site_demo.py runs it natively as well.
+
+The shop has three tables:
+
+ * `orders` is a tinydelta table with a history worth travelling through:
+ three yearly appends, an overwrite that drops 2023, and a restore that
+ brings it back.
+ * `customers` has a skewed `tier` column. Two customers in two hundred are
+ platinum, but equality selectivity assumes all four tiers are equally
+ common, so `WHERE c.tier = 'platinum'` is estimated 25x too high.
+ * `lineitem` has four items per order, for every order any version holds.
+
+`customers` and `lineitem` never change, so they are registered in memory.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import random
+import shutil
+from pathlib import Path
+
+from tinydelta import DeltaTable, Schema
+from tinyquery.catalog import Catalog
+from tinyquery.engine import explain_analyze
+from tinyquery.profiler import format_analyze
+from tinyquery.schema import Column, Row
+from tinyquery.schema import Schema as RowSchema
+
+if not hasattr(os, "link"):
+ # Pyodide's filesystem has no hard links, and tinydelta publishes a commit
+ # by linking a finished temp file to its version name. Stand in with an
+ # exclusive create plus a copy. That gives up link()'s atomicity, which is
+ # only acceptable because a browser tab runs a single Python thread: there
+ # is no second writer to race and no reader to catch a half-copied file.
+ # Native runs, including the tests, keep the real link().
+ def _link(src, dst, *args, **kwargs):
+ with open(src, "rb") as source, open(dst, "xb") as target:
+ shutil.copyfileobj(source, target)
+
+ os.link = _link
+
+REGIONS = ("west", "east", "north", "south")
+SKUS = ("widget", "gadget", "gizmo", "doohickey")
+# (tier, how many customers have it). Skewed on purpose; see the module docstring.
+TIERS = (("platinum", 2), ("gold", 18), ("silver", 60), ("bronze", 120))
+ORDERS_PER_YEAR = 600
+ITEMS_PER_ORDER = 4
+YEARS = (2023, 2024, 2025)
+
+PRESETS = [
+ {
+ "name": "Join order and a bad estimate",
+ "sql": (
+ "SELECT c.tier, COUNT(o.id) AS orders, SUM(l.revenue) AS revenue\n"
+ "FROM lineitem l\n"
+ "JOIN orders o ON l.order_id = o.id\n"
+ "JOIN customers c ON o.customer_id = c.id\n"
+ "WHERE c.tier = 'platinum'\n"
+ "GROUP BY c.tier"
+ ),
+ },
+ {
+ "name": "Orders per year",
+ "sql": (
+ "SELECT o.year, COUNT(o.id) AS orders\n"
+ "FROM orders o\n"
+ "GROUP BY o.year\n"
+ "ORDER BY o.year"
+ ),
+ },
+ {
+ "name": "Top orders by revenue",
+ "sql": (
+ "SELECT o.id, o.region, SUM(l.revenue) AS total\n"
+ "FROM orders o\n"
+ "JOIN lineitem l ON o.id = l.order_id\n"
+ "WHERE o.year = 2024\n"
+ "GROUP BY o.id, o.region\n"
+ "ORDER BY total DESC\n"
+ "LIMIT 5"
+ ),
+ },
+]
+
+_state: dict[str, object] = {}
+
+
+def setup(base: str | Path = "/data") -> str:
+ """Build the shop under `base`. Returns the history, as `history()` does."""
+ rng = random.Random(20261003)
+ base = Path(base)
+ base.mkdir(parents=True, exist_ok=True)
+ table_path = base / "orders"
+ if table_path.exists():
+ shutil.rmtree(table_path)
+
+ customers: list[Row] = []
+ for tier, count in TIERS:
+ for _ in range(count):
+ customers.append((len(customers), f"customer {len(customers)}", tier))
+ rng.shuffle(customers)
+
+ by_year: dict[int, list[dict[str, object]]] = {}
+ lineitem: list[Row] = []
+ for y, year in enumerate(YEARS):
+ rows = []
+ for i in range(ORDERS_PER_YEAR):
+ order_id = y * ORDERS_PER_YEAR + i
+ rows.append(
+ {
+ "id": order_id,
+ "customer_id": rng.randrange(len(customers)),
+ "region": rng.choice(REGIONS),
+ "year": year,
+ }
+ )
+ for _ in range(ITEMS_PER_ORDER):
+ lineitem.append((order_id, rng.choice(SKUS), rng.randrange(1, 200)))
+ by_year[year] = rows
+
+ table = DeltaTable.create(
+ table_path,
+ Schema.parse(["id:int", "customer_id:int", "region:str", "year:int"]),
+ )
+ for year in YEARS:
+ table.append(by_year[year])
+ table.overwrite([row for year in YEARS[1:] for row in by_year[year]])
+ table.restore(len(YEARS)) # the version before the overwrite
+
+ _state.update(table_path=table_path, customers=customers, lineitem=lineitem)
+ return history()
+
+
+def history() -> str:
+ """Every commit in `orders`, with the row count of the snapshot it made."""
+ table = DeltaTable.open(_state["table_path"])
+ return json.dumps(
+ [
+ {
+ "version": commit.version,
+ "operation": commit.operation,
+ "timestamp": commit.timestamp,
+ "rows": table.describe(commit.version)["num_records"],
+ }
+ for commit in table.history()
+ ]
+ )
+
+
+def presets() -> str:
+ return json.dumps(PRESETS)
+
+
+def run(
+ sql: str,
+ version: int | None = None,
+ reorder: bool = True,
+ pushdown: bool = True,
+) -> str:
+ """Run `sql` under EXPLAIN ANALYZE against `orders` at `version`.
+
+ Returns JSON: columns, rows, the plan tree, the text rendering of it, and
+ the version actually read. Any failure comes back as {"error": ...} rather
+ than an exception, so the page has one shape to handle.
+ """
+ try:
+ catalog = Catalog()
+ read = catalog.load_delta("orders", _state["table_path"], version=version)
+ _register(catalog, "customers", ["id", "name", "tier"], _state["customers"])
+ _register(catalog, "lineitem", ["order_id", "sku", "revenue"], _state["lineitem"])
+ result = explain_analyze(catalog, sql, reorder=reorder, pushdown=pushdown)
+ except Exception as exc: # the page shows the message; it must not crash
+ return json.dumps({"error": f"{type(exc).__name__}: {exc}"})
+ return json.dumps(
+ {
+ "version": read,
+ "columns": result.schema.names(),
+ "rows": [list(row) for row in result.rows],
+ "plan": result.plan.to_dict(),
+ "text": format_analyze(result.plan),
+ }
+ )
+
+
+def _register(catalog: Catalog, name: str, columns: list[str], rows: list[Row]) -> None:
+ catalog.register(name, RowSchema(tuple(Column(c, table=name) for c in columns)), rows)
diff --git a/site/index.html b/site/index.html
new file mode 100644
index 0000000..f7bfb7d
--- /dev/null
+++ b/site/index.html
@@ -0,0 +1,65 @@
+
+
+
+
+
+ tinyquery + tinydelta
+
+
+
+
+
+
tinyquery + tinydelta
+
+ A SQL engine and a table format, both written from scratch in Python,
+ running in this tab with Pyodide. Every query runs under
+ EXPLAIN ANALYZE, so you can see what the planner expected
+ next to what actually happened.
+