Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -3510,6 +3510,7 @@ function DBDashboardPage({
showVariableOptions
showRequiredFilterOptions
variables={variables}
dateRange={searchedTimeRange}
/>
)}
</>
Expand Down
17 changes: 12 additions & 5 deletions packages/app/src/DashboardFilters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isFilterRequired,
isFilterVariableEnabled,
isQueryExpressionFilter,
isSqlQueryFilter,
isStaticListFilter,
} from '@hyperdx/common-utils/dist/filters';
import {
Expand Down Expand Up @@ -141,8 +142,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 @@ -241,11 +243,16 @@ const DashboardFilters = ({
const isLoadingValues = queriedFilterValues
? queriedFilterValues.isLoading
: isFetching;
// Only a queried dropdown has a values query that can await a
// variable's selection.
// Only queried and SQL query dropdowns have a values query that can
// await a variable's selection.
const pendingVariables = isQueryExpressionFilter(filter)
? getPendingFilterValuesVariables(filter, variables)
: undefined;
: isSqlQueryFilter(filter)
? getPendingFilterValuesVariables(
{ where: filter.sqlTemplate, whereLanguage: 'sql' },
variables,
)
: undefined;
return (
<DashboardFilterSelect
key={filter.id}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
} from './filterFormState';
import { PromqlLabelFilterEditForm } from './PromqlLabelFilterEditForm';
import { QueryExpressionFilterEditForm } from './QueryExpressionFilterEditForm';
import { SqlQueryFilterEditForm } from './SqlQueryFilterEditForm';
import { StaticListFilterEditForm } from './StaticListFilterEditForm';

const FILTER_TYPE_OPTIONS = [
Expand All @@ -48,6 +49,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' },
...(IS_PROMQL_ENABLED
? [
{
Expand Down Expand Up @@ -79,6 +81,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 @@ -97,6 +101,7 @@ export const DashboardFilterEditForm = ({
showVariableOptions,
showRequiredFilterOptions,
variables,
dateRange,
onSave,
onClose,
onCancel,
Expand Down Expand Up @@ -249,6 +254,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,251 @@
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 {
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 { ConnectionSelectControlled } from '@/components/ConnectionSelect';
import EmptyState from '@/components/EmptyState';
import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor';
import {
buildSqlVariableCompletions,
toMacroCompletion,
useChartVariables,
} from '@/components/SQLEditor/variableCompletions';
import { NOW } from '@/config';
import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues';
import { truncateText } from '@/utils';

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;
}>();
const canPreview = !!connection && !!sqlTemplate?.trim();
const runPreview = () => {
if (canPreview) setPreviewed({ connection, sqlTemplate });
};

return (
<>
<CustomInputWrapper
label="Connection"
tooltipText="The ClickHouse connection the query runs on"
error={errors.connection}
>
<div data-testid="filter-connection-select">
<ConnectionSelectControlled
control={control}
name="connection"
rules={{ required: 'Select a connection' }}
/>
</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."
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}
/>
<Group justify="flex-end">
<Button
variant="secondary"
size="compact-sm"
leftSection={<IconPlayerPlay size={14} />}
disabled={!canPreview}
onClick={runPreview}
data-testid="filter-sql-preview-button"
>
Preview values
</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>
);
}

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'}
</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}>
{truncateText(value, PREVIEW_VALUE_MAX_LENGTH, '…')}
</span>
</span>
))}
{notShown > 0 && `, and ${notShown} more`}
</Text>
</Stack>
);
};
Loading
Loading