Skip to content

Commit

Permalink
Variables: Add datasource variable support (#1006)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunker authored Dec 17, 2024
1 parent f57c6fb commit cb03ae9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import {
} from '@grafana/data';
import { getRunRequest } from '@grafana/runtime';

import { hasCustomVariableSupport, hasLegacyVariableSupport, hasStandardVariableSupport } from './guards';
import {
hasCustomVariableSupport,
hasDataSourceVariableSupport,
hasLegacyVariableSupport,
hasStandardVariableSupport,
} from './guards';

import { QueryVariable } from './QueryVariable';
import { DataQuery } from '@grafana/schema';
Expand Down Expand Up @@ -111,6 +116,31 @@ class CustomQueryRunner implements QueryRunner {
}
}

const variableDummyRefId = 'variable-query';
class DatasourceQueryRunner implements QueryRunner {
public constructor(private datasource: DataSourceApi, private _runRequest = getRunRequest()) {}

public getTarget(variable: QueryVariable) {
if (hasDataSourceVariableSupport(this.datasource)) {
if (typeof variable.state.query === 'string') {
return variable.state.query;
}

return { ...variable.state.query, refId: variable.state.query.refId ?? variableDummyRefId };
}

throw new Error("Couldn't create a target with supplied arguments.");
}

public runRequest(_: RunnerArgs, request: DataQueryRequest) {
if (!hasDataSourceVariableSupport(this.datasource)) {
return getEmptyMetricFindValueObservable();
}

return this._runRequest(this.datasource, request, this.datasource.query);
}
}

function getEmptyMetricFindValueObservable(): Observable<PanelData> {
return of({ state: LoadingState.Done, series: [], timeRange: getDefaultTimeRange() });
}
Expand All @@ -128,6 +158,10 @@ function createQueryVariableRunnerFactory(datasource: DataSourceApi): QueryRunne
return new CustomQueryRunner(datasource);
}

if (hasDataSourceVariableSupport(datasource)) {
return new DatasourceQueryRunner(datasource);
}

throw new Error(`Couldn't create a query runner for datasource ${datasource.type}`);
}

Expand Down
13 changes: 13 additions & 0 deletions packages/scenes/src/variables/variants/query/guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,16 @@ export const hasCustomVariableSupport = <
Boolean(variableSupport.editor)
);
};

export const hasDataSourceVariableSupport = <
TQuery extends DataQuery = DataQuery,
TOptions extends DataSourceJsonData = DataSourceJsonData
>(
datasource: DataSourceApi<TQuery, TOptions>
): datasource is DataSourceWithCustomVariableSupport<TQuery, TOptions> => {
if (!datasource.variables) {
return false;
}

return datasource.variables.getType() === VariableSupportType.Datasource;
};

0 comments on commit cb03ae9

Please sign in to comment.