Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ dist/
build/
.mypy_cache/
.ruff_cache/
_site/
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ tinyquery = "tinyquery.cli:main"
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
# Name the package explicitly: site/ and benchmarks/ hold scripts, and
# automatic discovery refuses a flat layout with more than one candidate.
packages = ["tinyquery"]

[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
139 changes: 139 additions & 0 deletions site/app.js
Original file line number Diff line number Diff line change
@@ -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);
});
54 changes: 54 additions & 0 deletions site/build.py
Original file line number Diff line number Diff line change
@@ -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())
Loading
Loading