fix bug in loki's adhoc filters (#54920)

This commit is contained in:
Sven Grossmann 2022-09-09 12:04:51 +02:00 committed by GitHub
parent a861c10f1b
commit 20b07fae6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 3 deletions

View File

@ -639,6 +639,22 @@ describe('LokiDatasource', () => {
it('then the correct label should be added for metrics query', () => {
assertAdHocFilters('rate({bar="baz"}[5m])', 'rate({bar="baz", job="grafana"}[5m])', ds);
});
it('then the correct label should be added for metrics query and variable', () => {
assertAdHocFilters('rate({bar="baz"}[$__interval])', 'rate({bar="baz", job="grafana"}[$__interval])', ds);
});
it('then the correct label should be added for logs query with empty selector', () => {
assertAdHocFilters('{}', '{job="grafana"}', ds);
});
it('then the correct label should be added for metrics query with empty selector', () => {
assertAdHocFilters('rate({}[5m])', 'rate({job="grafana"}[5m])', ds);
});
it('then the correct label should be added for metrics query with empty selector and variable', () => {
assertAdHocFilters('rate({}[$__interval])', 'rate({job="grafana"}[$__interval])', ds);
});
});
describe('and query has parser', () => {
it('then the correct label should be added for logs query', () => {

View File

@ -43,6 +43,7 @@ import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_sr
import { serializeParams } from '../../../core/utils/fetch';
import { renderLegendFormat } from '../prometheus/legend';
import { replaceVariables, returnVariables } from '../prometheus/querybuilder/shared/parsingUtils';
import LanguageProvider from './LanguageProvider';
import { transformBackendResult } from './backendResultTransformer';
@ -698,14 +699,14 @@ export class LokiDatasource
addAdHocFilters(queryExpr: string) {
const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
let expr = queryExpr;
let expr = replaceVariables(queryExpr);
expr = adhocFilters.reduce((acc: string, filter: { key: string; operator: string; value: string }) => {
const { key, operator, value } = filter;
return this.addLabelToQuery(acc, key, operator, value);
}, expr);
return expr;
return returnVariables(expr);
}
addLabelToQuery(queryExpr: string, key: string, operator: string, value: string) {

View File

@ -65,7 +65,7 @@ const varTypeFunc = [
* Get back the text with variables in their original format.
* @param expr
*/
function returnVariables(expr: string) {
export function returnVariables(expr: string) {
return expr.replace(/__V_(\d)__(.+?)__V__(?:__F__(\w+)__F__)?/g, (match, type, v, f) => {
return varTypeFunc[parseInt(type, 10)](v, f);
});