Skip to content
8 changes: 8 additions & 0 deletions .changeset/sql-query-dashboard-filter-app.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hyperdx/common-utils': patch
'@hyperdx/app': patch
---

feat: create SQL query dashboard filters and fill their dropdowns

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.
1 change: 1 addition & 0 deletions packages/app/src/DBDashboardPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3603,6 +3603,7 @@ function DBDashboardPage({
showVariableOptions
showRequiredFilterOptions
variables={variables}
dateRange={searchedTimeRange}
/>
)}
</ReferenceVariablesProvider>
Expand Down
18 changes: 13 additions & 5 deletions packages/app/src/DashboardFilters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
isFilterRequired,
isQueryExpressionFilter,
isReferenceVariableFilter,
isSqlQueryFilter,
isStaticListFilter,
} from '@hyperdx/common-utils/dist/filters';
import { ReferenceVariableValues } from '@hyperdx/common-utils/dist/referenceVariables';
Expand Down Expand Up @@ -149,8 +150,9 @@ const DashboardFilterSelect = ({
// so a completed/empty/failed query stays interactive and the user can
// still clear or adjust the selection.
loading={isLoading}
// A static list renders in the order its author wrote it.
sort={!isStaticListFilter(filter)}
// A static list renders in the order its author wrote it, and a SQL
// query filter in the order its query returns.
sort={!isStaticListFilter(filter) && !isSqlQueryFilter(filter)}
isMultiSelect={!isFilterSingleSelect(filter)}
onChange={onChange}
data-testid={`dashboard-filter-select-${filter.name}`}
Expand Down Expand Up @@ -306,13 +308,19 @@ const DashboardFilters = ({
const isLoadingValues =
unresolvedVariables.length === 0 &&
(queriedFilterValues ? queriedFilterValues.isLoading : isFetching);
// Only a queried dropdown has a values query that can await a
// variable's selection, besides any data source variable it reads from.
// Only queried and SQL query dropdowns have a values query that can
// await a variable's selection, besides any data source variable it
// reads from.
const pendingVariables = [
...unselectedVariables,
...(isQueryExpressionFilter(filter)
? getPendingFilterValuesVariables(filter, variables)
: []),
: isSqlQueryFilter(filter)
? getPendingFilterValuesVariables(
{ where: filter.sqlTemplate, whereLanguage: 'sql' },
variables,
)
: []),
];
return (
<DashboardFilterSelect
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const CustomInputWrapper = ({
<div>
<Input.Label>{label}</Input.Label>
{tooltipText && (
<Tooltip label={tooltipText}>
<Tooltip label={tooltipText} multiline maw={400}>
<IconInfoCircle size={14} className="ms-2" />
</Tooltip>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
} from './filterFormState';
import { PromqlLabelFilterEditForm } from './PromqlLabelFilterEditForm';
import { QueryExpressionFilterEditForm } from './QueryExpressionFilterEditForm';
import { SqlQueryFilterEditForm } from './SqlQueryFilterEditForm';
import { StaticListFilterEditForm } from './StaticListFilterEditForm';
import { VariableNameInput } from './VariableNameInput';

Expand All @@ -51,6 +52,7 @@ const FILTER_TYPE_OPTIONS = [
label: 'Queried values',
},
{ value: DashboardFilterType.enum.STATIC_LIST, label: 'Static values' },
{ value: DashboardFilterType.enum.SQL_QUERY, label: 'SQL query values' },
Comment thread
karl-power marked this conversation as resolved.
Resolved
...(IS_PROMQL_ENABLED
? [
{
Expand Down Expand Up @@ -84,6 +86,8 @@ interface DashboardFilterEditFormProps {
showRequiredFilterOptions: boolean;
/** The dashboard's current variable state, if any */
variables?: ChartVariable[];
/** The dashboard's date range, which filter previews run over */
dateRange?: [Date, Date];
onSave: (filter: DashboardFilter) => void;
onClose: () => void;
onCancel: () => void;
Expand All @@ -102,6 +106,7 @@ export const DashboardFilterEditForm = ({
showVariableOptions,
showRequiredFilterOptions,
variables,
dateRange,
onSave,
onClose,
onCancel,
Expand Down Expand Up @@ -285,6 +290,14 @@ export const DashboardFilterEditForm = ({
otherFilters={otherFilters}
/>
</SqlVariablesProvider>
) : formFilterType === 'SQL_QUERY' ? (
<SqlVariablesProvider variables={otherVariables}>
<SqlQueryFilterEditForm
control={control}
otherFilters={otherFilters}
dateRange={dateRange}
/>
</SqlVariablesProvider>
) : formFilterType === 'PROMETHEUS_LABEL' ? (
<SqlVariablesProvider variables={otherVariables}>
<PromqlLabelFilterEditForm
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
import { useMemo, useState } from 'react';
import { useFormState, useWatch } from 'react-hook-form';
import { validateSqlQueryFilterTemplate } from '@hyperdx/common-utils/dist/filters';
import {
INTERVAL_MACROS,
MACRO_SUGGESTIONS,
SOURCE_DEPENDENT_MACROS,
} from '@hyperdx/common-utils/dist/macros';
import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables';
import {
DashboardFilter,
SqlQueryDashboardFilter,
} from '@hyperdx/common-utils/dist/types';
import { Alert, Button, Group, Loader, Stack, Text } from '@mantine/core';
import { IconAlertTriangle, IconPlayerPlay } from '@tabler/icons-react';
import { useQueryClient } from '@tanstack/react-query';

import { ConnectionSelectControlled } from '@/components/ConnectionSelect';
import EmptyState from '@/components/EmptyState';
import { useResolvedReference } from '@/components/sourceSelectUtils';
import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor';
import {
buildSqlVariableCompletions,
toMacroCompletion,
useChartVariables,
} from '@/components/SQLEditor/variableCompletions';
import { NOW } from '@/config';
import {
SQL_QUERY_FILTER_VALUES_QUERY_KEY,
useSqlQueryFilterValues,
} from '@/hooks/useSqlQueryFilterValues';
import { truncateText } from '@/utils';

import { TOOLTIP_PORTAL_TARGET } from './constants';
import { CustomInputWrapper } from './CustomInputWrapper';
import { FilterFormControl } from './filterFormState';
import { VariableNameInput } from './VariableNameInput';

/** Values the preview lists before summarizing the rest as a count. */
const PREVIEW_VALUES_SHOWN = 20;
/** Characters of each value the preview shows before truncating it. */
const PREVIEW_VALUE_MAX_LENGTH = 20;

/**
* Macros a SQL query filter can't expand: it has no source, and no time buckets.
*/
const UNSUPPORTED_MACROS = new Set<string>([
...SOURCE_DEPENDENT_MACROS,
...INTERVAL_MACROS,
]);

const PLACEHOLDER_SQL = `SELECT DISTINCT env
FROM default.environments
WHERE $__filter(cloud, $cloud)
ORDER BY env`;

interface SqlQueryFilterEditFormProps {
control: FilterFormControl;
/** Filters other than the one being edited, used to keep variable names unique. */
otherFilters: DashboardFilter[];
/** The range the preview runs over. Defaults to the last hour. */
dateRange?: [Date, Date];
}

/** Form describing a dashboard filter whose values come from a SQL query */
export const SqlQueryFilterEditForm = ({
control,
otherFilters,
dateRange,
}: SqlQueryFilterEditFormProps) => {
const { errors } = useFormState({ control });
const variables = useChartVariables();
const completions = useMemo(
() => [
...MACRO_SUGGESTIONS.filter(
// `sourceTable(gauge)` etc. are per-metric variants of `sourceTable`.
macro => !UNSUPPORTED_MACROS.has(macro.name.split('(')[0]),
).map(toMacroCompletion),
...buildSqlVariableCompletions(variables),
],
[variables],
);

const [connection, sqlTemplate] = useWatch({
control,
name: ['connection', 'sqlTemplate'],
});
// What the preview last ran, so editing doesn't re-query on every keystroke.
const [previewed, setPreviewed] = useState<{
connection: string;
sqlTemplate: string;
}>();
// A connection variable previews as the connection it currently selects.
const resolvedConnection = useResolvedReference(connection);
const unresolvedConnection =
parseVariableReference(connection) != null && !resolvedConnection;
const canPreview = !!resolvedConnection && !!sqlTemplate?.trim();
const queryClient = useQueryClient();
const runPreview = () => {
if (!canPreview) return;
// The same query keeps its cache key, so re-run it explicitly.
if (
Comment thread
karl-power marked this conversation as resolved.
Resolved
previewed?.connection === resolvedConnection &&
previewed.sqlTemplate === sqlTemplate
) {
void queryClient.invalidateQueries({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Preview re-run invalidates every SQL query filter on the connection, and the first preview can return cached dashboard results

invalidateQueries({ queryKey: [KEY, resolvedConnection] }) is a prefix match, so each repeat click also refetches every SQL query filter the dashboard behind the modal shows on that connection. When editing an existing filter, the first click shows results the dashboard cached in the last 5 minutes (staleTime) instead of running the query. Re-run only the preview's own query on every click: return refetch from the hook, or invalidate the exact key including the SQL and params. The test only checks that invalidateQueries was called with a mocked key, so also assert that the query runs again.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

queryKey: [SQL_QUERY_FILTER_VALUES_QUERY_KEY, resolvedConnection],
});
}
setPreviewed({ connection: resolvedConnection, sqlTemplate });
};

return (
<>
<CustomInputWrapper
label="Connection"
tooltipText="The ClickHouse connection the query runs on, which can be a connection variable"
error={errors.connection}
>
<div data-testid="filter-connection-select">
<ConnectionSelectControlled
control={control}
name="connection"
rules={{ required: 'Select a connection' }}
allowConnectionVariables
/>
</div>
</CustomInputWrapper>

<CustomInputWrapper
label="SQL query"
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."
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
error={errors.sqlTemplate}
>
<Stack gap="xs" data-testid="filter-sql-template-input">
<SQLEditorControlled
control={control}
name="sqlTemplate"
rules={{
validate: (value: unknown) => {
if (typeof value !== 'string' || !value.trim()) {
return 'This field is required';
}
// `variables` leaves out this filter's own, so a reference to
// it is rejected as unknown.
return (
validateSqlQueryFilterTemplate(value, variables ?? []) ?? true
);
},
}}
height="150px"
enableLineWrapping
placeholder={PLACEHOLDER_SQL}
additionalCompletions={completions}
onSubmit={runPreview}
parentRef={TOOLTIP_PORTAL_TARGET}
/>
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
<Group justify="flex-end">
{unresolvedConnection && (
<Text size="xs" c="dimmed">
Select a value for {connection} to preview
</Text>
)}
<Button
variant="secondary"
size="compact-sm"
leftSection={<IconPlayerPlay size={14} />}
disabled={!canPreview}
onClick={runPreview}
data-testid="filter-sql-preview-button"
>
Preview values
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
</Button>
</Group>
{previewed && (
<SqlQueryFilterPreview
{...previewed}
dateRange={dateRange}
variables={variables}
/>
)}
</Stack>
</CustomInputWrapper>

<VariableNameInput control={control} otherFilters={otherFilters} />
</>
);
};

const SqlQueryFilterPreview = ({
connection,
sqlTemplate,
dateRange,
variables,
}: {
connection: string;
sqlTemplate: string;
dateRange?: [Date, Date];
variables: ReturnType<typeof useChartVariables>;
}) => {
const lastHour = useMemo(
Comment thread
karl-power marked this conversation as resolved.
Resolved
(): [Date, Date] => [new Date(NOW - 60 * 60 * 1000), new Date(NOW)],
[],
);
const filters = useMemo(
(): SqlQueryDashboardFilter[] => [
{
id: 'preview',
type: 'SQL_QUERY',
name: 'Preview',
connection,
sqlTemplate,
isBroadcastEnabled: false,
isVariableEnabled: true,
},
],
[connection, sqlTemplate],
);
const { data, filterErrorMessages, isLoading, isFetching, isError } =
useSqlQueryFilterValues({
filters,
dateRange: dateRange ?? lastHour,
variables,
});
const values = data.get('preview')?.values ?? [];

// While a re-run loads, the previous query's values stand in as placeholder
// data, so isLoading alone would show them as this query's results.
if (isLoading || isFetching) {
return (
<Group gap="xs" data-testid="filter-sql-preview">
<Loader size="xs" />
<Text size="xs">Running query</Text>
</Group>
);
}

if (isError) {
return (
<Alert
variant="danger"
icon={<IconAlertTriangle size={16} />}
data-testid="filter-sql-preview"
>
{filterErrorMessages.get('preview') ?? 'The query failed.'}
</Alert>
);
}

if (values.length === 0) {
return (
<div data-testid="filter-sql-preview">
<EmptyState
title="No values"
description="The query returned no rows for the dashboard's time range."
/>
</div>
);
}

Comment thread
karl-power marked this conversation as resolved.
Resolved
const notShown = values.length - PREVIEW_VALUES_SHOWN;
return (
<Stack gap={4} data-testid="filter-sql-preview">
<Text size="xs" fw={500}>
{values.length} {values.length === 1 ? 'value' : 'values'}
Comment thread
karl-power marked this conversation as resolved.
Resolved
</Text>
<Text size="xs" data-testid="filter-sql-preview-values">
{values.slice(0, PREVIEW_VALUES_SHOWN).map((value, index) => (
<span key={value}>
{index > 0 && ', '}
<span title={value}>
Comment thread
karl-power marked this conversation as resolved.
Resolved
{truncateText(value, PREVIEW_VALUE_MAX_LENGTH, '…')}
</span>
</span>
))}
{notShown > 0 && `, and ${notShown} more`}
</Text>
</Stack>
);
};
Loading
Loading