MySQL, Postgres, MSSQL: Fix validating query with template variables in alert (#19237)

Adds support for validating query in alert for mysql, 
postgres and mssql.

Fixes #13155
This commit is contained in:
Marcus Efraimsson
2019-09-24 20:46:07 +02:00
committed by GitHub
parent f203e82b40
commit 96046a7ba6
6 changed files with 189 additions and 10 deletions

View File

@@ -160,4 +160,19 @@ export class PostgresDatasource {
}
});
}
targetContainsTemplate(target: any) {
let rawSql = '';
if (target.rawQuery) {
rawSql = target.rawSql;
} else {
const query = new PostgresQuery(target);
rawSql = query.buildQuery();
}
rawSql = rawSql.replace('$__', '');
return this.templateSrv.variableExists(rawSql);
}
}

View File

@@ -3,14 +3,13 @@ import { CustomVariable } from 'app/features/templating/custom_variable';
import { toUtc, dateTime } from '@grafana/data';
import { BackendSrv } from 'app/core/services/backend_srv';
import { IQService } from 'angular';
import { TemplateSrv } from 'app/features/templating/template_srv';
describe('PostgreSQLDatasource', () => {
const instanceSettings = { name: 'postgresql' };
const backendSrv = {};
const templateSrv: any = {
replace: jest.fn(text => text),
};
const templateSrv: TemplateSrv = new TemplateSrv();
const raw = {
from: toUtc('2018-04-25 10:00'),
to: toUtc('2018-04-25 11:00'),
@@ -249,4 +248,53 @@ describe('PostgreSQLDatasource', () => {
});
});
});
describe('targetContainsTemplate', () => {
it('given query that contains template variable it should return true', () => {
const rawSql = `SELECT
$__timeGroup("createdAt",'$summarize'),
avg(value) as "value",
hostname as "metric"
FROM
grafana_metric
WHERE
$__timeFilter("createdAt") AND
measurement = 'logins.count' AND
hostname IN($host)
GROUP BY time, metric
ORDER BY time`;
const query = {
rawSql,
rawQuery: true,
};
templateSrv.init([
{ type: 'query', name: 'summarize', current: { value: '1m' } },
{ type: 'query', name: 'host', current: { value: 'a' } },
]);
expect(ctx.ds.targetContainsTemplate(query)).toBeTruthy();
});
it('given query that only contains global template variable it should return false', () => {
const rawSql = `SELECT
$__timeGroup("createdAt",'$__interval'),
avg(value) as "value",
hostname as "metric"
FROM
grafana_metric
WHERE
$__timeFilter("createdAt") AND
measurement = 'logins.count'
GROUP BY time, metric
ORDER BY time`;
const query = {
rawSql,
rawQuery: true,
};
templateSrv.init([
{ type: 'query', name: 'summarize', current: { value: '1m' } },
{ type: 'query', name: 'host', current: { value: 'a' } },
]);
expect(ctx.ds.targetContainsTemplate(query)).toBeFalsy();
});
});
});