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/pyproject.toml b/pyproject.toml index b6c7865..dda8527 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] 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. +

+ +
+ +
+
+
+

Query

+
+
+ +
+ + Ctrl+Enter + Loading Python… +
+
+ +
+

Plan

+
Run a query to see its plan.
+
+ +
+

Result

+
+
+ +
+

Tables

+
+
orders tinydelta
+
id, customer_id, region, year; loading…
+
customers
+
id, name, tier; 200 rows, only 2 of them platinum
+
lineitem
+
order_id, sku, revenue; 4 items per order
+
+
+
+ + + + diff --git a/site/style.css b/site/style.css new file mode 100644 index 0000000..d0c6ea3 --- /dev/null +++ b/site/style.css @@ -0,0 +1,177 @@ +:root { + --bg: #f7f7f5; + --panel: #ffffff; + --text: #1d1d1f; + --muted: #62626a; + --border: #e2e2de; + --accent: #2f5fd0; + --accent-text: #ffffff; + --code-bg: #f0f0ec; + --error: #b42318; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #141416; + --panel: #1c1c1f; + --text: #ececef; + --muted: #9d9da6; + --border: #2e2e33; + --accent: #7aa2ff; + --accent-text: #0d1020; + --code-bg: #26262a; + --error: #ff8a80; + color-scheme: dark; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 15px/1.5 var(--sans); +} + +code, pre, textarea { font-family: var(--mono); font-size: 13px; } + +a { color: var(--accent); } + +.masthead { + max-width: 1200px; + margin: 0 auto; + padding: 32px 16px 8px; +} + +.masthead h1 { margin: 0 0 8px; font-size: 26px; letter-spacing: -0.01em; } +.masthead .plus { color: var(--muted); font-weight: 400; } +.lede { max-width: 70ch; margin: 0 0 8px; color: var(--muted); } +.links { display: flex; gap: 16px; margin: 0; } + +.layout { + max-width: 1200px; + margin: 0 auto; + padding: 16px; + display: grid; + gap: 16px; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + grid-template-areas: + "query plan" + "results plan" + "tables plan"; + align-items: start; +} + +.query { grid-area: query; } +.plan { grid-area: plan; } +.results { grid-area: results; } +.tables { grid-area: tables; } + +@media (max-width: 860px) { + .layout { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: "query" "plan" "results" "tables"; + } +} + +.panel { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 10px; + padding: 16px; + min-width: 0; +} + +.panel h2 { + margin: 0 0 12px; + font-size: 13px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted); +} + +.panel-head { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: baseline; + justify-content: space-between; +} + +.presets { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; } + +.presets button { + font: 12px var(--sans); + padding: 4px 10px; + border: 1px solid var(--border); + border-radius: 999px; + background: transparent; + color: var(--text); + cursor: pointer; +} + +.presets button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } + +textarea { + width: 100%; + resize: vertical; + padding: 10px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--code-bg); + color: var(--text); + line-height: 1.5; +} + +.actions { display: flex; align-items: center; gap: 12px; margin-top: 10px; } + +#run { + font: 600 14px var(--sans); + padding: 7px 18px; + border: 0; + border-radius: 6px; + background: var(--accent); + color: var(--accent-text); + cursor: pointer; +} + +#run:disabled { opacity: 0.5; cursor: default; } +.hint { color: var(--muted); font-size: 12px; } +.status { margin-left: auto; color: var(--muted); font-size: 13px; text-align: right; } +.status.error { color: var(--error); } + +.plan-text { + margin: 0; + padding: 12px; + overflow-x: auto; + background: var(--code-bg); + border-radius: 6px; + line-height: 1.6; +} + +.results-body { overflow-x: auto; } + +table { border-collapse: collapse; width: 100%; font-size: 13px; } +th, td { padding: 6px 10px; border-bottom: 1px solid var(--border); text-align: left; white-space: nowrap; } +th { font-weight: 600; color: var(--muted); } +th.num, td.num { text-align: right; font-variant-numeric: tabular-nums; } +.note { color: var(--muted); font-size: 12px; margin: 8px 0 0; } +.error-text { color: var(--error); font-family: var(--mono); font-size: 13px; white-space: pre-wrap; margin: 0; } + +.table-list { margin: 0; } +.table-list dt { font-weight: 600; margin-top: 8px; } +.table-list dt:first-child { margin-top: 0; } +.table-list dd { margin: 2px 0 0; color: var(--muted); font-size: 13px; } + +.tag { + font: 600 11px var(--sans); + padding: 1px 6px; + border-radius: 4px; + background: var(--code-bg); + color: var(--muted); +} diff --git a/tests/test_site_demo.py b/tests/test_site_demo.py new file mode 100644 index 0000000..a6ffb88 --- /dev/null +++ b/tests/test_site_demo.py @@ -0,0 +1,98 @@ +"""The browser demo's Python side, run natively. + +site/demo.py has no browser dependencies, so everything the page asks of it +can be checked here: the shop builds, every preset query runs, the bad +estimate the first preset exists to show is really there, and time travel +reads the versions the history claims. +""" + +import importlib.util +import json +import zipfile +from pathlib import Path + +import pytest + +pytest.importorskip("tinydelta") + +SITE = Path(__file__).resolve().parent.parent / "site" + + +def _load(name): + spec = importlib.util.spec_from_file_location(f"site_{name}", SITE / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def demo(tmp_path_factory): + module = _load("demo") + module.setup(tmp_path_factory.mktemp("data")) + return module + + +def _nodes(plan): + yield plan + for child in plan["children"]: + yield from _nodes(child) + + +def _first_sql(demo): + return json.loads(demo.presets())[0]["sql"] + + +def test_history_has_appends_overwrite_and_restore(demo): + commits = json.loads(demo.history()) + assert [c["operation"] for c in commits] == [ + "CREATE", "APPEND", "APPEND", "APPEND", "OVERWRITE", "RESTORE", + ] + assert [c["rows"] for c in commits] == [0, 600, 1200, 1800, 1200, 1800] + + +def test_every_preset_runs(demo): + for preset in json.loads(demo.presets()): + result = json.loads(demo.run(preset["sql"])) + assert "error" not in result, (preset["name"], result) + assert result["rows"], preset["name"] + assert result["plan"]["actual_rows"] == len(result["rows"]) + + +def test_first_preset_shows_a_flagged_misestimate(demo): + result = json.loads(demo.run(_first_sql(demo))) + filter_node = next(n for n in _nodes(result["plan"]) if n["operator"] == "Filter") + assert filter_node["estimated_rows"] == 50 + assert filter_node["actual_rows"] == 2 + assert "estimate off by 25x" in result["text"] + + +def test_toggles_change_the_plan_but_not_the_answer(demo): + sql = _first_sql(demo) + default = json.loads(demo.run(sql)) + for options in ({"reorder": False}, {"pushdown": False}): + other = json.loads(demo.run(sql, **options)) + assert other["rows"] == default["rows"], options + assert other["text"] != default["text"], options + + +def test_time_travel_reads_each_version(demo): + sql = "SELECT COUNT(o.id) AS n FROM orders o" + for commit in json.loads(demo.history()): + result = json.loads(demo.run(sql, version=commit["version"])) + assert result["version"] == commit["version"] + assert result["rows"] == [[commit["rows"]]] + + +def test_errors_come_back_as_json(demo): + result = json.loads(demo.run("SELECT nope FROM orders")) + assert result == {"error": "TinyQueryError: unknown column nope"} + assert "error" in json.loads(demo.run("SELECT * FROM orders", version=99)) + + +def test_build_bundles_both_packages_and_the_demo(tmp_path): + bundle = _load("build").build(tmp_path / "site") + names = set(zipfile.ZipFile(bundle).namelist()) + assert {"demo.py", "tinyquery/engine.py", "tinydelta/log.py"} <= names + assert not any("__pycache__" in name for name in names) + for page in ("index.html", "style.css", "app.js"): + assert (tmp_path / "site" / page).is_file()