grafana/public/app/plugins/datasource/mysql/datasource.ts

210 lines
6.1 KiB
TypeScript
Raw Normal View History

import { map as _map } from 'lodash';
import { of } from 'rxjs';
import { catchError, map, mapTo } from 'rxjs/operators';
import { getBackendSrv, DataSourceWithBackend, FetchResponse, BackendDataSourceResponse } from '@grafana/runtime';
import { DataSourceInstanceSettings, ScopedVars, MetricFindValue, AnnotationEvent } from '@grafana/data';
import MySQLQueryModel from 'app/plugins/datasource/mysql/mysql_query_model';
import ResponseParser from './response_parser';
import { MysqlQueryForInterpolation, MySQLOptions, MySQLQuery } from './types';
import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
import { getSearchFilterScopedVar } from '../../../features/variables/utils';
import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv';
2017-03-29 13:43:20 -05:00
export class MysqlDatasource extends DataSourceWithBackend<MySQLQuery, MySQLOptions> {
2017-03-29 15:54:07 -05:00
id: any;
name: any;
responseParser: ResponseParser;
queryModel: MySQLQueryModel;
interval: string;
2017-03-29 13:43:20 -05:00
constructor(
instanceSettings: DataSourceInstanceSettings<MySQLOptions>,
private readonly templateSrv: TemplateSrv = getTemplateSrv(),
private readonly timeSrv: TimeSrv = getTimeSrv()
) {
super(instanceSettings);
2017-03-29 15:54:07 -05:00
this.name = instanceSettings.name;
this.id = instanceSettings.id;
this.responseParser = new ResponseParser();
this.queryModel = new MySQLQueryModel({});
const settingsData = instanceSettings.jsonData || ({} as MySQLOptions);
this.interval = settingsData.timeInterval || '1m';
2017-03-29 13:43:20 -05:00
}
interpolateVariable = (value: string | string[] | number, variable: any) => {
2017-12-20 05:33:33 -06:00
if (typeof value === 'string') {
if (variable.multi || variable.includeAll) {
const result = this.queryModel.quoteLiteral(value);
return result;
} else {
return value;
}
2017-04-23 07:22:47 -05:00
}
2017-12-20 05:33:33 -06:00
if (typeof value === 'number') {
return value;
}
const quotedValues = _map(value, (v: any) => {
return this.queryModel.quoteLiteral(v);
2017-04-23 07:22:47 -05:00
});
2017-12-20 05:33:33 -06:00
return quotedValues.join(',');
};
2017-04-23 07:22:47 -05:00
interpolateVariablesInQueries(
queries: MysqlQueryForInterpolation[],
scopedVars: ScopedVars
): MysqlQueryForInterpolation[] {
let expandedQueries = queries;
if (queries && queries.length > 0) {
expandedQueries = queries.map((query) => {
const expandedQuery = {
...query,
datasource: this.name,
rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),
rawQuery: true,
};
return expandedQuery;
});
}
return expandedQueries;
}
filterQuery(query: MySQLQuery): boolean {
return !query.hide;
}
applyTemplateVariables(target: MySQLQuery, scopedVars: ScopedVars): Record<string, any> {
const queryModel = new MySQLQueryModel(target, this.templateSrv, scopedVars);
return {
refId: target.refId,
datasourceId: this.id,
rawSql: queryModel.render(this.interpolateVariable as any),
format: target.format,
};
}
2017-04-20 10:10:09 -05:00
async annotationQuery(options: any): Promise<AnnotationEvent[]> {
if (!options.annotation.rawQuery) {
return Promise.reject({
2017-12-20 05:33:33 -06:00
message: 'Query missing in annotation definition',
});
}
const query = {
refId: options.annotation.name,
datasourceId: this.id,
rawSql: this.templateSrv.replace(options.annotation.rawQuery, options.scopedVars, this.interpolateVariable),
2017-12-20 05:33:33 -06:00
format: 'table',
};
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 03:08:07 -06:00
return getBackendSrv()
.fetch<BackendDataSourceResponse>({
url: '/api/ds/query',
2017-12-20 05:33:33 -06:00
method: 'POST',
data: {
from: options.range.from.valueOf().toString(),
to: options.range.to.valueOf().toString(),
2017-12-20 05:33:33 -06:00
queries: [query],
},
requestId: options.annotation.name,
})
.pipe(
map(
async (res: FetchResponse<BackendDataSourceResponse>) =>
await this.responseParser.transformAnnotationResponse(options, res.data)
)
)
.toPromise();
}
metricFindQuery(query: string, optionalOptions: any): Promise<MetricFindValue[]> {
2017-12-20 05:33:33 -06:00
let refId = 'tempvar';
if (optionalOptions && optionalOptions.variable && optionalOptions.variable.name) {
refId = optionalOptions.variable.name;
}
const rawSql = this.templateSrv.replace(
query,
getSearchFilterScopedVar({ query, wildcardChar: '%', options: optionalOptions }),
this.interpolateVariable
);
const interpolatedQuery = {
refId: refId,
datasourceId: this.id,
rawSql,
2017-12-20 05:33:33 -06:00
format: 'table',
};
2018-08-31 11:24:09 -05:00
const range = this.timeSrv.timeRange();
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 03:08:07 -06:00
return getBackendSrv()
.fetch<BackendDataSourceResponse>({
url: '/api/ds/query',
2017-12-20 05:33:33 -06:00
method: 'POST',
data: {
from: range.from.valueOf().toString(),
to: range.to.valueOf().toString(),
queries: [interpolatedQuery],
},
requestId: refId,
})
.pipe(
map((rsp) => {
return this.responseParser.transformMetricFindResponse(rsp);
})
)
.toPromise();
}
testDatasource(): Promise<any> {
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 03:08:07 -06:00
return getBackendSrv()
.fetch({
url: '/api/ds/query',
2017-12-20 05:33:33 -06:00
method: 'POST',
data: {
2017-12-20 05:33:33 -06:00
from: '5m',
to: 'now',
queries: [
{
2017-12-20 05:33:33 -06:00
refId: 'A',
intervalMs: 1,
maxDataPoints: 1,
datasourceId: this.id,
2017-12-20 05:33:33 -06:00
rawSql: 'SELECT 1',
format: 'table',
},
],
},
})
.pipe(
mapTo({ status: 'success', message: 'Database Connection OK' }),
catchError((err) => {
console.error(err);
if (err.data && err.data.message) {
return of({ status: 'error', message: err.data.message });
} else {
return of({ status: 'error', message: err.status });
}
})
)
.toPromise();
}
targetContainsTemplate(target: any) {
let rawSql = '';
if (target.rawQuery) {
rawSql = target.rawSql;
} else {
const query = new MySQLQueryModel(target);
rawSql = query.buildQuery();
}
rawSql = rawSql.replace('$__', '');
return this.templateSrv.variableExists(rawSql);
}
2017-03-29 13:43:20 -05:00
}