Skip to content

Commit cf6ccc5

Browse files
committed
feat: create SQL query dashboard filters and fill their dropdowns
Add a "SQL query values" type to the dashboard filter editor and populate the filter's dropdown from its query. - Render the filter's query in common-utils: expand time macros and other filters' variables, select the first column as a string, and cap the result at 10,000 rows - Run each SQL query filter's query on its connection and merge the values and errors into the dashboard's filter values - Keep the query's row order in the dropdown and show a caution while a referenced variable has no selection - Add the editor form: connection picker, SQL editor with macro and variable autocomplete, variable name, and an on-demand preview of the values over the dashboard's time range Refs HDX-5524
1 parent 790896c commit cf6ccc5

15 files changed

Lines changed: 1035 additions & 26 deletions
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@hyperdx/common-utils': patch
3+
'@hyperdx/app': patch
4+
---
5+
6+
feat: create SQL query dashboard filters and fill their dropdowns
7+
8+
Dashboard filters can now take their values from a ClickHouse SQL query. The filter editor offers a "SQL query values" type with a connection, a SQL editor, and a preview of the values. The dropdown lists the query's first column in the order it returns, up to 10,000 values, and the query can use the time macros and other filters' variables.

‎packages/app/src/DBDashboardPage.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3510,6 +3510,7 @@ function DBDashboardPage({
35103510
showVariableOptions
35113511
showRequiredFilterOptions
35123512
variables={variables}
3513+
dateRange={searchedTimeRange}
35133514
/>
35143515
)}
35153516
</>

