Skip to content

Commit 3bdbf7f

Browse files
authored
feat: show generated SQL in the SQL query filter preview (#3823)
## Summary Shows the SQL a SQL query filter runs, with its variables and macros filled in, below **Preview values** in the filter editor. This matches the raw SQL tile's **Generated SQL**, so users can see what `$svc`, `$__filter(...)`, `$__timeFilter(...)`, `$__sourceTable` and `$__filters` turned into. - `renderSqlQueryFilterValuesQuery` also returns `expandedSql`: the filter's SQL after expansion, without the `SELECT DISTINCT … LIMIT` wrapper the values query adds. - `useSqlQueryFilterValues` moves its per-filter setup and its `$__filters` step into helpers, with no behavior change. The new `useSqlQueryFilterGeneratedSql` uses the same helpers, so the SQL shown is built by the code that runs the values query. It sends nothing to ClickHouse. - After **Preview values**, the editor shows a collapsed **Generated SQL** section, including when the query fails. As on the raw SQL tile, the time range is written in as millisecond timestamps and the SQL is formatted. - `QueryPreviewAccordion` takes an optional `variant`. The filter editor passes `noPadding`, so the section lines up with the other form fields. ### Screenshots or video | <img width="651" height="939" alt="Screenshot 2026-11-25 at 10 32 34" src="https://github.com/user-attachments/assets/ae0aaa76-708f-4534-b431-2996635c0550" /> | <img width="684" height="905" alt="Screenshot 2026-11-25 at 10 33 05" src="https://github.com/user-attachments/assets/21886405-2242-4d8d-be12-e623cef432ef" /> | | :----- | :---- | ### How to reproduce **Starting point:** `yarn app:dev:local` connected to the demo server (onboarding → "Connect to Demo Server"), or the Vercel preview. **On `main`:** 1. Open a dashboard, click **Edit filters and variables**, then **Add new filter**. 2. Create a **Static values** filter named `Service` with options `frontend` and `checkout`, and variable name `svc`. Save it. 3. Add a **SQL query values** filter named `Severity` on connection **Demo** and source **Logs**, with: ```sql SELECT SeverityText FROM $__sourceTable WHERE $__timeFilter(Timestamp) AND $__filter(ServiceName, $svc) AND $__filters GROUP BY SeverityText ORDER BY count() DESC ``` 4. Click **Preview values**. Only the values are listed. There's no way to see what the macros and `$svc` expanded to. **On this branch:** 1. Repeat the steps above, then expand **Generated SQL** below the values. 2. It shows the Logs table in place of `$__sourceTable` and timestamps in place of `$__timeFilter`. `$__filter(ServiceName, $svc)` shows as `(1=1 /** no values selected for variable 'svc' */)`. 3. Save the filter, close the modal, and pick `frontend` in **Service**. 4. Edit **Severity** and click **Preview values** again. **Generated SQL** now shows `(ServiceName IN ('frontend'))`, and the values narrow to match. ### References - Linear: HDX-6191
1 parent e9c89eb commit 3bdbf7f

12 files changed

Lines changed: 522 additions & 122 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@hyperdx/app': patch
3+
'@hyperdx/common-utils': patch
4+
---
5+
6+
feat: show the generated SQL, with variables and macros filled in, in the SQL query filter preview

‎packages/app/src/components/DBEditTimeChartForm/QueryPreviewAccordion.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
import { ReactNode } from 'react';
2-
import { Accordion, Box, Text, Tooltip } from '@mantine/core';
2+
import { Accordion, AccordionProps, Box, Text, Tooltip } from '@mantine/core';
33
import { IconCode } from '@tabler/icons-react';
44

55
/** The collapsed accordion the preview panel shows a tile's query in. */
66
export function QueryPreviewAccordion({
77
value,
88
label,
99
disabledReason,
10+
variant,
1011
children,
1112
}: {
1213
/** The accordion item's key — arbitrary, but it must be non-empty. */
1314
value: string;
1415
label: string;
1516
/** Why there is nothing to show. Set means the control is disabled. */
1617
disabledReason?: string;
18+
variant?: AccordionProps['variant'];
1719
children: ReactNode;
1820
}) {
1921
const isDisabled = disabledReason != null;
2022

2123
return (
22-
<Accordion defaultValue="">
24+
<Accordion defaultValue="" variant={variant}>
2325
<Accordion.Item value={value}>
2426
{/* The tooltip hangs off the wrapper Box rather than the control itself
2527
* because a disabled Accordion.Control emits none of the pointer events

‎packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx‎

Lines changed: 34 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVari
1515
import {
1616
BroadcastFilter,
1717
DashboardFilter,
18-
SqlQueryDashboardFilter,
1918
} from '@hyperdx/common-utils/dist/types';
2019
import { Alert, Button, Group, Loader, Stack, Text } from '@mantine/core';
2120
import { IconAlertTriangle, IconPlayerPlay } from '@tabler/icons-react';
@@ -32,6 +31,7 @@ import {
3231
useChartVariables,
3332
} from '@/components/SQLEditor/variableCompletions';
3433
import { NOW } from '@/config';
34+
import { SqlQueryFilterPreviewOptions } from '@/hooks/useSqlQueryFilterGeneratedSql';
3535
import {
3636
SQL_QUERY_FILTER_VALUES_QUERY_KEY,
3737
useSqlQueryFilterValues,
@@ -47,6 +47,7 @@ import { resolveConnectionSourceSync } from '@/utils/connectionSourceSync';
4747
import { TOOLTIP_PORTAL_TARGET } from './constants';
4848
import { CustomInputWrapper } from './CustomInputWrapper';
4949
import { FilterFormControl, FilterFormValues } from './filterFormState';
50+
import { SqlQueryFilterGeneratedSql } from './SqlQueryFilterGeneratedSql';
5051
import { VariableNameInput } from './VariableNameInput';
5152

5253
/** Values the preview lists before summarizing the rest as a count. */
@@ -166,6 +167,27 @@ export const SqlQueryFilterEditForm = ({
166167
source?: string;
167168
sqlTemplate: string;
168169
}>();
170+
const lastHour = useMemo(
171+
(): [Date, Date] => [new Date(NOW - 60 * 60 * 1000), new Date(NOW)],
172+
[],
173+
);
174+
const preview = useMemo(
175+
(): SqlQueryFilterPreviewOptions | undefined =>
176+
previewed && {
177+
filter: {
178+
id: 'preview',
179+
type: 'SQL_QUERY',
180+
name: 'Preview',
181+
...previewed,
182+
isBroadcastEnabled: false,
183+
isVariableEnabled: true,
184+
},
185+
dateRange: dateRange ?? lastHour,
186+
variables,
187+
getDashboardFilters,
188+
},
189+
[previewed, dateRange, lastHour, variables, getDashboardFilters],
190+
);
169191
const unresolvedVariables = [
170192
!resolvedConnection && parseVariableReference(connection) != null
171193
? connection
@@ -303,13 +325,11 @@ export const SqlQueryFilterEditForm = ({
303325
Preview values
304326
</Button>
305327
</Group>
306-
{previewed && (
307-
<SqlQueryFilterPreview
308-
{...previewed}
309-
dateRange={dateRange}
310-
variables={variables}
311-
getDashboardFilters={getDashboardFilters}
312-
/>
328+
{preview && (
329+
<>
330+
<SqlQueryFilterPreview {...preview} />
331+
<SqlQueryFilterGeneratedSql {...preview} />
332+
</>
313333
)}
314334
</Stack>
315335
</CustomInputWrapper>
@@ -320,47 +340,20 @@ export const SqlQueryFilterEditForm = ({
320340
};
321341

322342
const SqlQueryFilterPreview = ({
323-
connection,
324-
source,
325-
sqlTemplate,
343+
filter,
326344
dateRange,
327345
variables,
328346
getDashboardFilters,
329-
}: {
330-
connection: string;
331-
source?: string;
332-
sqlTemplate: string;
333-
dateRange?: [Date, Date];
334-
variables: ReturnType<typeof useChartVariables>;
335-
getDashboardFilters?: (sourceId: string) => BroadcastFilter[];
336-
}) => {
337-
const lastHour = useMemo(
338-
(): [Date, Date] => [new Date(NOW - 60 * 60 * 1000), new Date(NOW)],
339-
[],
340-
);
341-
const filters = useMemo(
342-
(): SqlQueryDashboardFilter[] => [
343-
{
344-
id: 'preview',
345-
type: 'SQL_QUERY',
346-
name: 'Preview',
347-
connection,
348-
source,
349-
sqlTemplate,
350-
isBroadcastEnabled: false,
351-
isVariableEnabled: true,
352-
},
353-
],
354-
[connection, source, sqlTemplate],
355-
);
347+
}: SqlQueryFilterPreviewOptions) => {
348+
const filters = useMemo(() => [filter], [filter]);
356349
const { data, filterErrorMessages, isLoading, isFetching, isError } =
357350
useSqlQueryFilterValues({
358351
filters,
359-
dateRange: dateRange ?? lastHour,
352+
dateRange,
360353
variables,
361354
getDashboardFilters,
362355
});
363-
const values = data.get('preview')?.values ?? [];
356+
const values = data.get(filter.id)?.values ?? [];
364357

365358
// While a re-run loads, the previous query's values stand in as placeholder
366359
// data, so isLoading alone would show them as this query's results.
@@ -380,7 +373,7 @@ const SqlQueryFilterPreview = ({
380373
icon={<IconAlertTriangle size={16} />}
381374
data-testid="filter-sql-preview"
382375
>
383-
{filterErrorMessages.get('preview') ?? 'The query failed.'}
376+
{filterErrorMessages.get(filter.id) ?? 'The query failed.'}
384377
</Alert>
385378
);
386379
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { SQLPreview } from '@/components/ChartSQLPreview';
2+
import { QueryPreviewAccordion } from '@/components/DBEditTimeChartForm/QueryPreviewAccordion';
3+
import {
4+
SqlQueryFilterPreviewOptions,
5+
useSqlQueryFilterGeneratedSql,
6+
} from '@/hooks/useSqlQueryFilterGeneratedSql';
7+
8+
/** The previewed SQL with variables and macros filled in. */
9+
export const SqlQueryFilterGeneratedSql = (
10+
props: SqlQueryFilterPreviewOptions,
11+
) => {
12+
const { data: sql } = useSqlQueryFilterGeneratedSql(props);
13+
14+
if (sql == null) {
15+
return null;
16+
}
17+
18+
return (
19+
<div data-testid="filter-sql-generated-sql">
20+
{/* Flush with the form's other fields */}
21+
<QueryPreviewAccordion
22+
value="generated-sql"
23+
label="Generated SQL"
24+
variant="noPadding"
25+
>
26+
<SQLPreview
27+
data={sql}
28+
enableCopy
29+
copyButtonSize="xs"
30+
enableLineWrapping
31+
/>
32+
</QueryPreviewAccordion>
33+
</div>
34+
);
35+
};

‎packages/app/src/components/DashboardFiltersModal/__tests__/SqlQueryFilterEditForm.test.tsx‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { ReferenceVariablesProvider } from '@/components/sourceSelectUtils';
1414
import { SqlVariablesProvider } from '@/components/SQLEditor/variableCompletions';
1515

1616
const mockUseSqlQueryFilterValues = jest.fn();
17+
const mockUseSqlQueryFilterGeneratedSql = jest.fn();
1718
const mockCompletionLabels: string[] = [];
1819
const mockTables: string[] = [];
1920
let mockSources: TSource[] = [];
@@ -55,6 +56,14 @@ jest.mock('@/hooks/useSqlQueryFilterValues', () => ({
5556
useSqlQueryFilterValues: (...args: unknown[]) =>
5657
mockUseSqlQueryFilterValues(...args),
5758
}));
59+
jest.mock('@/hooks/useSqlQueryFilterGeneratedSql', () => ({
60+
useSqlQueryFilterGeneratedSql: (...args: unknown[]) =>
61+
mockUseSqlQueryFilterGeneratedSql(...args),
62+
}));
63+
// CodeMirror doesn't render meaningfully in jsdom.
64+
jest.mock('@/components/ChartSQLPreview', () => ({
65+
SQLPreview: ({ data }: { data?: string }) => <pre>{data}</pre>,
66+
}));
5867
// The real selector fetches connections, and the real editor is CodeMirror;
5968
// plain inputs bound to the same fields are enough to drive the preview.
6069
jest.mock('@/components/ConnectionSelect', () => ({
@@ -174,6 +183,8 @@ describe('SqlQueryFilterEditForm', () => {
174183
mockUseSqlQueryFilterValues.mockReturnValue(
175184
valuesResult({ values: ['prod', 'dev'] }),
176185
);
186+
mockUseSqlQueryFilterGeneratedSql.mockReset();
187+
mockUseSqlQueryFilterGeneratedSql.mockReturnValue({ data: undefined });
177188
});
178189

179190
it('suggests time macros but not source or interval macros', () => {
@@ -540,4 +551,46 @@ describe('SqlQueryFilterEditForm', () => {
540551
'Unknown table default.envs',
541552
);
542553
});
554+
555+
describe('generated SQL', () => {
556+
const sql = 'SELECT env FROM envs WHERE $__filter(cloud, $cloud)';
557+
const generated = 'SELECT env FROM envs WHERE (1=1)';
558+
559+
it('shows the previewed SQL with its variables filled in', async () => {
560+
mockUseSqlQueryFilterGeneratedSql.mockReturnValue({ data: generated });
561+
const user = await renderForm(sql);
562+
563+
expect(
564+
screen.queryByTestId('filter-sql-generated-sql'),
565+
).not.toBeInTheDocument();
566+
await user.click(screen.getByTestId('filter-sql-preview-button'));
567+
568+
expect(screen.getByTestId('filter-sql-generated-sql')).toHaveTextContent(
569+
generated,
570+
);
571+
expect(mockUseSqlQueryFilterGeneratedSql).toHaveBeenLastCalledWith(
572+
expect.objectContaining({
573+
filter: expect.objectContaining({
574+
connection: 'conn1',
575+
sqlTemplate: sql,
576+
}),
577+
variables: [cloudVariable],
578+
}),
579+
);
580+
});
581+
582+
it('shows it when the values query fails', async () => {
583+
mockUseSqlQueryFilterValues.mockReturnValue(
584+
valuesResult({ error: 'Unknown table default.envs' }),
585+
);
586+
mockUseSqlQueryFilterGeneratedSql.mockReturnValue({ data: generated });
587+
const user = await renderForm(sql);
588+
589+
await user.click(screen.getByTestId('filter-sql-preview-button'));
590+
591+
expect(screen.getByTestId('filter-sql-generated-sql')).toHaveTextContent(
592+
generated,
593+
);
594+
});
595+
});
543596
});

0 commit comments

Comments
 (0)