Skip to content

Commit 0c77d52

Browse files
authored
feat: SQL query filter follow-ups: table autocomplete, type rename, type-switch fix, E2E tests (#3719)
## Summary Follow-ups from review on #3678: autocomplete table and column names in the SQL query filter editor, rename "Queried values", fix a validation bug when switching filter types, and add E2E coverage for SQL query filters. One commit per change: - **feat: autocomplete table and column names in the SQL query filter editor.** The editor now suggests the tables and columns of the selected connection's sources, like the Raw SQL tile. A connection variable suggests the tables of the connection it currently selects. The tile's table-list logic moves to a shared `getTableConnectionsForConnection()` in `utils.ts`, which both editors use. - **feat: rename the Queried values filter type to SQL expression values.** This tells it apart from "SQL query values" and "PromQL label values". The two SQL types are now next to each other in the type dropdown. - **fix: clear the previous filter type's rules when switching types.** react-hook-form keeps a field's validation rules after its input unmounts, and merges the next input's rules over them. Switching from "PromQL label values" to "SQL query values" failed with "Select a PromQL source", and a new SQL query filter couldn't be saved without a source because "SQL expression values" (the default type) requires one. Changing the type now clears the old rules before the next editor registers its own. - **test: add E2E tests for SQL query dashboard filters.** Five tests: values listed in query order and selected by variable name, values narrowed by another filter's variable using `$__sourceTable` and `$__filter`, a connection variable, a data source variable, and a query error shown in the preview and on the dropdown. ### Screenshots or video Not captured. The visible changes are autocomplete suggestions in the SQL query filter editor and the renamed, reordered type dropdown. ### How to reproduce **Starting point:** `yarn dev`, any dashboard, with a Logs source on the local connection. **On `main`:** 1. Click **Edit filters and variables**, then **Add new filter**, and choose **PromQL label values**. 2. Switch the type to **SQL query values**, fill in a name, connection and query, and click **Save filter**. It fails with "Select a PromQL source". 3. In the SQL editor, start typing a table name. Only keywords, functions and macros are suggested. **On this branch:** 1. Repeat step 2. The filter saves. 2. In the SQL editor, type `otel`. The tables of the connection's sources are suggested, and after `FROM`, their columns. 3. Open the **Type** dropdown. It lists **SQL expression values** then **SQL query values**, and "Queried values" is gone. ### How to test on Vercel preview **Preview routes:** /dashboards **Steps:** 1. Create a new dashboard and click **Edit filters and variables**, then **Add new filter**. 2. Open the **Type** dropdown and verify the first two options are "SQL expression values" and "SQL query values". 3. Choose **SQL query values**, pick the demo connection, and type `SELECT * FROM otel` in the SQL editor. Verify table names appear in the suggestions. ### References - Linear Issue: [HDX-5524](https://linear.app/clickhouse/issue/HDX-5524/support-dashboard-variables-populated-from-arbitrary-clickhouse-sql) - Related PRs: follows #3691. Addresses [this comment](#3678 (comment)) and [this one](#3678 (comment)) on #3678.
1 parent 22377df commit 0c77d52

14 files changed

Lines changed: 788 additions & 52 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@hyperdx/app': patch
3+
---
4+
5+
fix: stop the previous filter type's validation from blocking a save after switching types
6+
7+
Switching a dashboard filter from "PromQL label values" to another type no longer fails with "Select a PromQL source".
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@hyperdx/app': patch
3+
---
4+
5+
feat: rename the "Queried values" dashboard filter type to "SQL expression values"
6+
7+
The new name separates it from "SQL query values" and "PromQL label values".
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@hyperdx/app': patch
3+
---
4+
5+
feat: autocomplete table and column names in the SQL query filter editor
6+
7+
The SQL query dashboard filter's editor now suggests the tables and columns of
8+
the selected connection's sources, like the Raw SQL tile editor.

‎packages/app/src/__tests__/utils.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import {
22
ChartPaletteTokenSchema,
33
ColorCondition,
44
NumericUnit,
5+
SourceKind,
6+
TLogSource,
57
TSource,
68
} from '@hyperdx/common-utils/dist/types';
79
import { SortingState } from '@tanstack/react-table';
@@ -22,6 +24,7 @@ import {
2224
getColorFromCSSToken,
2325
getLogSeverityLevel,
2426
getMetricTableName,
27+
getTableConnectionsForConnection,
2528
isColumnInSelect,
2629
mapKeyBy,
2730
mergePath,
@@ -303,6 +306,60 @@ describe('getAllMetricTables', () => {
303306
});
304307
});
305308

