Query data
Natural-language analytics card that streams syntax-tinted SQL into a collapsible copyable panel, runs queries with a rolling rows-scanned counter, and renders interactive Bar, Line, and Table views with a streamed insight.
import { AskYourData } from '@uthereal/ui/ask-your-data'Ask your data playground
Overview
AskYourData turns plain-language questions into SQL and interactive charts inside one self-contained card. Readers submit a question against a labelled database source (or pick a starter suggestion). The model’s query streams into a collapsible, line-numbered Generated SQL panel with syntax tints and a one-click Copy SQL button. As the query executes, a rolling counter tracks rows scanned while a breathing skeleton reserves the chart height. Once data lands, the stage reveals a Bar, Line, or Table view with hover and keyboard crosshair readouts and streams a one-line analytical insight underneath.
Use AskYourData for self-serve BI panels, warehouse copilots, and precomputed metric cards that let readers inspect the underlying SQL. For static multi-series charts without a question bar or SQL drawer, use Bar chart or Line chart.
Usage
'use client'
import { AskYourData } from '@uthereal/ui/ask-your-data'
export function AnalyticsCopilot() {
return (
<AskYourData
source={{ name: 'warehouse', dialect: 'PostgreSQL' }}
generateSql={async (question, { signal, source }) => {
const res = await fetch('/api/sql', {
method: 'POST',
signal,
body: JSON.stringify({ question, source }),
})
if (!res.ok) throw new Error('Could not generate SQL')
return (await res.json()).sql
}}
runQuery={async (sql, { signal, onProgress }) => {
const res = await fetch('/api/query', {
method: 'POST',
signal,
body: JSON.stringify({ sql }),
})
if (!res.ok) throw new Error(await res.text())
const data = await res.json()
onProgress(data.rowsScanned, data.rowsScanned)
return data.result
}}
onResult={(result, { sql }) => {
console.log('Charted', result.title, sql)
}}
/>
)
}Omit generateSql and runQuery to run the deterministic local simulation (covering signups, revenue, and churn questions with zero network requests). Always execute runQuery on a read-only database role on your backend.
Examples
Precomputed line chart with open SQL
Pass initialResult alongside initialSql and keepSqlOpen={true} to render an already-answered query immediately with its syntax-tinted PostgreSQL panel expanded and ready to copy.
SELECT
date_trunc('week', created_at)::date AS week,
plan,
COUNT(*) AS signups
FROM workspaces
WHERE created_at >= DATE '2026-09-07'
GROUP BY 1, 2
ORDER BY 1, 2;- Starter2,595
- Pro1,728
- Enterprise457
Pro and Enterprise signups accelerated 72% over the six-week window, lifting total weekly volume from 537 to 851.
Non-stacked rate table on a custom warehouse
Set stacked={false} and chart="table" for rates or percentages that should not sum across series, paired with a custom source (billing_dw on Snowflake).
SELECT
TO_CHAR(month_start, 'Mon') AS month,
segment,
ROUND(100.0 * churned_logos / NULLIF(active_logos, 0), 2) AS churn_pct
FROM billing_dw.monthly_logo_retention
WHERE month_start >= '2026-05-01'
ORDER BY month_start, segment;- Starter %3.6
- Growth %1.7
- Enterprise %0.3
| Month | Starter % | Growth % | Enterprise % |
|---|---|---|---|
| May | 4.8 | 2.4 | 0.6 |
| Jun | 4.5 | 2.2 | 0.5 |
| Jul | 4.3 | 2.1 | 0.5 |
| Aug | 4.1 | 1.9 | 0.4 |
| Sep | 3.9 | 1.8 | 0.4 |
| Oct | 3.6 | 1.7 | 0.3 |
Churn improved across every segment since May, with Starter dropping 1.2 points to 3.6% and Enterprise holding at 0.3%.
Query lifecycle and views
Execution stages
| Stage | Header & SQL panel | Cancellation & recovery |
|---|---|---|
| Idle | Prompts the reader with up to six clickable suggestions. | Submitting a non-empty question starts the pipeline. |
| Writing | Expands Generated SQL automatically and streams syntax-tinted tokens (4 tokens per 34ms). | Pressing Stop or Escape aborts generateSql and keeps only arrived SQL. |
| Running | Folds SQL (unless keepSqlOpen or toggled by the reader) and displays a rolling rows-scanned count. | Pressing Stop or Escape aborts runQuery and offers Run again. |
| Done | Draws the chart (bar, line, or table), updates SQL meta with row count and timing, and streams insight. | Reader can switch views, inspect points, copy SQL, or ask a follow-up. |
| Error | Shows the SQL or database failure reason (plus monospace detail for query errors). | Offers Try again or starter suggestions for unmatched questions. |
Chart views
| View | Behavior |
|---|---|
| Bar | Draws stacked bars when stacked is true (default) or grouped bars when false; dims non-hovered columns on inspect. |
| Line | Traces one smooth stroked path per series with focus markers at the active category. |
| Table | Renders a sticky-header scrollable table with tabular numerals and a Total column when stacked is true. |
API reference
These serializable arguments and defaults come directly from the component schema.
| Argument | Type / default | Description |
|---|---|---|
defaultQuestion | stringDefault: "Weekly signups by plan since August" | Starting question when uncontrolled. Edits do not reset a mounted instance. |
placeholder | stringDefault: "Ask a question about your data" | Placeholder for the empty question field. |
source | AskYourDataSourceDefault: {"name":"analytics","dialect":"PostgreSQL"} | The database the question runs against: its name and dialect. Defaults to analytics on PostgreSQL. |
suggestions | string[]Default: ["Weekly signups by plan since August","Monthly recurring revenue by region in 2026","Monthly churn rate by plan since May"] | Questions offered in the empty state. Defaults to three samples; pass an empty array to hide them. |
defaultChart | bar | line | tableDefault: "bar" | View for results that do not name their own chart. Defaults to bar. |
keepSqlOpen | booleanDefault: false | Keep the SQL panel open after the query starts instead of folding it away. Once someone opens or closes the panel, their choice wins. |
autoRun | booleanDefault: false | Ask the starting question once the card scrolls into view. On by default without generateSql; never over an initialResult. |
initialResult | AskYourDataResult— | Precomputed result rendered immediately, without streaming or running. Pair with initialSql to show the query beside it. |
initialSql | string— | SQL shown beside an initialResult, already complete and copyable. |
askAction | string— | Registered host action requested when Ask is pressed. The question itself travels through the React-only generateSql and runQuery callbacks. |
locale | string— | BCP 47 locale for number formatting. Inherited from the page when omitted. |
recipe | studio | softDefault: "studio" | Visual treatment. Both recipes preserve interaction behavior. |
theme | AskYourDataThemeDefault: {} | Color mode, accent, and typed semantic token overrides. |
motion | none | subtle | expressiveDefault: "subtle" | Animation preset. System reduced-motion preferences take precedence. |
motionOptions | AskYourDataMotionOptionsDefault: {} | SQL stream pacing, header crossfades, and chart draw timing in milliseconds. |
dir | ltr | rtl— | Reading direction; inherited from the page when omitted. |
AskYourDataSourceaccepts{ name, dialect }.AskYourDataResultaccepts{ title, subtitle?, categories, series, stacked?, legendValue?, chart?, categoryLabel?, insight?, rowCount?, durationMs? }, where eachAskYourDataSeriesis{ id, label, values, color? }with unique IDs andvalues.length <= categories.length(up to8series).
React integration
| Prop | Purpose |
|---|---|
question / onQuestionChange | Controlled question text and change callback. |
chart / onChartChange | Controlled view ("bar" | "line" | "table") and view-change callback. |
generateSql(question, context) | Returns SQL as a string (paced locally) or AsyncIterable<string> (streamed live). Honor context.signal. |
runQuery(sql, context) | Executes read-only SQL, calls context.onProgress(rowsScanned, totalRows?), and resolves with an AskYourDataResult. |
onResult(result, { question, sql }) | Fires once a query resolves and is charted. |
onError(error, { question, stage }) | Fires when generateSql ("sql") or runQuery ("query") throws a non-abort error. |
onAction(action, itemId?) | Called with askAction when the reader submits a question or picks a suggestion. |
formatValue(value) | Formats numeric values across Y-axis ticks, hover tooltips, legend summaries, and table cells. |
renderSourceMark() | Replaces the default 16px cylinder mark in the question bar and SQL panel header. Keep returned elements decorative. |
preset | Application defaults overridden by explicit instance arguments. |
tokens | CSS variables applied after the typed theme, forwarded to the root card, buttons, and view switcher. |
ref, className, style | Applied to the root <section> element. |
| Native attributes | id, aria-*, data-*, and remaining <section> props forwarded to the root element. |
Keyboard & accessibility
| Key | Action |
|---|---|
Enter (in question) | Submits the question or stops an in-flight run. |
Escape (in question) | Aborts SQL streaming or query execution while busy. |
ArrowLeft / ArrowRight | Steps across categories on the focused Bar or Line chart to inspect values (respects RTL). |
Home / End | Jumps chart inspection to the first or last category. |
Escape (on chart) | Clears the active chart crosshair readout. |
Tab | Moves across the question input, Ask/Stop button, SQL toggle, Copy SQL, SQL code block, view switch, and chart/table. |
- The plot region (
tabIndex={0},role="group") pairs its floating tooltip with a polite live region reading every series value and total for the focused category. - The SQL panel header uses an explicit
aria-expanded/aria-controlsdisclosure button while keeping Copy SQL stacked cleanly above it as an independent focusable control. - Container queries adapt the card below
520px, shortening the SQL metadata pill, moving the view switcher inline below the heading, and compacting chart and table spacing.@media (forced-colors: active)maps borders, series dots, and hover bands to system colors.
Motion & theming
The SQL panel expands and collapses on the smooth spring (0.4s, bounce 0), bars rise with a short stagger (320ms), lines trace across the plot (460ms), and the analytical insight streams word-by-word inside a height-reserved band so nothing shifts.
Under prefers-reduced-motion: reduce, SQL and insights land whole, bar rises and line draws become immediate, the breathing skeleton stops, and the spinner slows to 1.6s. Setting motion="none" makes every swap immediate (0ms) and stops all spinner and skeleton animations.
theme accepts mode, accent, and typed tokens across these groups:
| Token group | CSS custom properties |
|---|---|
core | --ui-surface, --ui-surface-raised, --ui-text, --ui-text-secondary, --ui-muted, --ui-border, --ui-highlight, --ui-accent, --ui-accent-foreground, --ui-danger, --ui-focus-ring, --ui-radius, --ui-border-width, --ui-shadow, --ui-disabled-opacity, --ui-font, --ui-font-size, --ui-font-weight |
extended | --ui-surface-sunken, --ui-border-strong, --ui-border-subtle, --ui-track, --ui-info, --ui-success, --ui-warning, --ui-tone-foreground, --ui-overlay, --ui-tint-strength |
chart | --ui-series-1 through --ui-series-8, --ui-series-other, --ui-sequential-1..7, --ui-diverging-1..7 |
shape | --ui-radius-sm, --ui-popup-radius, --ui-surface-radius |
type | --ui-font-mono, --ui-font-display |
elevation | --ui-shadow-resting, --ui-shadow-raised |
include | --ui-accent-strong, --ui-accent-subtle, --ui-tone-foreground |
An application-wide UtherealProvider supplies defaults.
Composition
In an agent composition, AskYourData is a leaf block. Provide source, starter suggestions, or a precomputed initialResult and initialSql, and wire askAction to a registered host action. See Building with agents.
{
"type": "AskYourData",
"props": {
"source": { "name": "analytics", "dialect": "PostgreSQL" },
"defaultQuestion": "Weekly signups by plan since August",
"defaultChart": "bar",
"keepSqlOpen": false,
"askAction": "ask_warehouse"
},
"children": []
}