diff --git a/.changeset/source-variable-field-references.md b/.changeset/source-variable-field-references.md new file mode 100644 index 0000000000..37e21a988b --- /dev/null +++ b/.changeset/source-variable-field-references.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/app': minor +'@hyperdx/api': patch +--- + +feat: Add the sqlidentifier variable format and field references to data source and connection variables diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 273fb97e7f..9760e465c0 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -1297,6 +1297,7 @@ Only add one when the default is wrong. \${service:sqlstring} is redundant in a promql a or (a|b) "" or .* the default in PromQL; a single-select variable (maxSelections: 1) renders its raw value for {label="$var"}, a multi-select one an escaped regex for {label=~"$var"} csv a,b use INSIDE a string literal markdown a, b the default in markdown tiles; markdown syntax in values is escaped + sqlidentifier \`a\`, \`b c\` backtick-quotes each value, for a table, database, or column name BUILDER TILES diff --git a/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts b/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts index 31b91cbcc8..de7e0c368e 100644 --- a/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts +++ b/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts @@ -49,6 +49,7 @@ describe('buildSqlVariableCompletions', () => { '${service:csv}', '${service:regex}', '${service:lucene}', + '${service:sqlidentifier}', ]), ); }); diff --git a/packages/app/src/components/SQLEditor/variableCompletions.tsx b/packages/app/src/components/SQLEditor/variableCompletions.tsx index 10df934e5b..8cf6d4589f 100644 --- a/packages/app/src/components/SQLEditor/variableCompletions.tsx +++ b/packages/app/src/components/SQLEditor/variableCompletions.tsx @@ -26,6 +26,8 @@ const COMPLETION_FORMATS: Record< sqlstring: "Quoted and comma-separated, escaped for SQL. e.g. 'a', 'b', 'c'", csv: 'Comma-separated and unquoted. Not SQL-escaped. e.g. a,b,c', + sqlidentifier: + 'Comma-separated identifiers, each backtick-quoted. e.g. `a`, `b c`', regex: 'A regex alternation. Regex escaped. e.g. (a|b|c)', lucene: 'An OR of quoted terms, for Lucene inputs. e.g. ("a" OR "b" OR "c"). Quote the reference (field:"$var") for exact-match behavior. Leave unquoted (field:$var) for substring matching.', diff --git a/packages/app/tests/e2e/features/dashboard.spec.ts b/packages/app/tests/e2e/features/dashboard.spec.ts index 2d6d864d05..d86e41c51f 100644 --- a/packages/app/tests/e2e/features/dashboard.spec.ts +++ b/packages/app/tests/e2e/features/dashboard.spec.ts @@ -1945,13 +1945,14 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => { // entries the popup is empty the moment the brace is typed. await dashboardPage.chartEditor.replaceSqlQuery('${'); const options = dashboardPage.chartEditor.sqlCompletionOptions(); - await expect(options).toHaveCount(5); + await expect(options).toHaveCount(6); // Compared as a set: ranking between equally-good matches is // CodeMirror's business, not something worth pinning here. expect((await options.allTextContents()).sort()).toEqual( [ '${svc}', '${svc:sqlstring}', + '${svc:sqlidentifier}', '${svc:regex}', '${svc:csv}', '${svc:lucene}', diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index 300e037754..4ce6707304 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -4,6 +4,7 @@ import { getAdhocFilterTargetsForTile, getBlockingRequiredFilterNames, getBlockingRequiredFilters, + getFiltersDeclaringVariables, getUnsatisfiedRequiredFilters, parseDashboardFilterValues, resolveFilterSelection, @@ -22,6 +23,7 @@ import type { SavedChartConfig, StaticListDashboardFilter, } from '@/types'; +import { SourceKind } from '@/types'; const filter = ( overrides: Partial = {}, @@ -655,6 +657,30 @@ describe('dashboardFilterValues', () => { }); }); + describe('getFiltersDeclaringVariables', () => { + const dataSource: DashboardFilter = { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + const env = staticFilter(); + + it('matches value and data source variables by name', () => { + expect( + getFiltersDeclaringVariables([env, dataSource], ['logs', 'env']), + ).toEqual([env, dataSource]); + expect(getFiltersDeclaringVariables([env, dataSource], ['logs'])).toEqual( + [dataSource], + ); + }); + }); + describe('getBlockingRequiredFilters', () => { const names = ( filters: DashboardFilter[], @@ -704,6 +730,33 @@ describe('dashboardFilterValues', () => { expect(names(filters, { referencedVariableNames: [] })).toEqual([]); }); + it('blocks a tile whose text references a data source variable', () => { + const dataSource: DashboardFilter = { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + expect( + names([dataSource], { + referencedVariableNames: ['logs'], + consumesBroadcastFilters: false, + }), + ).toEqual(['Logs source']); + expect( + names([dataSource], { + referencedVariableNames: [], + consumesBroadcastFilters: false, + }), + ).toEqual([]); + }); + // A filter with no explicit variableName is still referenced by the token // derived from its display name. it('matches a filter by its derived variable name', () => { diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index 849b27736d..08f5b97007 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -37,6 +37,7 @@ import { validateSavedQuery, validateVariableName, } from '@/filters'; +import { buildReferenceChartVariables } from '@/referenceVariables'; import type { AdhocDashboardFilter, AdhocFilterCondition, @@ -53,6 +54,7 @@ import type { import { DASHBOARD_VARIABLE_NAME_MAX_LENGTH, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, + SourceKind, } from '@/types'; import { isFilterSingleSelect } from '@/variables'; @@ -1436,6 +1438,39 @@ describe('filters', () => { ).toEqual(['svc']); }); + it('reports a data source variable only until it selects a source', () => { + const where = 'ServiceName IN (SELECT s FROM $src)'; + const src = (selected: boolean) => + buildReferenceChartVariables( + [ + { + type: 'DATA_SOURCE', + name: 'Source', + variableName: 'src', + allowedSourceKinds: [SourceKind.Log], + }, + ], + { + values: new Map([['src', selected ? 'logs' : undefined]]), + sources: [ + { + id: 'logs', + name: 'Logs', + kind: SourceKind.Log, + from: { databaseName: 'default', tableName: 'logs' }, + }, + ], + }, + )[0]; + + expect(getPendingFilterValuesVariables({ where }, [src(false)])).toEqual([ + 'src', + ]); + expect(getPendingFilterValuesVariables({ where }, [src(true)])).toEqual( + [], + ); + }); + it('reports a braced reference once, however often it appears', () => { expect( getPendingFilterValuesVariables( diff --git a/packages/common-utils/src/__tests__/variableReferenceFields.test.ts b/packages/common-utils/src/__tests__/variableReferenceFields.test.ts new file mode 100644 index 0000000000..b99f611141 --- /dev/null +++ b/packages/common-utils/src/__tests__/variableReferenceFields.test.ts @@ -0,0 +1,530 @@ +import { + MacroExpansionError, + VariableFieldReferenceError, +} from '@/macroErrors'; +import { + buildReferenceChartVariables, + getEmptyDashboardVariables, + ReferenceVariableSource, +} from '@/referenceVariables'; +import { + ChartVariable, + DashboardFilter, + MetricsDataType, + MetricTable, + SourceKind, +} from '@/types'; +import { + formatVariableValues, + getReferenceFieldReferences, + getVariableReferences, + substituteVariables, + TemplateLanguage, + validateVariableReferencesInTemplate, +} from '@/variables'; + +const referenceFilterFields = { + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, +} as const; + +const sourceFilter = ( + variableName: string, + allowedSourceKinds: SourceKind[], +): DashboardFilter => ({ + ...referenceFilterFields, + id: `${variableName}-filter`, + type: 'DATA_SOURCE', + name: variableName, + variableName, + allowedSourceKinds, +}); + +const connectionFilter = (variableName: string): DashboardFilter => ({ + ...referenceFilterFields, + id: `${variableName}-filter`, + type: 'CONNECTION', + name: variableName, + variableName, +}); + +/** A data source variable selecting `source`, or nothing when it is undefined. */ +const sourceVariable = ( + variableName: string, + source: Omit | undefined, + allowedSourceKinds: SourceKind[] = [SourceKind.Log], +): ChartVariable => { + const [variable] = buildReferenceChartVariables( + [sourceFilter(variableName, allowedSourceKinds)], + { + values: new Map([[variableName, source && 'selected']]), + sources: source ? [{ id: 'selected', ...source }] : [], + }, + ); + return variable; +}; + +const connectionVariable = ( + variableName: string, + connectionName: string | undefined, +): ChartVariable => { + const [variable] = buildReferenceChartVariables( + [connectionFilter(variableName)], + { + values: new Map([[variableName, connectionName && 'selected']]), + connections: connectionName + ? [{ id: 'selected', name: connectionName }] + : [], + }, + ); + return variable; +}; + +const LOGS_SOURCE = { + name: 'My Logs', + kind: SourceKind.Log, + from: { databaseName: 'default', tableName: 'otel_logs' }, +}; + +const LOGS = sourceVariable('src', LOGS_SOURCE); +const UNSELECTED_SOURCE = sourceVariable('src', undefined); +const ODD_NAMES = sourceVariable('src', { + name: 'Odd', + kind: SourceKind.Log, + from: { databaseName: 'my-db', tableName: 'logs v2' }, +}); + +const NO_METRIC_TABLES: MetricTable = { + [MetricsDataType.Gauge]: '', + [MetricsDataType.Histogram]: '', + [MetricsDataType.Sum]: '', + [MetricsDataType.Summary]: '', + [MetricsDataType.ExponentialHistogram]: '', +}; + +const metricVariable = ( + metricTables: Partial, + allowedSourceKinds: SourceKind[] = [SourceKind.Metric], +) => + sourceVariable( + 'm', + { + name: 'Metrics', + kind: SourceKind.Metric, + from: { databaseName: 'default', tableName: '' }, + metricTables: { ...NO_METRIC_TABLES, ...metricTables }, + }, + allowedSourceKinds, + ); + +const ONE_TABLE_METRICS = metricVariable({ + [MetricsDataType.Gauge]: 'otel_metrics_gauge', +}); +const MANY_TABLE_METRICS = metricVariable({ + [MetricsDataType.Gauge]: 'otel_metrics_gauge', + [MetricsDataType.Sum]: 'otel_metrics_sum', + [MetricsDataType.ExponentialHistogram]: 'otel_metrics_exp', +}); + +const CONNECTION = connectionVariable('conn', 'Prod'); + +const SERVICE: ChartVariable = { name: 'svc', values: ['api', 'web'] }; + +const expand = ( + input: string, + variables: ChartVariable[], + inputLanguage: TemplateLanguage = 'sql', +) => substituteVariables(input, { variables, inputLanguage }); + +describe('sqlidentifier format', () => { + it('backtick-quotes every value', () => { + expect( + formatVariableValues({ values: ['a', 'limit', 'b c'] }, 'sqlidentifier'), + ).toBe('`a`, `limit`, `b c`'); + }); + + it('escapes backticks and backslashes, taking the value literally', () => { + expect( + formatVariableValues({ values: ['d`e', '`a b`'] }, 'sqlidentifier'), + ).toBe('`d\\`e`, `\\`a b\\``'); + }); + + it('keeps a value that tries to close the identifier inside it', () => { + const injected: ChartVariable = { + name: 'svc', + values: ['a\\`) OR 1=1 --'], + }; + expect(expand('WHERE ${svc:sqlidentifier} = 1', [injected])).toBe( + 'WHERE `a\\\\\\`) OR 1=1 --` = 1', + ); + }); + + it('renders nothing for an empty selection', () => { + expect(formatVariableValues({ values: [] }, 'sqlidentifier')).toBe(''); + }); + + it('applies to a value variable', () => { + expect(expand('SELECT ${svc:sqlidentifier}', [SERVICE])).toBe( + 'SELECT `api`, `web`', + ); + }); +}); + +describe('data source variable references', () => { + it.each([ + ['$src', '`default`.`otel_logs`'], + ['${src}', '`default`.`otel_logs`'], + ['${src.table}', '`otel_logs`'], + ['${src.database}', '`default`'], + ['${src.name}', "'My Logs'"], + ['${src.id}', "'selected'"], + ])('expands %s in SQL as %s', (reference, expected) => { + expect(expand(`SELECT * FROM ${reference}`, [LOGS])).toBe( + `SELECT * FROM ${expected}`, + ); + }); + + it('quotes each segment separately', () => { + expect(expand('FROM $src', [ODD_NAMES])).toBe('FROM `my-db`.`logs v2`'); + expect(expand('FROM ${src.table}', [ODD_NAMES])).toBe('FROM `logs v2`'); + }); + + it('escapes a backslash ending a table name', () => { + const trailingBackslash = sourceVariable('src', { + name: 'Odd', + kind: SourceKind.Log, + from: { databaseName: 'd', tableName: 't\\' }, + }); + expect(expand('FROM $src', [trailingBackslash])).toBe('FROM `d`.`t\\\\`'); + }); + + it('applies a requested format to the field', () => { + expect(expand('WHERE t = ${src.table:sqlstring}', [LOGS])).toBe( + "WHERE t = 'otel_logs'", + ); + expect(expand("WHERE n = '${src.name:csv}'", [LOGS])).toBe( + "WHERE n = 'My Logs'", + ); + expect(expand('${src:csv}', [LOGS])).toBe('default.otel_logs'); + expect(expand('SELECT ${src.name:sqlidentifier}', [LOGS])).toBe( + 'SELECT `My Logs`', + ); + }); + + it('renders the name as plain text in markdown', () => { + expect(expand('# ${src.name}', [LOGS], 'markdown')).toBe('# My Logs'); + expect(expand('Table: $src', [LOGS], 'markdown')).toBe( + 'Table: default\\.otel\\_logs', + ); + }); + + it('renders nothing while unselected', () => { + expect(expand('FROM $src', [UNSELECTED_SOURCE])).toBe('FROM '); + expect(expand('${src.name}', [UNSELECTED_SOURCE], 'markdown')).toBe(''); + }); + + it('renders nothing when the selection is not a known source', () => { + const [variable] = buildReferenceChartVariables( + [sourceFilter('src', [SourceKind.Log])], + { + values: new Map([['src', 'missing']]), + sources: [{ id: 'other', ...LOGS_SOURCE }], + }, + ); + expect(expand('FROM $src', [variable])).toBe('FROM '); + }); + + it('still rejects an unknown field while unselected', () => { + expect(() => expand('${src.nope}', [UNSELECTED_SOURCE])).toThrow( + VariableFieldReferenceError, + ); + }); + + it('rejects an unknown field, listing the fields it has', () => { + expect(() => expand('${src.columns}', [LOGS])).toThrow( + "'${src.columns}' reads a field $src doesn't have. Expected one of: " + + '$src, ${src.table}, ${src.database}, ${src.name}, ${src.id}.', + ); + expect(() => expand('${src.name.first}', [LOGS])).toThrow( + VariableFieldReferenceError, + ); + }); + + it('leaves a field on an unknown variable as written', () => { + expect(expand('SELECT ${other.table}', [LOGS])).toBe( + 'SELECT ${other.table}', + ); + }); + + it('expands an exact match in lucene', () => { + expect(expand('SourceName:"${src.name}"', [LOGS], 'lucene')).toBe( + '(SourceName:"My Logs")', + ); + }); + + it('matches everything in lucene while unselected', () => { + expect( + expand('SourceName:"${src.name}"', [UNSELECTED_SOURCE], 'lucene'), + ).toBe('SourceName:("")'); + }); + + it('escapes the name for the promql string it sits in', () => { + const quoted = sourceVariable('src', { + name: 'a"b', + kind: SourceKind.Log, + from: { databaseName: 'd', tableName: 't' }, + }); + expect(expand('up{source="${src.name}"}', [quoted], 'promql')).toBe( + 'up{source="a\\"b"}', + ); + }); + + describe('metric sources', () => { + it('has no bare or table field on a variable that allows only metric sources', () => { + const unselected = sourceVariable('m', undefined, [SourceKind.Metric]); + for (const variable of [unselected, ONE_TABLE_METRICS]) { + expect(() => expand('FROM $m', [variable])).toThrow( + "'$m' reads a field $m doesn't have.", + ); + expect(() => expand('FROM ${m.table}', [variable])).toThrow( + "'${m.table}' reads a field $m doesn't have.", + ); + } + }); + + it('requires the table to be named even when only one is configured', () => { + const mixed = metricVariable( + { [MetricsDataType.Gauge]: 'otel_metrics_gauge' }, + [SourceKind.Log, SourceKind.Metric], + ); + const message = + "can't render for the selected data source. Use one of: ${m.table.gauge}, ${m.database}, ${m.name}, ${m.id}."; + expect(() => expand('FROM $m', [mixed])).toThrow(`'$m' ${message}`); + expect(() => expand('FROM ${m.table}', [mixed])).toThrow( + `'\${m.table}' ${message}`, + ); + }); + + it('renders no table for a metric source with no tables configured', () => { + const mixed = metricVariable({}, [SourceKind.Log, SourceKind.Metric]); + expect(() => expand('FROM $m', [mixed])).toThrow( + "'$m' can't render for the selected data source.", + ); + }); + + it('picks a named table', () => { + expect(expand('FROM ${m.table.sum}', [MANY_TABLE_METRICS])).toBe( + 'FROM `otel_metrics_sum`', + ); + expect( + expand('FROM ${m.table.exponential_histogram}', [MANY_TABLE_METRICS]), + ).toBe('FROM `otel_metrics_exp`'); + }); + + it('rejects a table the source does not configure, listing the fields that render', () => { + expect(() => + expand('FROM ${m.table.histogram}', [ONE_TABLE_METRICS]), + ).toThrow( + "'${m.table.histogram}' can't render for the selected data source. Use one of: " + + '${m.table.gauge}, ${m.database}, ${m.name}, ${m.id}.', + ); + }); + + it('rejects a metric table on a selected non-metric source', () => { + const mixed = sourceVariable('src', LOGS_SOURCE, [ + SourceKind.Log, + SourceKind.Metric, + ]); + expect(() => expand('FROM ${src.table.gauge}', [mixed])).toThrow( + "'${src.table.gauge}' can't render for the selected data source.", + ); + }); + + it('has no metric table fields on a variable that allows no metric source', () => { + expect(() => expand('FROM ${src.table.gauge}', [LOGS])).toThrow( + "'${src.table.gauge}' reads a field $src doesn't have.", + ); + }); + }); +}); + +describe('connection variable references', () => { + it('expands to the connection name', () => { + expect(expand('$conn', [CONNECTION])).toBe("'Prod'"); + expect(expand('${conn.name}', [CONNECTION], 'markdown')).toBe('Prod'); + }); + + it('expands the connection id', () => { + expect(expand('${conn.id}', [CONNECTION])).toBe("'selected'"); + }); + + it('renders nothing while unselected', () => { + expect(expand('$conn', [connectionVariable('conn', undefined)])).toBe(''); + }); + + it('rejects a field a connection does not have', () => { + expect(() => expand('${conn.table}', [CONNECTION])).toThrow( + "'${conn.table}' reads a field $conn doesn't have. Expected one of: $conn, ${conn.name}, ${conn.id}.", + ); + }); +}); + +describe('fields on a value variable', () => { + it('are rejected', () => { + expect(() => expand('${svc.table}', [SERVICE])).toThrow( + VariableFieldReferenceError, + ); + }); +}); + +describe('variable macros on a reference variable', () => { + it.each(['$__filter(SourceName, $src)', '$__conditionalAll(1 = 1, $src)'])( + 'reject %s', + template => { + expect(() => expand(template, [LOGS])).toThrow(MacroExpansionError); + }, + ); +}); + +describe('getReferenceFieldReferences', () => { + const references = (variable: ChartVariable) => + variable.reference + ? getReferenceFieldReferences(variable.name, variable.reference).map( + ({ reference }) => reference, + ) + : []; + + it('offers every field while nothing is selected', () => { + expect( + references( + sourceVariable('m', undefined, [SourceKind.Log, SourceKind.Metric]), + ), + ).toContain('${m.table.summary}'); + }); + + it('offers only the fields the selection renders', () => { + expect(references(MANY_TABLE_METRICS)).toEqual([ + '${m.table.gauge}', + '${m.table.sum}', + '${m.table.exponential_histogram}', + '${m.database}', + '${m.name}', + '${m.id}', + ]); + }); +}); + +describe('getVariableReferences', () => { + it('reports the field path', () => { + expect(getVariableReferences('${src.table.gauge:sqlidentifier}')).toEqual([ + expect.objectContaining({ + name: 'src', + path: ['table', 'gauge'], + format: 'sqlidentifier', + }), + ]); + }); +}); + +describe('validateVariableReferencesInTemplate with reference variables', () => { + const validate = (template: string, language: TemplateLanguage = 'sql') => + validateVariableReferencesInTemplate(template, [LOGS, CONNECTION], { + language, + }); + + it('accepts a valid reference without the value-variable warnings', () => { + expect(validate('SELECT * FROM $src WHERE x = ${src.name}')).toEqual({ + errors: [], + warnings: [], + }); + }); + + it('reports an unknown field', () => { + expect(validate('SELECT ${src.columns}').errors).toEqual([ + expect.stringContaining( + "'${src.columns}' reads a field $src doesn't have", + ), + ]); + }); + + it('reports a quoted name', () => { + expect(validate("WHERE n = '${src.name}'").errors).toEqual([ + '${src.name} is wrapped in quotes, but the sqlstring format already quotes the value. Remove the quotes, or use ${src.name:csv} inside them.', + ]); + }); + + it.each([ + ["WHERE t = '${src.table}'", '${src.table}', '${src.table:csv}'], + ["WHERE t = '$src'", '$src', '${src:csv}'], + ["WHERE s = '${svc:sqlidentifier}'", '${svc:sqlidentifier}', '${svc:csv}'], + ])('reports a quoted identifier in %s', (template, reference, suggestion) => { + expect( + validateVariableReferencesInTemplate(template, [LOGS, SERVICE], { + language: 'sql', + }).errors, + ).toEqual([ + `${reference} is wrapped in quotes, but the sqlidentifier format renders a backtick-quoted identifier. Remove the quotes, or use ${suggestion} inside them.`, + ]); + }); + + it('accepts a quoted identifier field in the csv format', () => { + expect(validate("WHERE t = '${src.table:csv}'").errors).toEqual([]); + }); + + it('reports a quoted name while unselected', () => { + expect( + validateVariableReferencesInTemplate("WHERE n = '${src.name}'", [ + UNSELECTED_SOURCE, + ]).errors, + ).toHaveLength(1); + }); + + it('reports an unknown field in markdown', () => { + expect(validate('${conn.database}', 'markdown').errors).toEqual([ + expect.stringContaining( + "'${conn.database}' reads a field $conn doesn't have", + ), + ]); + }); + + it('reports a field on a value variable', () => { + expect( + validateVariableReferencesInTemplate('SELECT ${svc.table}', [SERVICE]) + .errors, + ).toEqual([ + "'${svc.table}' reads a field, but $svc is not a data source or connection variable, so it has none.", + ]); + }); + + it('reports a metric source reference that names no table', () => { + expect( + validateVariableReferencesInTemplate('FROM $m', [ONE_TABLE_METRICS]) + .errors, + ).toEqual([expect.stringContaining("'$m' reads a field $m doesn't have")]); + }); + + it('reports a metric-only reference that names no table while unselected', () => { + expect( + validateVariableReferencesInTemplate('FROM ${m.table}', [ + sourceVariable('m', undefined, [SourceKind.Metric]), + ]).errors, + ).toEqual([ + expect.stringContaining("'${m.table}' reads a field $m doesn't have"), + ]); + }); +}); + +describe('getEmptyDashboardVariables', () => { + it('includes the reference variables, unselected', () => { + const variables = getEmptyDashboardVariables([ + sourceFilter('src', [SourceKind.Log]), + connectionFilter('conn'), + ]); + expect(variables.map(variable => variable.name)).toEqual(['src', 'conn']); + expect(expand('FROM $src WHERE c = $conn', variables)).toBe( + 'FROM WHERE c = ', + ); + }); +}); diff --git a/packages/common-utils/src/__tests__/variables.test.ts b/packages/common-utils/src/__tests__/variables.test.ts index 6451859658..7d9a801aec 100644 --- a/packages/common-utils/src/__tests__/variables.test.ts +++ b/packages/common-utils/src/__tests__/variables.test.ts @@ -2175,7 +2175,7 @@ describe('validateVariableReferencesInTemplate', () => { it('warns about an unknown format', () => { expect(markdown('${service:nope}', [SERVICE]).warnings).toEqual([ '${service:nope} uses an unknown format, so no variables are substituted. ' + - 'Expected one of: sqlstring, regex, csv, lucene, markdown, promql, url.', + 'Expected one of: sqlstring, sqlidentifier, regex, csv, lucene, markdown, promql, url.', ]); }); diff --git a/packages/common-utils/src/dashboardFilterValues.ts b/packages/common-utils/src/dashboardFilterValues.ts index a0e7922d12..e868431d64 100644 --- a/packages/common-utils/src/dashboardFilterValues.ts +++ b/packages/common-utils/src/dashboardFilterValues.ts @@ -262,6 +262,26 @@ export function getAdhocFilterTargetsForTile( ); } +/** + * The filters that declare a variable named in `names`: value variables, and + * data source and connection variables, whether a field or text references them. + */ +export function getFiltersDeclaringVariables( + filters: T[], + names: Iterable, +): T[] { + const named = new Set(names); + const declaring = new Set( + [ + ...getDashboardVariableFilters(filters), + ...getReferenceVariableFilters(filters), + ] + .filter(({ name }) => named.has(name)) + .map(({ filter }) => filter), + ); + return filters.filter(filter => declaring.has(filter)); +} + /** * The subset of `unsatisfiedRequiredFilters` that blocks the given tile. * @@ -284,24 +304,17 @@ export function getBlockingRequiredFilters( referenceVariableNames?: readonly string[]; }, ): DashboardFilter[] { - const referenceVariableNames = new Set(tile.referenceVariableNames ?? []); - const referenceVariableFilterIds = new Set( - getReferenceVariableFilters(unsatisfiedRequiredFilters) - .filter(({ name }) => referenceVariableNames.has(name)) - .map(({ filter }) => filter.id), - ); - const referencedNamesSet = new Set(tile.referencedVariableNames ?? []); - const referencedFilterIds = new Set( - getDashboardVariableFilters(unsatisfiedRequiredFilters) - .filter(({ name }) => referencedNamesSet.has(name)) - .map(({ filter }) => filter.id), + const referencedFilters = new Set( + getFiltersDeclaringVariables(unsatisfiedRequiredFilters, [ + ...(tile.referencedVariableNames ?? []), + ...(tile.referenceVariableNames ?? []), + ]), ); return unsatisfiedRequiredFilters.filter( filter => isFilterGlobalRequirement(filter) || - referencedFilterIds.has(filter.id) || - referenceVariableFilterIds.has(filter.id) || + referencedFilters.has(filter) || (tile.consumesBroadcastFilters && doesFilterApplyToSource(filter, tile.sourceId)), ); diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index d443fd303b..c5f26af1d6 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -36,6 +36,7 @@ import { escapePromqlStringValue, formatVariableValues, getVariableReferences, + hasSelection, substituteVariables, } from '@/variables'; @@ -1170,8 +1171,8 @@ export function isReferenceVariableFilterType( /** Type guard for reference variable filters; see `isReferenceVariableFilterType`. */ export function isReferenceVariableFilter< - T extends { type: DashboardFilterKind }, ->(filter: T): filter is Extract { + T extends { type?: DashboardFilterKind }, +>(filter: T): filter is T & { type: 'DATA_SOURCE' | 'CONNECTION' } { return isReferenceVariableFilterType(filter.type); } @@ -1494,9 +1495,11 @@ export type FilterForVariableDeclaration = { /** * The variable-enabled filters a dashboard declares, paired with the name each - * one answers to, in filter order. Data source variables are left out: their - * value selects a tile's source or connection and is never substituted into - * query text. + * one answers to, in filter order. Data source and connection variables are + * left out: their selection is an ID that text references read fields of, not + * values to render, so they are built separately by + * `buildReferenceChartVariables`. To match a filter by name across both, use + * `getFiltersDeclaringVariables`. */ export function getDashboardVariableFilters< T extends FilterForVariableDeclaration, @@ -1637,7 +1640,7 @@ export function getPendingFilterValuesVariables( if (variables == null || !where.trim() || whereLanguage !== 'sql') return []; const emptyVariableNames = new Set( - variables.filter(v => v.values.length === 0).map(v => v.name), + variables.filter(v => !hasSelection(v)).map(v => v.name), ); if (emptyVariableNames.size === 0) return []; diff --git a/packages/common-utils/src/macroErrors.ts b/packages/common-utils/src/macroErrors.ts index 302806cd55..7eef6e2539 100644 --- a/packages/common-utils/src/macroErrors.ts +++ b/packages/common-utils/src/macroErrors.ts @@ -20,6 +20,20 @@ export class MacroExpansionError extends Error { } } +/** + * Thrown when a field reference like `${src.table}` can't render because it + * references a field the variable doesn't have. + */ +export class VariableFieldReferenceError extends Error { + constructor( + public readonly variableName: string, + message: string, + ) { + super(message); + this.name = 'VariableFieldReferenceError'; + } +} + /** * Thrown during expansion when `$__filter` / `$__conditionalAll` names a * variable that the context does not declare. diff --git a/packages/common-utils/src/referenceVariables.ts b/packages/common-utils/src/referenceVariables.ts index d59405ad4a..5ad0945d7e 100644 --- a/packages/common-utils/src/referenceVariables.ts +++ b/packages/common-utils/src/referenceVariables.ts @@ -1,7 +1,9 @@ import { castArray, isString, uniq } from 'lodash'; import { + FilterForVariableDeclaration, getAdhocFilterSourceKinds, + getDashboardVariableDeclarations, isConnectionFilter, isDataSourceFilter, isReferenceVariableFilter, @@ -10,12 +12,17 @@ import { SQL_QUERY_FILTER_SOURCE_KINDS, } from '@/filters'; import { + ChartReferenceField, + ChartVariable, ConnectionDashboardFilter, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, DashboardFilter, DataSourceDashboardFilter, + MetricsDataType, NON_PROMQL_SOURCE_KINDS, SourceKind, + TMetricSource, + TSource, } from '@/types'; /** @@ -58,6 +65,152 @@ export function getObjectName( /** Selected ID per reference variable name; undefined when unselected. */ export type ReferenceVariableValues = ReadonlyMap; +/** The parts of a source that text references to a data source variable read. */ +export type ReferenceVariableSource = Pick< + TSource, + 'id' | 'name' | 'from' | 'kind' +> & + Partial>; + +/** What text references to a connection variable read from its selected connection. */ +export type ReferenceVariableConnection = { id: string; name: string }; + +/** A filter that may declare a reference variable, and the source kinds it allows. */ +export type ReferenceVariableFilter = FilterForVariableDeclaration & { + allowedSourceKinds?: SourceKind[]; +}; + +/** The `${src.table.}` field naming each metric table. */ +const METRIC_TABLE_FIELDS = Object.values(MetricsDataType).map( + type => [type.replace(/ /g, '_'), type] as const, +); + +const identifierField = (parts: string[] | undefined): ChartReferenceField => ({ + type: 'identifier', + parts, +}); + +/** + * The fields of a data source variable. Metric table fields are declared when + * the variable can select a metric source. A metric source never renders + * `$src` or `${src.table}`: picking its only table would silently change what + * a tile queries once the source gains another, so the table must be named. + * A variable that can only select metric sources doesn't declare them at all. + */ +function getSourceFields( + source: ReferenceVariableSource | undefined, + allowedSourceKinds: readonly SourceKind[], +): Record { + const allowsMetricSources = allowedSourceKinds.includes(SourceKind.Metric); + const allowsOnlyMetricSources = + allowsMetricSources && + allowedSourceKinds.every(kind => kind === SourceKind.Metric); + const metricTables = new Map(Object.entries(source?.metricTables ?? {})); + const table = + source?.kind === SourceKind.Metric ? undefined : source?.from.tableName; + const database = source?.from.databaseName; + + return Object.fromEntries([ + ...(allowsOnlyMetricSources + ? [] + : [ + [ + '', + identifierField( + database != null && table != null ? [database, table] : undefined, + ), + ], + ['table', identifierField(table != null ? [table] : undefined)], + ]), + ...(allowsMetricSources + ? METRIC_TABLE_FIELDS.map(([field, type]) => { + const metricTable = metricTables.get(type); + return [ + `table.${field}`, + identifierField(metricTable ? [metricTable] : undefined), + ]; + }) + : []), + ['database', identifierField(database != null ? [database] : undefined)], + ['name', { type: 'text', text: source?.name }], + ['id', { type: 'text', text: source?.id }], + ]); +} + +function getConnectionFields( + connection: ReferenceVariableConnection | undefined, +): Record { + const name: ChartReferenceField = { type: 'text', text: connection?.name }; + return { + '': name, + name, + id: { type: 'text', text: connection?.id }, + }; +} + +/** + * The data source and connection variables a dashboard declares, as the + * variables text references (`$src`, `${src.table}`) expand against. A + * variable with no selection, or one selecting an ID not in `sources` / + * `connections`, is unselected and expands to nothing. + */ +export function buildReferenceChartVariables( + filters: ReferenceVariableFilter[] | undefined, + { + values, + sources, + connections, + }: { + values?: ReferenceVariableValues; + sources?: readonly ReferenceVariableSource[]; + connections?: readonly ReferenceVariableConnection[]; + } = {}, +): ChartVariable[] { + return getReferenceVariableFilters(filters).map( + ({ filter, name }): ChartVariable => { + const id = values?.get(name); + if (filter.type === 'CONNECTION') { + const connection = id ? connections?.find(c => c.id === id) : undefined; + return { + name, + values: [], + reference: { + noun: 'connection', + hasSelection: connection != null, + fields: getConnectionFields(connection), + }, + }; + } + const source = id ? sources?.find(s => s.id === id) : undefined; + return { + name, + values: [], + reference: { + noun: 'data source', + hasSelection: source != null, + fields: getSourceFields(source, filter.allowedSourceKinds ?? []), + }, + }; + }, + ); +} + +/** + * Every variable a dashboard declares, with nothing selected: how templates + * expand where no selection applies, such as alerts and saved-template checks. + */ +export function getEmptyDashboardVariables( + filters: ReferenceVariableFilter[] | undefined, +): ChartVariable[] { + return [ + ...getDashboardVariableDeclarations(filters).map(declaration => ({ + ...declaration, + values: [], + })), + ...buildReferenceChartVariables(filters), + ]; +} + /** A data source variable's identity, as offered by source pickers. */ export type SourceVariableDeclaration = { name: string; @@ -128,14 +281,14 @@ export function getConnectionVariableFilters( */ export function getReferenceVariableFilters< T extends { - type: DashboardFilter['type']; + type?: DashboardFilter['type']; name: string; variableName?: string; }, >( filters: T[] | undefined, ): { - filter: Extract; + filter: T & { type: 'DATA_SOURCE' | 'CONNECTION' }; name: string; }[] { return pairWithVariableNames( diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 961386a169..f7347605c3 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1956,15 +1956,56 @@ export const _ChartConfigSchema = SharedChartSettingsSchema.extend({ groupByColumnsOnLeft: z.boolean().optional(), }); +/** + * One field a reference variable can be read by, as in `${src.table}`. Its + * value is set once the variable selects something that has it. + */ +export const ChartReferenceFieldSchema = z.discriminatedUnion('type', [ + z.object({ + /** A name rendered as an identifier, qualified by its parts (`db.table`). */ + type: z.literal('identifier'), + parts: z.array(z.string()).optional(), + }), + z.object({ + type: z.literal('text'), + text: z.string().optional(), + }), +]); + +export type ChartReferenceField = z.infer; + +/** What a data source or connection variable selects, as text references read it. */ +export const ChartReferenceVariableSchema = z.object({ + /** What the variable selects, for messages, e.g. `data source`. */ + noun: z.string(), + /** + * Whether the selection resolved to a known source or connection. Without + * one every field renders nothing; with one, a field it lacks is an error. + */ + hasSelection: z.boolean(), + /** + * Every field the variable can be read by, whether or not anything is + * selected, keyed by its path: `table.gauge` for `${src.table.gauge}`, and + * the empty string for the bare `$src`. + */ + fields: z.record(z.string(), ChartReferenceFieldSchema), +}); + +export type ChartReferenceVariable = z.infer< + typeof ChartReferenceVariableSchema +>; + /** A dashboard variable as seen by a tile's query. */ export const ChartVariableSchema = z.object({ name: z.string(), /** The filter's target expression; enables the 1-arg `$__filter($name)` form. */ expression: z.string().optional(), - /** Empty means nothing is selected. */ + /** Empty means nothing is selected. Always empty for a reference variable. */ values: z.array(z.string()), /** The filter's selection cap; 1 means the variable is single-select. */ maxSelections: z.number().optional(), + /** Set for a variable that supports ${var.field} references. */ + reference: ChartReferenceVariableSchema.optional(), }); export type ChartVariable = z.infer; diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index 001752c4bd..d03d4c45ea 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -1,4 +1,5 @@ import lucene from '@hyperdx/lucene'; +import { partition } from 'lodash'; import { getPromqlSeries } from './core/promql'; import { @@ -10,6 +11,7 @@ import { MacroExpansionError, MalformedMacroArgsError, UnknownVariableError, + VariableFieldReferenceError, } from './macroErrors'; import { decodeSpecialTokensToSource, @@ -18,6 +20,8 @@ import { } from './queryParser'; import { ChartConfigWithOptDateRange, + ChartReferenceField, + ChartReferenceVariable, ChartVariable, DASHBOARD_VARIABLE_NAME_PATTERN, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, @@ -32,6 +36,7 @@ import { /** Rendering formats a reference can request via `${name:format}`. */ export const VARIABLE_FORMATS = [ 'sqlstring', + 'sqlidentifier', 'regex', 'csv', 'lucene', @@ -49,6 +54,16 @@ export function isFilterSingleSelect( return 'maxSelections' in filter && filter.maxSelections === 1; } +/** + * Whether a variable has a selection: a value for a value variable, a source + * or connection for a data source or connection variable. + */ +export function hasSelection(variable: ChartVariable): boolean { + return variable.reference + ? variable.reference.hasSelection + : variable.values.length > 0; +} + const isVariableFormat = (format: string): format is VariableFormat => (VARIABLE_FORMATS as readonly string[]).includes(format); @@ -56,6 +71,14 @@ const isVariableFormat = (format: string): format is VariableFormat => const isStringLiteralFormat = (format: string | undefined) => format === 'regex' || format === 'promql'; +/** + * Backtick-quote a value as a ClickHouse identifier, taken literally. ClickHouse + * reads a backslash as an escape inside backticks, so it is escaped along with + * the backtick; otherwise a value ending in `\` could close the identifier early. + */ +const quoteSqlIdentifier = (value: string) => + `\`${value.replace(/\\/g, '\\\\').replace(/`/g, '\\`')}\``; + const escapeRegexValue = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); @@ -98,6 +121,9 @@ export function formatVariableValues( return values.length === 0 ? 'NULL' : values.map(value => `'${escapeSqlString(value)}'`).join(', '); + case 'sqlidentifier': + // Always quoted: a bare-looking value can still be a reserved word. + return values.map(quoteSqlIdentifier).join(', '); case 'regex': return formatRegexValues(values); case 'promql': @@ -145,6 +171,8 @@ export type TemplateToken = | { kind: 'braced'; name: string; + /** The fields after the name, as in `${src.table.gauge}`; empty for none. */ + path: string[]; format?: string; raw: string; inStringLiteral: boolean; @@ -163,11 +191,11 @@ const isVariableMacroName = (name: string): name is VariableMacroName => // eslint-disable-next-line security/detect-non-literal-regexp const BARE_NAME_REGEX = new RegExp(`^${DASHBOARD_VARIABLE_NAME_PATTERN}`); -// Pattern used for recognizing ${var} and ${var:format} references, and for extracting the name and format. +// Pattern used for recognizing ${var}, ${var.field} and ${var:format} references, and for extracting the name, field path and format. // (eslint ignored because DASHBOARD_VARIABLE_NAME_PATTERN is a shared constant, not user input) // eslint-disable-next-line security/detect-non-literal-regexp const BRACED_REFERENCE_REGEX = new RegExp( - `^(${DASHBOARD_VARIABLE_NAME_PATTERN})(?::([a-zA-Z][a-zA-Z0-9_]*))?$`, + `^(${DASHBOARD_VARIABLE_NAME_PATTERN})((?:\\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?::([a-zA-Z][a-zA-Z0-9_]*))?$`, ); /** @@ -237,7 +265,7 @@ export function findBalancedParens(input: string, start: number): number { * * At each `$` the scanner tries, in order: * 1. a known `$__` macro (longest match, requiring a non-word char after the name so `$__filter` never matches the prefix of `$__filters`), - * 2. a `${name}` / `${name:format}` reference, then a + * 2. a `${name}` / `${name.field}` / `${name:format}` reference, then a * 3. bare `$name` reference (maximal munch). Anything else is plain text, and an unknown `$__x` is emitted verbatim. * * `onMalformed` controls what happens when a macro's argument list has no @@ -367,7 +395,8 @@ export function scanTemplateTokens( tokens.push({ kind: 'braced', name: match[1], - format: match[2], + path: match[2] ? match[2].slice(1).split('.') : [], + format: match[3], raw: input.slice(i, closeIndex + 1), inStringLiteral, }); @@ -576,13 +605,24 @@ function requireVariableNameArg( ); } -/** Require that a variable with the given name exists in the context. Throws an error if not found. */ +/** + * Require that a value variable with the given name exists in the context. + * Throws an error if not found, or if it is a data source or connection + * variable, which has no values to filter on. + */ function requireVariable( ctx: VariableContext, macroName: VariableMacroName, variableName: string, ): ChartVariable { const variable = ctx.variables.find(v => v.name === variableName); + if (variable?.reference) { + throw new MacroExpansionError( + macroName, + `Macro '$__${macroName}' can't use $${variableName}, a ${variable.reference.noun} variable, ` + + `which selects no values. Reference it directly, as in $${variableName}.`, + ); + } if (!variable) { const available = ctx.variables.map(v => v.name); throw new UnknownVariableError( @@ -653,6 +693,123 @@ function expandConditionalAllMacro( return `(${args[0]})`; } +/** How a reference to a field is written: `$src` for the bare form, else `${src.field}`. */ +function formatFieldReference(name: string, key: string): string { + return key === '' ? `$${name}` : `\${${name}.${key}}`; +} + +/** The segments a field renders, joined by `.`; undefined while it has no value. */ +function getFieldSegments(field: ChartReferenceField): string[] | undefined { + if (field.type === 'identifier') return field.parts; + return field.text != null ? [field.text] : undefined; +} + +/** A reference to a data source or connection variable, paired with the field it reads. */ +type ParsedReference = { + reference: ChartReferenceVariable; + field: ChartReferenceField; +}; + +/** + * The field a reference reads; undefined for a value variable, which has + * none. Throws for a field the variable doesn't have, whether or not anything + * is selected. + */ +function parseReference( + variable: ChartVariable, + path: readonly string[], + raw: string, +): ParsedReference | undefined { + const { name, reference } = variable; + if (reference == null) { + if (path.length === 0) return undefined; + throw new VariableFieldReferenceError( + name, + `'${raw}' reads a field, but $${name} is not a data source or connection variable, so it has none.`, + ); + } + + const fields = new Map(Object.entries(reference.fields)); + const field = fields.get(path.join('.')); + if (field == null) { + throw new VariableFieldReferenceError( + name, + `'${raw}' reads a field $${name} doesn't have. Expected one of: ` + + `${Array.from(fields.keys(), key => formatFieldReference(name, key)).join(', ')}.`, + ); + } + return { reference, field }; +} + +/** + * The segments a parsed reference renders; undefined while nothing is + * selected. Throws when the selection doesn't have the field. + */ +function resolveReferenceSegments( + name: string, + { reference, field }: ParsedReference, + raw: string, +): string[] | undefined { + if (!reference.hasSelection) return undefined; + const segments = getFieldSegments(field); + if (segments) return segments; + + const available = Object.entries(reference.fields) + .filter(([, f]) => getFieldSegments(f) != null) + .map(([key]) => formatFieldReference(name, key)); + throw new VariableFieldReferenceError( + name, + `'${raw}' can't render for the selected ${reference.noun}. Use one of: ${available.join(', ')}.`, + ); +} + +/** + * The fields a data source or connection variable offers, and how each is + * referenced: every field while nothing is selected, else the fields the + * selection renders. `field` is empty for the bare `$name` form. + */ +export function getReferenceFieldReferences( + name: string, + reference: ChartReferenceVariable, +): { field: string; reference: string }[] { + return Object.entries(reference.fields) + .filter(([, field]) => !reference.hasSelection || getFieldSegments(field)) + .map(([key]) => ({ + field: key, + reference: formatFieldReference(name, key), + })); +} + +/** + * The format a value reference renders in: the requested one, else the + * language's default. In SQL a reference variable's identifier field renders + * as an identifier, and its text as a string. + */ +function getEffectiveFormat( + parsed: ParsedReference | undefined, + requestedFormat: VariableFormat | undefined, + language: TemplateLanguage, +): VariableFormat { + if (requestedFormat != null) return requestedFormat; + if (parsed && language === 'sql') { + return parsed.field.type === 'text' ? 'sqlstring' : 'sqlidentifier'; + } + return languageSettings(language).defaultFormat; +} + +/** Render a reference's segments, joined by `.`, as one value in `format`. */ +function formatReferenceSegments( + segments: string[], + format: VariableFormat, +): string { + return format === 'sqlidentifier' + ? segments.map(quoteSqlIdentifier).join('.') + : formatVariableValues( + { values: [segments.join('.')], maxSelections: 1 }, + format, + ); +} + /** * Expand one non-text token against a variable context. A macro token's * arguments must already be expanded, so call this through `expandTemplate`. @@ -682,10 +839,23 @@ export function expandVariableToken( ); } - const settings = languageSettings(ctx.inputLanguage); - const format = requestedFormat ?? settings.defaultFormat; - const rendered = formatVariableValues(variable, format); + const parsed = parseReference( + variable, + token.kind === 'braced' ? token.path : [], + token.raw, + ); + const format = getEffectiveFormat(parsed, requestedFormat, ctx.inputLanguage); + let rendered: string; + if (parsed == null) { + rendered = formatVariableValues(variable, format); + } else { + const segments = resolveReferenceSegments(variable.name, parsed, token.raw); + if (segments == null) return ''; + rendered = formatReferenceSegments(segments, format); + } + + const settings = languageSettings(ctx.inputLanguage); return isStringLiteralFormat(format) && settings.escapeForStringLiteral ? settings.escapeForStringLiteral(rendered) : rendered; @@ -735,7 +905,16 @@ function getLuceneFormattedValues( const settings = languageSettings(ctx.inputLanguage); if ((requestedFormat ?? settings.defaultFormat) !== 'lucene') return undefined; - return ctx.variables.find(variable => variable.name === token.name)?.values; + const variable = ctx.variables.find(v => v.name === token.name); + if (!variable) return undefined; + const parsed = parseReference( + variable, + token.kind === 'braced' ? token.path : [], + token.raw, + ); + if (parsed == null) return variable.values; + const segments = resolveReferenceSegments(variable.name, parsed, token.raw); + return segments ? [segments.join('.')] : []; } /** @@ -1094,6 +1273,8 @@ export type VariableReference = { kind: 'macro' | 'bare' | 'braced'; /** The requested format, only ever set for `${name:format}`. */ format?: string; + /** The fields read, as in `${src.table}`; unset for none. */ + path?: string[]; /** Whether the reference sits inside a single- or double-quoted string. */ inStringLiteral: boolean; /** @@ -1151,6 +1332,10 @@ export function getVariableReferences( name: token.name, kind: token.kind, format: token.kind === 'braced' ? token.format : undefined, + path: + token.kind === 'braced' && token.path.length > 0 + ? token.path + : undefined, inStringLiteral: token.inStringLiteral, guardedBy, raw: token.raw, @@ -1319,18 +1504,37 @@ export function validateVariableReferencesInTemplate( } // An unrecognized format throws during expansion, so it is already reported. - const resolved = valueReferences.filter( - r => - knownVariableNames.has(r.name) && - (r.format == null || isVariableFormat(r.format)), + const variableByName = new Map(variables.map(v => [v.name, v])); + // Expansion is only attempted above for macros, so field errors are found + // here. A reference with a field error is left out of the checks below. + const fieldErrors = new Set(); + const resolved = valueReferences.flatMap(r => { + const variable = variableByName.get(r.name); + const { format } = r; + if (variable == null || (format != null && !isVariableFormat(format))) + return []; + try { + const parsed = parseReference(variable, r.path ?? [], r.raw); + if (parsed) resolveReferenceSegments(variable.name, parsed, r.raw); + const effectiveFormat = getEffectiveFormat(parsed, format, language); + return [{ ...r, variable, effectiveFormat }]; + } catch (e) { + if (!(e instanceof VariableFieldReferenceError)) throw e; + fieldErrors.add(e.message); + return []; + } + }); + errors.push(...fieldErrors); + + const [referenceRefs, valueVariableRefs] = partition( + resolved, + r => r.variable.reference != null, ); - // The two checks below are specific to SQL's `sqlstring` default format. + // The checks below are specific to SQL's `sqlstring` format. if (language === 'sql') { - const quoted = resolved.filter( - r => - (r.format ?? settings.defaultFormat) === 'sqlstring' && - r.inStringLiteral, + const quoted = valueVariableRefs.filter( + r => r.effectiveFormat === 'sqlstring' && r.inStringLiteral, ); if (quoted.length > 0) { const [{ name }] = quoted; @@ -1339,9 +1543,32 @@ export function validateVariableReferencesInTemplate( ); } - const unguarded = resolved.filter( + const quotedReferences = referenceRefs.filter( + r => r.effectiveFormat === 'sqlstring' && r.inStringLiteral, + ); + if (quotedReferences.length > 0) { + const [{ name, path }] = quotedReferences; + const field = path ? `.${path.join('.')}` : ''; + errors.push( + `${formatReferenceList(quotedReferences)} is wrapped in quotes, but the sqlstring format already quotes the value. Remove the quotes, or use \${${name}${field}:csv} inside them.`, + ); + } + + // Inside a string the backticks become part of the value + const quotedIdentifiers = resolved.filter( + r => r.effectiveFormat === 'sqlidentifier' && r.inStringLiteral, + ); + if (quotedIdentifiers.length > 0) { + const [{ name, path }] = quotedIdentifiers; + const field = path ? `.${path.join('.')}` : ''; + errors.push( + `${formatReferenceList(quotedIdentifiers)} is wrapped in quotes, but the sqlidentifier format renders a backtick-quoted identifier. Remove the quotes, or use \${${name}${field}:csv} inside them.`, + ); + } + + const unguarded = valueVariableRefs.filter( r => - (r.format ?? settings.defaultFormat) === 'sqlstring' && + r.effectiveFormat === 'sqlstring' && !r.inStringLiteral && r.guardedBy !== r.name, ); @@ -1356,15 +1583,13 @@ export function validateVariableReferencesInTemplate( // A regex or promql expansion is only valid as a quoted matcher value: an // alternation like `(api|web)`, `.*`, or an empty value is a syntax error // anywhere else, so `up{service=~$svc}` and `${svc}_total` are mistakes. + // A reference variable's one value, such as a metric name, is valid unquoted. if (language === 'promql') { - const unquoted = resolved.filter( - r => - isStringLiteralFormat(r.format ?? settings.defaultFormat) && - !r.inStringLiteral, + const unquoted = valueVariableRefs.filter( + r => isStringLiteralFormat(r.effectiveFormat) && !r.inStringLiteral, ); const isExactValue = (r: (typeof unquoted)[number]) => - (r.format ?? settings.defaultFormat) === 'promql' && - variables.some(v => v.name === r.name && isFilterSingleSelect(v)); + r.effectiveFormat === 'promql' && isFilterSingleSelect(r.variable); const groups = [ { refs: unquoted.filter(isExactValue), kind: 'a string', op: '=' }, { @@ -1437,6 +1662,19 @@ export function filterReferencedVariables( return variables.filter(variable => referenced.has(variable.name)); } +/** Whether `config`'s text references a data source or connection variable among `variables`. */ +export function configReferencesReferenceVariable( + config: ChartConfigWithOptDateRange | SavedChartConfig, + variables: ChartVariable[] | undefined, +): boolean { + const referenceVariables = + variables?.filter(variable => variable.reference != null) ?? []; + return ( + referenceVariables.length > 0 && + filterReferencedVariables(config, referenceVariables).length > 0 + ); +} + /** The warning an alerting tile shows when its query references dashboard variables. */ export function getAlertVariableWarning( config: ChartConfigWithOptDateRange | SavedChartConfig,