Simon Willison's new datasette-charts plugin treats SQL as a compilation target for visualization. Instead of charting the current page of results (typically 100 rows), it rewrites queries to aggregate entire tables using GROUP BY, time bucketing, and window functions, then caps output at 5,000 rows for rendering. The plugin uses heuristics to suggest chart types, samples large tables to avoid full scans, and persists all state in URL fragments.
The core innovation is query rewriting. The plugin sits between user intent and the database engine, compiling chart specifications into aggregation SQL that executes once and returns exactly what the visualization needs.
The Pagination Problem
Previous Datasette charting plugins (like datasette-vega) visualized whatever rows appeared on the current page. If you had 10 million records and displayed 100 per page, your chart showed 100 data points. Pagination and visualization were coupled.
Datasette-charts breaks that coupling by compiling chart definitions into SQL queries that aggregate the full result set. The plugin never asks for raw rows. It asks for aggregated rows.
Key architectural shift:
- Old model: fetch paginated rows, chart what you see
- New model: compile chart spec into aggregation query, execute once, render result
This moves the boundary. The visualization layer now controls query shape, not just rendering.
Query Compilation Flow
When you select a chart type, the plugin generates SQL that matches the chart's data requirements.
Example flow for a time-series line chart:
- User picks "line chart" for a table with a timestamp column
- Plugin detects the time column and numeric columns
- Generates SQL with time bucketing (hour, day, week) and GROUP BY
- Executes query, receives up to 5,000 aggregated rows
- Renders with Observable Plot
Sample generated query structure:
SELECT strftime('%Y-%m-%d', created_at) AS time_bucket, COUNT(*) AS event_count, AVG(response_time_ms) AS avg_response FROM api_logs GROUP BY time_bucket ORDER BY time_bucket LIMIT 5000; The plugin uses SQLite's strftime for time bucketing and standard aggregation functions. Window functions handle ranking and percentile calculations when needed.
Chart Type Heuristics
The plugin defines chart types (bar, line, scatter, map, etc.) with matching rules based on column types and cardinality.
Heuristic examples:
- Bar chart: one categorical column + one numeric column
- Line chart: one time column + one or more numeric columns
- Scatter plot: two numeric columns
- Map: columns named
latitude/longitudeor geometry types
For large tables, the plugin samples rows to evaluate heuristics without scanning the full dataset. Sampling uses SQLite's RANDOM() with a fixed seed for consistency.
Trade-off table:
| Approach | Accuracy | Speed | Use Case |
|---|---|---|---|
| Full table scan | 100% | Slow on large tables | <100k rows |
| Random sampling | ~95% | Fast | >1M rows, suggestion phase |
| Schema-only | Variable | Instant | Initial type matching, any size |
Sampling happens only during suggestion. Once a chart is selected, the full aggregation query runs.
State Management via URL Fragments
All chart configuration lives in the URL fragment (the part after #). This includes:
- Chart type
- Selected columns
- Aggregation functions
- Time bucket size
- Filter expressions
Example fragment:
#chart=line&x=date&y=count&bucket=day&filter=status='active' The fragment is parsed on page load and used to reconstruct the chart. No server-side session, no database writes. The URL is the state store. Fragments are UTF-8 encoded and subject to browser URL length limits (typically 2,000 characters for safe cross-browser compatibility).
Why fragments instead of query parameters:
- Fragments don't trigger page reloads when changed
- Easier to share (copy URL, paste in Slack)
- Works in Datasette Lite (client-side SQLite in the browser)
- No server-side state to expire or clean up
This pattern works well for stateless tools. The server never knows what chart you're viewing. It only receives SQL queries.
Aggregation Boundary and the 5,000-Row Cap
The plugin caps all query results at 5,000 rows. This is not a pagination limit. It's an aggregation output limit.
Why 5,000?
- Observable Plot and D3 render smoothly up to ~10k points
- 5,000 rows fit comfortably in JSON over HTTP
- Most aggregations produce far fewer rows (time buckets, category groups)
- Prevents accidental full table dumps when aggregation is too granular
If your aggregation produces more than 5,000 groups, the query returns the first 5,000 ordered by the grouping column. This can hide data, but it's rare in practice. Most time-series charts bucket to days or hours (365 or 8,760 rows per year).
Failure mode:
If you group by a high-cardinality column (user ID, transaction hash), you'll see only the first 5,000 groups. The plugin does not warn you. This is a known limitation of the alpha release.
Vendored Dependencies and Deployment Shape
The plugin vendors D3, Observable Plot, and topojson-client as static assets. No CDN dependencies. This keeps Datasette Lite working offline and avoids version drift.
Deployment options:
- Standard Datasette: install via
pip install datasette-charts, plugin auto-loads - Datasette Lite: runs entirely in the browser using Pyodide (Python compiled to WebAssembly)
- Docker: include in Datasette Docker image, no additional build step
The plugin is a single Python package with JavaScript assets. No build pipeline, no npm, no bundler. This matches Datasette's philosophy: plugins should be pip-installable and immediately usable.
Observable Plot as the Rendering Layer
The plugin uses Observable Plot for most chart types. Plot is a declarative charting library built on D3. You describe what you want (marks, scales, axes) and Plot generates SVG.
Why Plot instead of raw D3:
- Declarative API matches the plugin's chart spec structure
- Handles responsive sizing and axis formatting automatically
- Smaller API surface to expose in the UI
- Easier to generate from heuristics
The plugin translates chart specs into Plot configurations, then calls Plot's render function. The translation is straightforward because both use similar abstractions (marks, channels, scales).
Security Boundaries
The plugin executes user-provided SQL queries. This is inherent to Datasette's design, but it creates a risk surface.
Mitigations:
- Datasette's existing SQL query permissions apply (read-only by default)
- The plugin does not accept arbitrary SQL from URL parameters
- Chart specs are parsed and validated before query generation
- All queries use parameterized statements where possible
The plugin does not introduce new SQL injection vectors beyond what Datasette already exposes. If your Datasette instance allows arbitrary SQL queries, users can already run any SELECT statement. The plugin just makes it easier to generate specific aggregation queries.
Remaining risk:
If you expose Datasette publicly without authentication, users can run expensive aggregation queries that consume CPU and I/O. This is not unique to the plugin, but the plugin makes it easier to trigger. Rate limiting and query timeouts are your defense.
Observability Gaps
The plugin does not log or trace query execution. You see the final SQL in the browser's network tab, but there's no server-side telemetry. This is a deliberate design choice to keep the plugin stateless and avoid coupling to specific logging frameworks.
What you can't see:
- Query execution time
- Number of rows scanned before aggregation
- Cache hit rate (if using Datasette's query cache)
- Failed heuristic matches
Datasette itself logs queries if you enable debug mode, but the plugin doesn't add structured logging. For production use, you'd want to wrap the plugin's query execution in a middleware that emits metrics.
When to Use This Pattern
Good fit:
- Exploratory data analysis on structured datasets
- Internal tools where users understand SQL concepts
- Datasets with clear time or category dimensions
- Scenarios where bookmarkable URLs matter
Poor fit:
- Real-time dashboards (no streaming, no auto-refresh)
- Datasets requiring complex multi-table joins compiled into chart definitions
- Non-technical users who expect drag-and-drop UIs
- Cases where you need pixel-perfect chart customization
The plugin lacks streaming aggregation support and cannot compile multi-table joins into chart specifications. You must pre-join data in a view or custom query before charting.
Technical Verdict
Use datasette-charts when you need quick, shareable visualizations of SQL query results and you're already running Datasette. The URL fragment state model is elegant for stateless tools, and the SQL compilation approach scales to millions of rows without pagination workarounds.
Avoid it if you need real-time updates, complex multi-table joins in the chart layer, or fine-grained control over chart aesthetics. The 5,000-row cap and lack of streaming make it unsuitable for high-cardinality groupings or live dashboards.
The plugin's real contribution is showing how far you can push SQL as a visualization compiler. Most charting tools treat the database as a dumb row store. Datasette-charts treats it as an aggregation engine and lets the query planner do the work.