309+
describe('getTableConnectionsForConnection', () => {
310+
const logSource: TLogSource = {
311+
kind: SourceKind.Log,
312+
id: 'logs',
313+
name: 'Logs',
314+
connection: 'conn1',
315+
from: { databaseName: 'otel', tableName: 'logs' },
316+
timestampValueExpression: 'Timestamp',
317+
defaultTableSelectExpression: 'Body',
318+
materializedViews: [
319+
{
320+
databaseName: 'otel',
321+
tableName: 'logs_mv',
322+
dimensionColumns: 'ServiceName',
323+
minGranularity: '1 minute',
324+
timestampColumn: 'Timestamp',
325+
aggregatedColumns: [],
326+
},
327+
],
328+
};
329+
const otherConnectionSource: TLogSource = {
330+
...logSource,
331+
id: 'other',
332+
connection: 'conn2',
333+
from: { databaseName: 'other', tableName: 'logs' },
334+
materializedViews: undefined,
335+
};
336+
const disabledSource: TLogSource = {
337+
...logSource,
338+
id: 'disabled',
339+
disabled: true,
340+
from: { databaseName: 'otel', tableName: 'disabled' },
341+
};
342+
343+
const tables = (connectionId: string | undefined) =>
344+
getTableConnectionsForConnection(
345+
[logSource, otherConnectionSource, disabledSource],
346+
connectionId,
347+
).map(tc => `${tc.connectionId}:${tc.databaseName}.${tc.tableName}`);
348+
349+
it('lists source tables and materialized views on the connection', () => {
350+
expect(tables('conn1')).toEqual(['conn1:otel.logs', 'conn1:otel.logs_mv']);
351+
});
352+
353+
it('skips disabled sources and other connections', () => {
354+
expect(tables('conn2')).toEqual(['conn2:other.logs']);
355+
});
356+
357+
it('returns nothing without sources or a connection', () => {
358+
expect(getTableConnectionsForConnection(undefined, 'conn1')).toEqual([]);
359+
expect(tables(undefined)).toEqual([]);
360+
});
361+
});
362+
306363
describe('formatNumber', () => {
307364
it('handles undefined/null values', () => {
308365
expect(formatNumber(undefined)).toBe('N/A');

‎packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx‎

Lines changed: 6 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import { useEffect, useMemo, useState } from 'react';
22
import { Control, UseFormSetValue, useWatch } from 'react-hook-form';
3-
import {
4-
TableConnection,
5-
tcFromSource,
6-
} from '@hyperdx/common-utils/dist/core/metadata';
73
import {
84
displayTypeSupportsRawSqlAlerts,
95
validateRawSqlChartConfig,
@@ -15,12 +11,7 @@ import {
1511
RawSqlChartConfig,
1612
SourceKind,
1713
} from '@hyperdx/common-utils/dist/types';
18-
import {
19-
DisplayType,
20-
isLogSource,
21-
isMetricSource,
22-
isTraceSource,
23-
} from '@hyperdx/common-utils/dist/types';
14+
import { DisplayType, isMetricSource } from '@hyperdx/common-utils/dist/types';
2415
import {
2516
Alert,
2617
Box,
@@ -48,7 +39,7 @@ import { type SQLCompletion } from '@/components/SQLEditor/utils';
4839
import { IS_LOCAL_MODE } from '@/config';
4940
import useResizable from '@/hooks/useResizable';
5041
import { useSources } from '@/source';
51-
import { getAllMetricTables, usePrevious } from '@/utils';
42+
import { getTableConnectionsForConnection, usePrevious } from '@/utils';
5243
import { DEFAULT_TILE_ALERT } from '@/utils/alerts';
5344
import { resolveConnectionSourceSync } from '@/utils/connectionSourceSync';
5445

@@ -187,33 +178,10 @@ export default function RawSqlChartEditor({
187178
const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] =
188179
useState(false);
189180

190-
const tableConnections: TableConnection[] = useMemo(() => {
191-
if (!sources) return [];
192-
return sources
193-
.filter(s => s.connection === connection && !s.disabled)
194-
.flatMap(source => {
195-
const tables: TableConnection[] = getAllMetricTables(source);
196-
197-
if (!isMetricSource(source)) {
198-
tables.push(tcFromSource(source));
199-
}
200-
201-
if (
202-
(isLogSource(source) || isTraceSource(source)) &&
203-
source.materializedViews
204-
) {
205-
tables.push(
206-
...source.materializedViews.map(mv => ({
207-
databaseName: mv.databaseName,
208-
tableName: mv.tableName,
209-
connectionId: source.connection,
210-
})),
211-
);
212-
}
213-
214-
return tables;
215-
});
216-
}, [sources, connection]);
181+
const tableConnections = useMemo(
182+
() => getTableConnectionsForConnection(sources, connection),
183+
[sources, connection],
184+
);
217185

218186
const alertTooltip =
219187
displayType === DisplayType.Number

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

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,14 @@ import {
1919
Divider,
2020
Group,
2121
Modal,
22+
Select,
2223
Stack,
2324
TextInput,
2425
} from '@mantine/core';
2526
import { IconAlertTriangle } from '@tabler/icons-react';
2627

2728
import { ErrorBoundary } from '@/components/Error/ErrorBoundary';
2829
import { CheckBoxControlled } from '@/components/InputControlled';
29-
import SelectControlled from '@/components/SelectControlled';
3030
import { SqlVariablesProvider } from '@/components/SQLEditor/variableCompletions';
3131
import { IS_PROMQL_ENABLED } from '@/config';
3232
import { useConfirm } from '@/useConfirm';
@@ -50,10 +50,10 @@ import { VariableNameInput } from './VariableNameInput';
5050
const FILTER_TYPE_OPTIONS = [
5151
{
5252
value: DashboardFilterType.enum.QUERY_EXPRESSION,
53-
label: 'Queried values',
53+
label: 'SQL expression values',
5454
},
55-
{ value: DashboardFilterType.enum.STATIC_LIST, label: 'Static values' },
5655
{ value: DashboardFilterType.enum.SQL_QUERY, label: 'SQL query values' },
56+
{ value: DashboardFilterType.enum.STATIC_LIST, label: 'Static values' },
5757
...(IS_PROMQL_ENABLED
5858
? [
5959
{
@@ -116,10 +116,28 @@ export const DashboardFilterEditForm = ({
116116
setValue,
117117
setError,
118118
trigger,
119+
getValues,
119120
} = useForm<FilterFormValues>({
120121
defaultValues: toFormValues(filter, presetSource?.id),
121122
});
122123

124+
// react-hook-form keeps a field's rules after its input unmounts, and merges
125+
// the next input's rules over them. Without this, the previous editor's rules
126+
// (say, PromQL's required source) would still apply to the next editor's
127+
// input for the same field. Runs on the type change itself, before the next
128+
// editor registers its own rules.
129+
const changeType = (type: FilterFormValues['type']) => {
130+
const values = getValues();
131+
if (type === values.type) return;
132+
const fields = Object.keys(values).filter(
133+
(key): key is keyof FilterFormValues => key in values,
134+
);
135+
for (const field of fields) {
136+
register(field, { required: false, validate: undefined });
137+
}
138+
setValue('type', type, { shouldDirty: true });
139+
};
140+
123141
const confirm = useConfirm();
124142
// Read during render so react-hook-form subscribes this component to it.
125143
const isDirty = formState.isDirty;
@@ -239,9 +257,11 @@ export const DashboardFilterEditForm = ({
239257
<Stack>
240258
{showTypeInput && (
241259
<CustomInputWrapper label="Type">
242-
<SelectControlled
243-
control={control}
244-
name="type"
260+
<Select
261+
value={formFilterType}
262+
onChange={value =>
263+
value && changeType(DashboardFilterType.parse(value))
264+
}
245265
data={FILTER_TYPE_OPTIONS}
246266
data-testid="filter-type-picker"
247267
allowDeselect={false}

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ import {
3737
useSqlQueryFilterValues,
3838
} from '@/hooks/useSqlQueryFilterValues';
3939
import { useSources } from '@/source';
40-
import { truncateText, usePrevious } from '@/utils';
40+
import {
41+
getTableConnectionsForConnection,
42+
truncateText,
43+
usePrevious,
44+
} from '@/utils';
4145
import { resolveConnectionSourceSync } from '@/utils/connectionSourceSync';
4246

4347
import { TOOLTIP_PORTAL_TARGET } from './constants';
@@ -172,6 +176,10 @@ export const SqlQueryFilterEditForm = ({
172176
!!resolvedConnection &&
173177
!!sqlTemplate?.trim() &&
174178
unresolvedVariables.length === 0;
179+
const tableConnections = useMemo(
180+
() => getTableConnectionsForConnection(sources, resolvedConnection),
181+
[sources, resolvedConnection],
182+
);
175183
const queryClient = useQueryClient();
176184
const runPreview = () => {
177185
if (!canPreview) return;
@@ -272,6 +280,7 @@ export const SqlQueryFilterEditForm = ({
272280
height="150px"
273281
enableLineWrapping
274282
placeholder={PLACEHOLDER_SQL}
283+
tableConnections={tableConnections}
275284
additionalCompletions={completions}
276285
onSubmit={runPreview}
277286
parentRef={TOOLTIP_PORTAL_TARGET}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import { screen, waitFor } from '@testing-library/react';
2+
import userEvent from '@testing-library/user-event';
3+
4+
import DashboardFiltersModal from '@/components/DashboardFiltersModal';
5+
import { FilterFormControl } from '@/components/DashboardFiltersModal/filterFormState';
6+
7+
jest.mock('@/config', () => ({
8+
...jest.requireActual('@/config'),
9+
IS_PROMQL_ENABLED: true,
10+
}));
11+
// ConfirmProvider pulls in next/router, which jsdom has no answer for.
12+
jest.mock('@/useConfirm', () => ({ useConfirm: () => jest.fn() }));
13+
jest.mock('@/source', () => ({ useSources: () => ({ data: [] }) }));
14+
jest.mock('@/connection', () => ({ useConnections: () => ({ data: [] }) }));
15+
16+
// The real editors would drag CodeMirror and source metadata into jsdom. These
17+
// register the shared source field with the same rules as the real forms.
18+
jest.mock(
19+
'@/components/DashboardFiltersModal/QueryExpressionFilterEditForm',
20+
() => ({
21+
QueryExpressionFilterEditForm: ({
22+
control,
23+
}: {
24+
control: FilterFormControl;
25+
}) => <input {...control.register('source', { required: true })} />,
26+
}),
27+
);
28+
jest.mock(
29+
'@/components/DashboardFiltersModal/PromqlLabelFilterEditForm',
30+
() => ({
31+
PromqlLabelFilterEditForm: ({
32+
control,
33+
}: {
34+
control: FilterFormControl;
35+
}) => (
36+
<input
37+
data-testid="promql-source-input"
38+
{...control.register('source', {
39+
required: 'Select a PromQL source',
40+
validate: value => value !== 'logs' || 'Select a PromQL source',
41+
})}
42+
/>
43+
),
44+
}),
45+
);
46+
jest.mock('@/components/DashboardFiltersModal/SqlQueryFilterEditForm', () => ({
47+
SqlQueryFilterEditForm: ({ control }: { control: FilterFormControl }) => (
48+
<div>
49+
<input
50+
data-testid="connection-input"
51+
{...control.register('connection', { required: true })}
52+
/>
53+
<input data-testid="sql-source-input" {...control.register('source')} />
54+
<textarea
55+
data-testid="sql-input"
56+
{...control.register('sqlTemplate', { required: true })}
57+
/>
58+
</div>
59+
),
60+
}));
61+
62+
// Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it.
63+
window.HTMLElement.prototype.scrollIntoView = jest.fn();
64+
65+
describe('DashboardFiltersModal with PromQL enabled', () => {
66+
it.each([
67+
['without a source', ''],
68+
['with a non-PromQL source', 'logs'],
69+
])(
70+
'saves a SQL query filter %s after visiting the PromQL editor',
71+
async (_, source) => {
72+
const onSaveFilter = jest.fn();
73+
renderWithMantine(
74+
<DashboardFiltersModal
75+
opened
76+
filters={[]}
77+
showVariableOptions
78+
showRequiredFilterOptions
79+
onClose={jest.fn()}
80+
onSaveFilter={onSaveFilter}
81+
onRemoveFilter={jest.fn()}
82+
/>,
83+
);
84+
const user = userEvent.setup();
85+
const selectFilterType = async (label: string) => {
86+
await user.click(screen.getByTestId('filter-type-picker'));
87+
await user.click(await screen.findByText(label));
88+
};
89+
90+
await user.click(screen.getByTestId('add-filter-button'));
91+
await selectFilterType('PromQL label values');
92+
expect(screen.getByTestId('promql-source-input')).toBeInTheDocument();
93+
await selectFilterType('SQL query values');
94+
await user.type(screen.getByTestId('filter-name-input'), 'Service');
95+
await user.type(screen.getByTestId('connection-input'), 'conn1');
96+
if (source) {
97+
await user.type(screen.getByTestId('sql-source-input'), source);
98+
}
99+
await user.type(screen.getByTestId('sql-input'), 'SELECT 1');
100+
await user.click(screen.getByTestId('save-filter-button'));
101+
102+
await waitFor(() => expect(onSaveFilter).toHaveBeenCalledTimes(1));
103+
const saved = onSaveFilter.mock.calls[0][0];
104+
expect(saved.type).toBe('SQL_QUERY');
105+
expect(saved.source).toBe(source || undefined);
106+
},
107+
);
108+
});

0 commit comments

Comments
 (0)