diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 92ee40d56..26e998805 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -5917,11 +5917,14 @@ describe('External API v2 Dashboards - new format', () => { ...overrides, }); - const sendFilters = async (filters: Record[]) => { - const payload = createMockDashboardWithIds( - traceSource._id.toString(), - {}, - ); + const sendFilters = async ( + filters: Record[], + savedFilterValues: Record[] = [], + ) => { + const payload = { + ...createMockDashboardWithIds(traceSource._id.toString(), {}), + savedFilterValues, + }; if (method === 'post') { // A create body may not choose filter ids, so the shared fixtures shed // theirs on this path. @@ -6154,6 +6157,37 @@ describe('External API v2 Dashboards - new format', () => { }); }); + // Held back until the dashboard UI offers "All". + describe('"All" option', () => { + it.each([ + ['STATIC_LIST', () => staticFilterInput({ allowAll: true })], + [ + 'SQL_QUERY', + () => ({ + id: new ObjectId().toString(), + type: 'SQL_QUERY' as const, + name: 'Environment', + connectionId: connection._id.toString(), + sqlTemplate: 'SELECT DISTINCT env FROM envs', + allowAll: true, + }), + ], + ] as const)( + 'rejects allowAll on a %s filter', + async (_type, makeFilter) => { + await expectFilters([makeFilter()], 400); + }, + ); + + it('rejects a saved "all" value', async () => { + const response = await sendFilters( + [staticFilterInput()], + [{ type: 'variable', name: 'env', values: [], all: true }], + ); + expect(response.status).toBe(400); + }); + }); + describe('required filters', () => { // Named factories rather than a keyed map, so the label `it.each` prints // does not have to come from a lookup evaluated at collection time diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index b74358c17..6f99aa486 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -200,8 +200,11 @@ const externalQueryExpressionFilterShape = }); // A static filter's mode flags each accept exactly one value, so callers may -// omit them and get that value. -const externalStaticListFilterShape = StaticListDashboardFilterSchema.extend({ +// omit them and get that value. `allowAll` is held back until the dashboard UI +// offers "All". +const externalStaticListFilterShape = StaticListDashboardFilterSchema.omit({ + allowAll: true, +}).extend({ isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); @@ -215,10 +218,11 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ }); // `connectionId`/`sourceId` rather than `connection`/`source`, matching raw SQL -// tiles. +// tiles. `allowAll` is held back until the dashboard UI offers "All". const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ connection: true, source: true, + allowAll: true, }).extend({ connectionId: objectIdOrVariableReferenceSchema, sourceId: objectIdOrVariableReferenceSchema.optional(), @@ -300,8 +304,9 @@ export const externalSqlSavedFilterValueSchema = z.object({ condition: z.string().max(10000), }); +// `all` is held back until the dashboard UI offers "All". export const externalVariableSavedFilterValueSchema = - VariableFilterValueSchema.strict(); + VariableFilterValueSchema.omit({ all: true }).strict(); export const externalAdhocSavedFilterValueSchema = AdhocFilterValueSchema.strict(); diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index 300e03775..a1fd57b59 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -247,6 +247,16 @@ describe('dashboardFilterValues', () => { ]); }); + it('keeps an "all" selection even though it carries no values', () => { + expect( + serializeDashboardFilterValues({ + byVariable: new Map([ + ['env', { type: 'variable', values: ['ignored'], all: true }], + ]), + }), + ).toEqual([{ type: 'variable', name: 'env', values: [], all: true }]); + }); + it('emits legacy entries byte-identically to filtersToQuery', () => { const byExpression: FilterState = { ServiceName: { @@ -445,6 +455,18 @@ describe('dashboardFilterValues', () => { ); }); + it('resolves an "all" entry to an empty selection', () => { + // The included/excluded shape can't hold "all", and the entry's values + // are ignored, so neither may leak into it. + const parsed = parseDashboardFilterValues([ + { type: 'variable', name: 'env', values: ['prod'], all: true }, + ]); + + expect(resolveFilterSelection(staticFilter(), parsed)).toEqual( + included(), + ); + }); + it('treats an explicitly empty variable entry as a selection', () => { const parsed = parseDashboardFilterValues([ { type: 'sql', condition: "ServiceName IN ('legacy')" }, diff --git a/packages/common-utils/src/__tests__/dashboardValidation.test.ts b/packages/common-utils/src/__tests__/dashboardValidation.test.ts index 3856541f2..d60d3a4c7 100644 --- a/packages/common-utils/src/__tests__/dashboardValidation.test.ts +++ b/packages/common-utils/src/__tests__/dashboardValidation.test.ts @@ -1,11 +1,13 @@ import { z } from 'zod/v3'; import { + collectRefinementIssues, validateChartConfigFormulas, validateDashboardFilterFieldGating, validateDashboardFilterModes, validateDashboardFilterOptionUniqueness, validateDashboardFilterVariableNames, + validateDashboardSavedFilterValues, } from '@/dashboardValidation'; type TestFilter = { @@ -288,6 +290,8 @@ type GatingFilter = ModeFilter & { sourceType?: string; where?: string; whereLanguage?: string; + allowAll?: boolean; + maxSelections?: number; }; const collectGatingIssues = ( @@ -444,6 +448,76 @@ describe('validateDashboardFilterFieldGating', () => { expect(issues[0].path).toEqual(['body', 'filters', 0, 'variableName']); }); + + it('rejects allowAll on a single-select filter only', () => { + const issues = collectGatingIssues([ + { name: 'Multi', isVariableEnabled: true, allowAll: true }, + { + name: 'Single', + isVariableEnabled: true, + allowAll: true, + maxSelections: 1, + }, + { + name: 'Off', + isVariableEnabled: true, + allowAll: false, + maxSelections: 1, + }, + ]); + + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['filters', 1, 'allowAll']); + expect(issues[0].message).toBe( + 'Filter "Single" sets allowAll but is single-select; drop allowAll or maxSelections', + ); + }); +}); + +describe('validateDashboardSavedFilterValues', () => { + const filters = [ + { + type: 'STATIC_LIST' as const, + name: 'Environment', + variableName: 'env', + allowAll: true, + }, + { type: 'STATIC_LIST' as const, name: 'Region', variableName: 'region' }, + ]; + + const collect = ( + savedFilterValues: Parameters[1], + ) => + collectRefinementIssues(ctx => + validateDashboardSavedFilterValues(filters, savedFilterValues, ctx), + ); + + it('accepts "all" on a filter that offers it', () => { + expect(collect([{ type: 'variable', name: 'env', all: true }])).toEqual([]); + }); + + it('rejects "all" on a filter that does not offer it', () => { + const issues = collect([ + { type: 'variable', name: 'env', all: true }, + { type: 'variable', name: 'region', all: true }, + ]); + + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['savedFilterValues', 1, 'all']); + expect(issues[0].message).toBe( + 'Saved filter value for "region" sets all: true, but its filter does not offer "All"; set allowAll on the filter or select specific values', + ); + }); + + it('ignores explicit values and names no filter declares', () => { + expect( + collect([ + { type: 'variable', name: 'region' }, + { type: 'variable', name: 'unknown', all: true }, + { type: 'sql', all: true }, + ]), + ).toEqual([]); + }); }); type OptionsFilter = Parameters< diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index 849b27736..5fb4da606 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -6,6 +6,7 @@ import { FilterState, filterStateToPredicate, filtersToQuery, + filterSupportsAllValue, getAdhocFilterAppliesToSourceIds, getDashboardVariableDeclarations, getDashboardVariableFilters, @@ -2050,6 +2051,40 @@ describe('filters', () => { }); }); + describe('filterSupportsAllValue', () => { + it('holds for multi-select static list and SQL query filters that opt in', () => { + expect( + filterSupportsAllValue({ type: 'STATIC_LIST', allowAll: true }), + ).toBe(true); + expect( + filterSupportsAllValue({ type: 'SQL_QUERY', allowAll: true }), + ).toBe(true); + }); + + it('does not hold without the opt-in', () => { + expect(filterSupportsAllValue({ type: 'STATIC_LIST' })).toBe(false); + expect( + filterSupportsAllValue({ type: 'SQL_QUERY', allowAll: false }), + ).toBe(false); + }); + + it('does not hold for a single-select filter', () => { + expect( + filterSupportsAllValue({ + type: 'STATIC_LIST', + allowAll: true, + maxSelections: 1, + }), + ).toBe(false); + }); + + it('does not hold for other filter types', () => { + expect( + filterSupportsAllValue({ type: 'QUERY_EXPRESSION', allowAll: true }), + ).toBe(false); + }); + }); + describe('isFilterGlobalRequirement', () => { it('treats a missing flag as covering only the tiles that read the filter', () => { expect(isFilterGlobalRequirement({})).toBe(false); diff --git a/packages/common-utils/src/__tests__/types.test.ts b/packages/common-utils/src/__tests__/types.test.ts index 8b670f222..a80619339 100644 --- a/packages/common-utils/src/__tests__/types.test.ts +++ b/packages/common-utils/src/__tests__/types.test.ts @@ -588,6 +588,11 @@ describe('DashboardFilterSchema static-list variant', () => { ]); }); + it('keeps allowAll', () => { + const withAll = { ...staticFilter, allowAll: true }; + expect(DashboardFilterSchema.parse(withAll)).toEqual(withAll); + }); + it('rejects an unknown filter type at the discriminator', () => { const result = DashboardFilterSchema.safeParse({ ...staticFilter, @@ -694,6 +699,11 @@ describe('DashboardFilterSchema SQL query variant', () => { expect(DashboardFilterSchema.parse(sqlFilter)).toEqual(sqlFilter); }); + it('keeps allowAll', () => { + const withAll = { ...sqlFilter, allowAll: true }; + expect(DashboardFilterSchema.parse(withAll)).toEqual(withAll); + }); + it.each(['connection', 'sqlTemplate'] as const)( 'requires a non-empty %s', field => { @@ -867,6 +877,16 @@ describe('DashboardFilterValueSchema', () => { ).toBe(true); }); + it('accepts an "all" entry and rejects any other value for the flag', () => { + const entry = { type: 'variable', name: 'svc', values: [] }; + expect( + DashboardFilterValueSchema.safeParse({ ...entry, all: true }).success, + ).toBe(true); + expect( + DashboardFilterValueSchema.safeParse({ ...entry, all: false }).success, + ).toBe(false); + }); + it('requires a non-empty name and a values array', () => { for (const entry of [ { type: 'variable', values: ['a'] }, diff --git a/packages/common-utils/src/__tests__/variableSelection.test.ts b/packages/common-utils/src/__tests__/variableSelection.test.ts new file mode 100644 index 000000000..bd40cf3bc --- /dev/null +++ b/packages/common-utils/src/__tests__/variableSelection.test.ts @@ -0,0 +1,58 @@ +import type { ChartVariable } from '@/types'; +import { + ALL_SELECTION, + expandAllSelections, + isAllSelection, + selectionHasValue, +} from '@/variableSelection'; + +describe('isAllSelection', () => { + it('holds only for the "all" marker', () => { + expect(isAllSelection(ALL_SELECTION)).toBe(true); + expect(isAllSelection(['a'])).toBe(false); + expect(isAllSelection([])).toBe(false); + expect(isAllSelection(undefined)).toBe(false); + }); +}); + +describe('selectionHasValue', () => { + it('holds for "all" and for a non-empty list', () => { + expect(selectionHasValue(ALL_SELECTION)).toBe(true); + expect(selectionHasValue(['a'])).toBe(true); + }); + + it('treats an empty list like no selection', () => { + expect(selectionHasValue([])).toBe(false); + expect(selectionHasValue(undefined)).toBe(false); + }); +}); + +describe('expandAllSelections', () => { + const env: ChartVariable = { name: 'env', values: [], all: true }; + const region: ChartVariable = { name: 'region', values: ['eu'] }; + + it('fills an "all" variable with its sorted options', () => { + expect( + expandAllSelections( + [env, region], + new Map([ + ['env', ['staging', 'prod']], + ['region', ['us', 'eu']], + ]), + ), + ).toEqual([ + { name: 'env', values: ['prod', 'staging'], all: true }, + region, + ]); + }); + + it('leaves an "all" variable empty until its options are known', () => { + expect(expandAllSelections([env], new Map())).toEqual([env]); + }); + + it('does not mutate the options it was given', () => { + const options = ['staging', 'prod']; + expandAllSelections([env], new Map([['env', options]])); + expect(options).toEqual(['staging', 'prod']); + }); +}); diff --git a/packages/common-utils/src/__tests__/variables.test.ts b/packages/common-utils/src/__tests__/variables.test.ts index 9614f0310..88896e2c6 100644 --- a/packages/common-utils/src/__tests__/variables.test.ts +++ b/packages/common-utils/src/__tests__/variables.test.ts @@ -40,6 +40,8 @@ const substituteVariablesSql = ( const SERVICE = variable('service', ['api', 'web'], 'ServiceName'); const EMPTY_SERVICE = variable('service', [], 'ServiceName'); +/** "All" selected, with the filter's options already expanded into `values`. */ +const ALL_SERVICE: ChartVariable = { ...SERVICE, all: true }; const builderConfig = ( overrides: Partial = {}, @@ -239,6 +241,14 @@ describe('substituteVariables', () => { ).toBe("'checkout'"); }); + it('renders every option when "All" is selected', () => { + expect( + substituteVariablesSql('WHERE ServiceName IN ($service)', [ + ALL_SERVICE, + ]), + ).toBe("WHERE ServiceName IN ('api', 'web')"); + }); + it('leaves a lone $ and $-digit sequences alone', () => { expect(substituteVariablesSql('SELECT $, $1, x$', [SERVICE])).toBe( 'SELECT $, $1, x$', @@ -369,6 +379,14 @@ describe('substituteVariables', () => { ).toBe("WHERE (1=1 /** no values selected for variable 'service' */)"); }); + it('matches every option when "All" is selected', () => { + expect( + substituteVariablesSql('WHERE $__filter(ServiceName, $service)', [ + ALL_SERVICE, + ]), + ).toBe("WHERE (ServiceName IN ('api', 'web'))"); + }); + it('substitutes references nested in the expression argument', () => { expect( substituteVariablesSql( @@ -462,6 +480,15 @@ describe('substituteVariables', () => { ).toBe("WHERE (ServiceName IN ('api', 'web'))"); }); + it('emits a no-op predicate when "All" is selected', () => { + expect( + substituteVariablesSql( + 'WHERE $__conditionalAll(ServiceName IN ($service), $service)', + [ALL_SERVICE], + ), + ).toBe("WHERE (1=1 /** all values selected for variable 'service' */)"); + }); + it('rejects a name argument written without its $', () => { expect(() => substituteVariablesSql( diff --git a/packages/common-utils/src/dashboardFilterValues.ts b/packages/common-utils/src/dashboardFilterValues.ts index a0e7922d1..156c1c73f 100644 --- a/packages/common-utils/src/dashboardFilterValues.ts +++ b/packages/common-utils/src/dashboardFilterValues.ts @@ -121,6 +121,11 @@ export function serializeDashboardFilterValues(input: { ]; for (const [name, value] of input.byVariable ?? []) { + if (value.type === 'variable' && value.all) { + // "all" carries no values but is still a selection, so it isn't omitted. + entries.push({ type: 'variable', name, values: [], all: true }); + continue; + } // Empty selections are omitted. const isEmpty = value.type === 'adhoc' @@ -190,7 +195,7 @@ function resolveUncappedFilterSelection( const values = parsed.byVariable.get(key.name); if (values?.type === 'variable') { return { - included: new Set(values.values), + included: new Set(values.all ? [] : values.values), excluded: new Set(), }; } diff --git a/packages/common-utils/src/dashboardValidation.ts b/packages/common-utils/src/dashboardValidation.ts index 863ede007..e29745d14 100644 --- a/packages/common-utils/src/dashboardValidation.ts +++ b/packages/common-utils/src/dashboardValidation.ts @@ -2,6 +2,8 @@ import { z } from 'zod/v3'; import { validateFormula } from './core/formula'; import { + DashboardFilterKind, + filterSupportsAllValue, getFilterVariableName, hasFilterEffect, isFilterBroadcastEnabled, @@ -23,6 +25,7 @@ import { DashboardFilter, DisplayType, } from './types'; +import { isFilterSingleSelect } from './variables'; // Inputs shared by the internal `DashboardSchema` refinement and the // external API body schema: the validation only depends on the @@ -49,6 +52,8 @@ type FilterForGatingValidation = FilterForModeValidation & { sourceType?: string; where?: string; whereLanguage?: string; + allowAll?: boolean; + maxSelections?: number; }; /** @@ -259,6 +264,8 @@ export function validateDashboardFilterModes( * - A non-empty `appliesToSourceIds` on a filter that does not broadcast (path `[i].appliesToSourceIds`). * - `where` or `whereLanguage` on a PromQL ad hoc filter, which only SQL ad hoc * filters read (path `[i].where` / `.whereLanguage`). + * - `allowAll` on a single-select filter, where "All" isn't offered + * (path `[i].allowAll`). */ export function validateDashboardFilterFieldGating< T extends FilterForGatingValidation, @@ -304,6 +311,68 @@ export function validateDashboardFilterFieldGating< }); } } + + if (filter.allowAll === true && isFilterSingleSelect(filter)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Filter "${filter.name}" sets allowAll but is single-select; drop allowAll or maxSelections`, + path: [...filtersPath, filterIdx, 'allowAll'], + }); + } + }); +} + +type FilterForAllValueValidation = { + type: DashboardFilterKind; + name: string; + variableName?: string; + allowAll?: boolean; + maxSelections?: number; +}; + +type SavedFilterValueForValidation = { + type?: string; + name?: string; + all?: boolean; +}; + +/** + * Rejects an `all: true` saved filter value addressed to a filter that cannot + * hold one (see `filterSupportsAllValue`). Values for undeclared names are left + * alone: the dashboard ignores them when it loads. + * + * Issues raised: + * - `all: true` for a filter that doesn't offer "All" + * (path `[i].all`). + */ +export function validateDashboardSavedFilterValues( + filters: FilterForAllValueValidation[], + savedFilterValues: SavedFilterValueForValidation[], + ctx: z.RefinementCtx, + paths?: { savedFilterValuesPath?: (string | number)[] }, +): void { + const savedFilterValuesPath = paths?.savedFilterValuesPath ?? [ + 'savedFilterValues', + ]; + + const declaredNames = new Set(); + const allCapableNames = new Set(); + for (const filter of filters) { + const variableName = getFilterVariableName(filter); + if (!variableName) continue; + declaredNames.add(variableName); + if (filterSupportsAllValue(filter)) allCapableNames.add(variableName); + } + + savedFilterValues.forEach((value, valueIdx) => { + if (value.type !== 'variable' || !value.all) return; + const name = value.name ?? ''; + if (!declaredNames.has(name) || allCapableNames.has(name)) return; + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Saved filter value for "${name}" sets all: true, but its filter does not offer "All"; set allowAll on the filter or select specific values`, + path: [...savedFilterValuesPath, valueIdx, 'all'], + }); }); } diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index d443fd303..0e804715a 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -36,6 +36,7 @@ import { escapePromqlStringValue, formatVariableValues, getVariableReferences, + isFilterSingleSelect, substituteVariables, } from '@/variables'; @@ -1130,6 +1131,27 @@ export function isPrometheusLabelFilter< return filter.type === 'PROMETHEUS_LABEL'; } +/** + * Whether the filter's selection can be an "all" value sentinel: a static list + * or SQL query filter that opts in with `allowAll` and is multi-select. + * + * Limited to filters whose option list the author controls, so "all" is a known + * set. Query expression and Prometheus label options are capped and scoped to + * the time range, so "all" could silently miss values, and a broadcasting query + * expression filter would also need a rule for what "all" applies to tiles. + */ +export function filterSupportsAllValue(filter: { + type: DashboardFilterKind; + allowAll?: boolean; + maxSelections?: number; +}): boolean { + return ( + (filter.type === 'STATIC_LIST' || filter.type === 'SQL_QUERY') && + filter.allowAll === true && + !isFilterSingleSelect(filter) + ); +} + /** Type guard for ADHOC type filters. */ export function isAdhocFilter( filter: T, diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 03bc2cffa..c7274397d 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1333,6 +1333,8 @@ export const VariableFilterValueSchema = z.object({ type: z.literal('variable'), name: z.string().min(1).max(1024), values: z.array(z.string().max(10000)).max(1000), + /** When true, represents a selection of "all available values", and `values` is ignored. */ + all: z.literal(true).optional(), }); export type VariableFilterValue = z.infer; @@ -1901,6 +1903,11 @@ export const ChartVariableSchema = z.object({ values: z.array(z.string()), /** The filter's selection cap; 1 means the variable is single-select. */ maxSelections: z.number().optional(), + /** + * Set when "All" is selected. `values` holds every option once expanded by + * `expandAllSelections`, and is empty until then. + */ + all: z.literal(true).optional(), }); export type ChartVariable = z.infer; @@ -2416,6 +2423,12 @@ export const QueryExpressionDashboardFilterSchema = isVariableEnabled: z.boolean().optional(), }); +/** + * Whether the dropdown offers an "All" option, which selects every option the + * filter lists. Multi-select filters only (`validateDashboardFilterFieldGating`). + */ +const dashboardFilterAllowAllSchema = z.boolean().optional(); + /** A filter whose dropdown offers a hand-authored list. */ export const StaticListDashboardFilterSchema = dashboardFilterBaseSchema.extend( { @@ -2424,6 +2437,7 @@ export const StaticListDashboardFilterSchema = dashboardFilterBaseSchema.extend( .array(z.string().min(1).max(10000)) .min(1) .max(DASHBOARD_STATIC_FILTER_MAX_OPTIONS), + allowAll: dashboardFilterAllowAllSchema, isBroadcastEnabled: z.literal(false), isVariableEnabled: z.literal(true), }, @@ -2466,6 +2480,7 @@ export const SqlQueryDashboardFilterSchema = dashboardFilterBaseSchema.extend({ */ source: z.string().min(1).optional(), sqlTemplate: z.string().min(1), + allowAll: dashboardFilterAllowAllSchema, // Variable-only: there is no column to broadcast isBroadcastEnabled: z.literal(false), isVariableEnabled: z.literal(true), diff --git a/packages/common-utils/src/variableSelection.ts b/packages/common-utils/src/variableSelection.ts new file mode 100644 index 000000000..61ab72c5f --- /dev/null +++ b/packages/common-utils/src/variableSelection.ts @@ -0,0 +1,46 @@ +import type { ChartVariable } from '@/types'; + +/** + * A dashboard variable's selection: an explicit list of values, or the + * `{ all: true }` marker meaning every option its filter offers. Only filters + * that pass `filterSupportsAllValue` can hold the marker. + */ +export type VariableSelection = string[] | { all: true }; + +/** The "all" selection. */ +export const ALL_SELECTION: VariableSelection = { all: true }; + +/** True when a selection is the "all" marker. */ +export function isAllSelection( + selection: VariableSelection | undefined, +): selection is { all: true } { + return ( + selection != null && !Array.isArray(selection) && selection.all === true + ); +} + +/** + * True when a selection is "all" or a non-empty value list. An empty array + * means nothing is selected, the same as an absent selection. + */ +export function selectionHasValue( + selection: VariableSelection | undefined, +): selection is VariableSelection { + return isAllSelection(selection) || (!!selection && selection.length > 0); +} + +/** + * Fill each "all" variable's values with its filter's options, sorted so query + * keys stay stable. A variable whose options aren't known yet keeps its empty + * values, so callers can wait for them. + */ +export function expandAllSelections( + variables: ChartVariable[], + optionsByVariableName: ReadonlyMap, +): ChartVariable[] { + return variables.map(variable => { + if (!variable.all) return variable; + const options = optionsByVariableName.get(variable.name); + return options ? { ...variable, values: [...options].sort() } : variable; + }); +} diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index 9abe461e7..6659589c4 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -513,6 +513,9 @@ function languageSettings(language: TemplateLanguage): LanguageSettings { const sqlNoOp = (name: string) => `(1=1 /** no values selected for variable '${name}' */)`; +const sqlAllNoOp = (name: string) => + `(1=1 /** all values selected for variable '${name}' */)`; + /** * The variable a macro's name argument refers to, or undefined when the argument * isn't a `$name` reference. @@ -630,6 +633,9 @@ function expandConditionalAllMacro( const variableName = requireVariableNameArg('conditionalAll', args); const variable = requireVariable(ctx, 'conditionalAll', variableName); + // Matches Grafana's $__conditionalAll, which drops the condition for "All". + // $__filter keeps the expanded values instead, as `col IN ($var)` does there. + if (variable.all) return sqlAllNoOp(variableName); if (variable.values.length === 0) return sqlNoOp(variableName); // The condition is already expanded by `expandTemplate`.