‎packages/app/src/DashboardFilters.tsx‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
isFilterRequired,
1010
isFilterVariableEnabled,
1111
isQueryExpressionFilter,
12+
isSqlQueryFilter,
1213
isStaticListFilter,
1314
} from '@hyperdx/common-utils/dist/filters';
1415
import {
@@ -141,8 +142,9 @@ const DashboardFilterSelect = ({
141142
// so a completed/empty/failed query stays interactive and the user can
142143
// still clear or adjust the selection.
143144
loading={isLoading}
144-
// A static list renders in the order its author wrote it.
145-
sort={!isStaticListFilter(filter)}
145+
// A static list renders in the order its author wrote it, and a SQL
146+
// query filter in the order its query returns.
147+
sort={!isStaticListFilter(filter) && !isSqlQueryFilter(filter)}
146148
isMultiSelect={!isFilterSingleSelect(filter)}
147149
onChange={onChange}
148150
data-testid={`dashboard-filter-select-${filter.name}`}
@@ -245,7 +247,12 @@ const DashboardFilters = ({
245247
// variable's selection.
246248
const pendingVariables = isQueryExpressionFilter(filter)
247249
? getPendingFilterValuesVariables(filter, variables)
248-
: undefined;
250+
: isSqlQueryFilter(filter)
251+
? getPendingFilterValuesVariables(
252+
{ where: filter.sqlTemplate, whereLanguage: 'sql' },
253+
variables,
254+
)
255+
: undefined;
249256
return (
250257
<DashboardFilterSelect
251258
key={filter.id}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
} from './filterFormState';
4141
import { PromqlLabelFilterEditForm } from './PromqlLabelFilterEditForm';
4242
import { QueryExpressionFilterEditForm } from './QueryExpressionFilterEditForm';
43+
import { SqlQueryFilterEditForm } from './SqlQueryFilterEditForm';
4344
import { StaticListFilterEditForm } from './StaticListFilterEditForm';
4445

4546
const FILTER_TYPE_OPTIONS = [
@@ -48,6 +49,7 @@ const FILTER_TYPE_OPTIONS = [
4849
label: 'Queried values',
4950
},
5051
{ value: DashboardFilterType.enum.STATIC_LIST, label: 'Static values' },
52+
{ value: DashboardFilterType.enum.SQL_QUERY, label: 'SQL query values' },
5153
...(IS_PROMQL_ENABLED
5254
? [
5355
{
@@ -79,6 +81,8 @@ interface DashboardFilterEditFormProps {
7981
showRequiredFilterOptions: boolean;
8082
/** The dashboard's current variable state, if any */
8183
variables?: ChartVariable[];
84+
/** The dashboard's date range, which filter previews run over */
85+
dateRange?: [Date, Date];
8286
onSave: (filter: DashboardFilter) => void;
8387
onClose: () => void;
8488
onCancel: () => void;
@@ -97,6 +101,7 @@ export const DashboardFilterEditForm = ({
97101
showVariableOptions,
98102
showRequiredFilterOptions,
99103
variables,
104+
dateRange,
100105
onSave,
101106
onClose,
102107
onCancel,
@@ -249,6 +254,14 @@ export const DashboardFilterEditForm = ({
249254
otherFilters={otherFilters}
250255
/>
251256
</SqlVariablesProvider>
257+
) : formFilterType === 'SQL_QUERY' ? (
258+
<SqlVariablesProvider variables={otherVariables}>
259+
<SqlQueryFilterEditForm
260+
control={control}
261+
otherFilters={otherFilters}
262+
dateRange={dateRange}
263+
/>
264+
</SqlVariablesProvider>
252265
) : formFilterType === 'PROMETHEUS_LABEL' ? (
253266
<SqlVariablesProvider variables={otherVariables}>
254267
<PromqlLabelFilterEditForm
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
import { useMemo, useState } from 'react';
2+
import { useFormState, useWatch } from 'react-hook-form';
3+
import { MACRO_SUGGESTIONS } from '@hyperdx/common-utils/dist/macros';
4+
import {
5+
DashboardFilter,
6+
SqlQueryDashboardFilter,
7+
} from '@hyperdx/common-utils/dist/types';
8+
import { Alert, Button, Group, Loader, Stack, Text } from '@mantine/core';
9+
import { IconAlertTriangle, IconPlayerPlay } from '@tabler/icons-react';
10+
11+
import { ConnectionSelectControlled } from '@/components/ConnectionSelect';
12+
import EmptyState from '@/components/EmptyState';
13+
import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor';
14+
import {
15+
buildSqlVariableCompletions,
16+
toMacroCompletion,
17+
useChartVariables,
18+
} from '@/components/SQLEditor/variableCompletions';
19+
import { NOW } from '@/config';
20+
import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues';
21+
import { truncateText } from '@/utils';
22+
23+
import { CustomInputWrapper } from './CustomInputWrapper';
24+
import { FilterFormControl } from './filterFormState';
25+
import { VariableNameInput } from './VariableNameInput';
26+
27+
/** Values the preview lists before summarizing the rest as a count. */
28+
const PREVIEW_VALUES_SHOWN = 20;
29+
/** Characters of each value the preview shows before truncating it. */
30+
const PREVIEW_VALUE_MAX_LENGTH = 20;
31+
32+
/** Macros that need a source, which a SQL query filter doesn't have. */
33+
const SOURCE_MACROS = new Set(['filters', 'sourceTable']);
34+
35+
const PLACEHOLDER_SQL = `SELECT DISTINCT env
36+
FROM default.environments
37+
WHERE $__filter(cloud, $cloud)
38+
ORDER BY env`;
39+
40+
interface SqlQueryFilterEditFormProps {
41+
control: FilterFormControl;
42+
/** Filters other than the one being edited, used to keep variable names unique. */
43+
otherFilters: DashboardFilter[];
44+
/** The range the preview runs over. Defaults to the last hour. */
45+
dateRange?: [Date, Date];
46+
}
47+
48+
/** Form describing a dashboard filter whose values come from a SQL query */
49+
export const SqlQueryFilterEditForm = ({
50+
control,
51+
otherFilters,
52+
dateRange,
53+
}: SqlQueryFilterEditFormProps) => {
54+
const { errors } = useFormState({ control });
55+
const variables = useChartVariables();
56+
const completions = useMemo(
57+
() => [
58+
...MACRO_SUGGESTIONS.filter(
59+
// `sourceTable(gauge)` etc. are per-metric variants of `sourceTable`.
60+
macro => !SOURCE_MACROS.has(macro.name.split('(')[0]),
61+
).map(toMacroCompletion),
62+
...buildSqlVariableCompletions(variables),
63+
],
64+
[variables],
65+
);
66+
67+
const [connection, sqlTemplate] = useWatch({
68+
control,
69+
name: ['connection', 'sqlTemplate'],
70+
});
71+
// What the preview last ran, so editing doesn't re-query on every keystroke.
72+
const [previewed, setPreviewed] = useState<{
73+
connection: string;
74+
sqlTemplate: string;
75+
}>();
76+
const canPreview = !!connection && !!sqlTemplate?.trim();
77+
const runPreview = () => {
78+
if (canPreview) setPreviewed({ connection, sqlTemplate });
79+
};
80+
81+
return (
82+
<>
83+
<CustomInputWrapper
84+
label="Connection"
85+
tooltipText="The ClickHouse connection the query runs on"
86+
error={errors.connection}
87+
>
88+
<div data-testid="filter-connection-select">
89+
<ConnectionSelectControlled
90+
control={control}
91+
name="connection"
92+
rules={{ required: 'Select a connection' }}
93+
/>
94+
</div>
95+
</CustomInputWrapper>
96+
97+
<CustomInputWrapper
98+
label="SQL query"
99+
tooltipText="The first column of the results fills the dropdown, in the order the query returns them. The query may use the time macros and reference the dashboard's other variables."
100+
error={errors.sqlTemplate}
101+
>
102+
<Stack gap="xs" data-testid="filter-sql-template-input">
103+
<SQLEditorControlled
104+
control={control}
105+
name="sqlTemplate"
106+
rules={{
107+
validate: (value: unknown) =>
108+
(typeof value === 'string' && value.trim().length > 0) ||
109+
'This field is required',
110+
}}
111+
height="150px"
112+
enableLineWrapping
113+
placeholder={PLACEHOLDER_SQL}
114+
additionalCompletions={completions}
115+
onSubmit={runPreview}
116+
/>
117+
<Group justify="flex-end">
118+
<Button
119+
variant="secondary"
120+
size="compact-sm"
121+
leftSection={<IconPlayerPlay size={14} />}
122+
disabled={!canPreview}
123+
onClick={runPreview}
124+
data-testid="filter-sql-preview-button"
125+
>
126+
Preview values
127+
</Button>
128+
</Group>
129+
{previewed && (
130+
<SqlQueryFilterPreview
131+
{...previewed}
132+
dateRange={dateRange}
133+
variables={variables}
134+
/>
135+
)}
136+
</Stack>
137+
</CustomInputWrapper>
138+
139+
<VariableNameInput control={control} otherFilters={otherFilters} />
140+
</>
141+
);
142+
};
143+
144+
const SqlQueryFilterPreview = ({
145+
connection,
146+
sqlTemplate,
147+
dateRange,
148+
variables,
149+
}: {
150+
connection: string;
151+
sqlTemplate: string;
152+
dateRange?: [Date, Date];
153+
variables: ReturnType<typeof useChartVariables>;
154+
}) => {
155+
const lastHour = useMemo(
156+
(): [Date, Date] => [new Date(NOW - 60 * 60 * 1000), new Date(NOW)],
157+
[],
158+
);
159+
const filters = useMemo(
160+
(): SqlQueryDashboardFilter[] => [
161+
{
162+
id: 'preview',
163+
type: 'SQL_QUERY',
164+
name: 'Preview',
165+
connection,
166+
sqlTemplate,
167+
isBroadcastEnabled: false,
168+
isVariableEnabled: true,
169+
},
170+
],
171+
[connection, sqlTemplate],
172+
);
173+
const { data, filterErrorMessages, isLoading, isError } =
174+
useSqlQueryFilterValues({
175+
filters,
176+
dateRange: dateRange ?? lastHour,
177+
variables,
178+
});
179+
const values = data.get('preview')?.values ?? [];
180+
181+
if (isLoading) {
182+
return (
183+
<Group gap="xs" data-testid="filter-sql-preview">
184+
<Loader size="xs" />
185+
<Text size="xs">Running query</Text>
186+
</Group>
187+
);
188+
}
189+
190+
if (isError) {
191+
return (
192+
<Alert
193+
variant="danger"
194+
icon={<IconAlertTriangle size={16} />}
195+
data-testid="filter-sql-preview"
196+
>
197+
{filterErrorMessages.get('preview') ?? 'The query failed.'}
198+
</Alert>
199+
);
200+
}
201+
202+
if (values.length === 0) {
203+
return (
204+
<div data-testid="filter-sql-preview">
205+
<EmptyState
206+
title="No values"
207+
description="The query returned no rows for the dashboard's time range."
208+
/>
209+
</div>
210+
);
211+
}
212+
213+
const notShown = values.length - PREVIEW_VALUES_SHOWN;
214+
return (
215+
<Stack gap={4} data-testid="filter-sql-preview">
216+
<Text size="xs" fw={500}>
217+
{values.length} {values.length === 1 ? 'value' : 'values'}
218+
</Text>
219+
<Text size="xs" data-testid="filter-sql-preview-values">
220+
{values.slice(0, PREVIEW_VALUES_SHOWN).map((value, index) => (
221+
<span key={value}>
222+
{index > 0 && ', '}
223+
<span title={value}>
224+
{truncateText(value, PREVIEW_VALUE_MAX_LENGTH, '…')}
225+
</span>
226+
</span>
227+
))}
228+
{notShown > 0 && `, and ${notShown} more`}
229+
</Text>
230+
</Stack>
231+
);
232+
};

0 commit comments

Comments
 (0)