This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSqlProxyDatasource.ts
More file actions
146 lines (130 loc) · 4.28 KB
/
Copy pathSqlProxyDatasource.ts
File metadata and controls
146 lines (130 loc) · 4.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// TODO - merge with new Datasource.ts
import _ from 'lodash';
import {
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
MutableDataFrame,
DataFrame,
guessFieldTypeFromValue,
FieldType,
} from '@grafana/data';
import { Settings, SqlQuery } from '../shared/types';
import { getBackendSrv } from '@grafana/runtime';
import { format } from 'date-fns';
export class DataSource extends DataSourceApi<SqlQuery, Settings> {
/** @ngInject */
constructor(private instanceSettings: DataSourceInstanceSettings<Settings>, public templateSrv: any) {
super(instanceSettings);
}
async query(options: DataQueryRequest<SqlQuery>): Promise<DataQueryResponse> {
const { range } = options;
if (!range) {
return { data: [] };
}
options.startTime = range.from.valueOf();
options.endTime = range.to.valueOf();
let baseUrl = this.instanceSettings.url!;
if (this.instanceSettings.jsonData.backend) {
baseUrl = 'api/ds/';
}
const route = baseUrl.endsWith('/') ? 'query?' : '/query?';
const opts = this.interpolate(options);
const calls = opts.targets.map(target => {
const url = `${baseUrl}${route}sql=${target.sql}`;
return getBackendSrv()
.datasourceRequest({ url })
.then(res => {
return this.arrayToDataFrame(res.data);
});
});
const data = await Promise.all(calls);
return {
data,
};
}
arrayToDataFrame(array: any[]): DataFrame {
let dataFrame: MutableDataFrame = new MutableDataFrame();
if (array.length > 0) {
const fields = Object.keys(array[0]).map(field => {
return { name: field, type: guessFieldTypeFromValue(array[0][field]) };
});
for (const field of fields) {
if (field.name.toLowerCase() === 'time') {
field.type = FieldType.time;
}
}
dataFrame = new MutableDataFrame({ fields });
array.forEach((row, index) => {
dataFrame.appendRow(Object.values(row));
});
}
return dataFrame;
}
interpolate(options: DataQueryRequest<SqlQuery>): DataQueryRequest<SqlQuery> {
const visibleTargets: SqlQuery[] = options.targets.filter((target: SqlQuery) => !target.hide);
return {
...options,
targets: visibleTargets.map(target => {
const query: SqlQuery = {
...target,
sql: this.applyMacros(this.templateSrv.replace(target.sql, options.scopedVars), options),
};
return query;
}),
};
}
applyMacros(sql: string, options: DataQueryRequest<SqlQuery>) {
if (sql.includes('$__timeFrom(')) {
sql = this.applyMacroFunction('$__timeFrom(', sql, options);
}
if (sql.includes('$__timeTo(')) {
sql = this.applyMacroFunction('$__timeTo(', sql, options);
}
if (sql.includes('$__timeFrom')) {
sql = sql.replace(/\$__timeFrom/g, options.startTime.toString());
}
if (sql.includes('$__timeTo')) {
sql = sql.replace(/\$__timeTo/g, options.endTime?.toString() ?? '');
}
return sql;
}
applyMacroFunction(macro: string, sql: string, options: DataQueryRequest<SqlQuery>): string {
if (sql.includes(macro)) {
let time;
if (macro === '$__timeFrom(') {
time = new Date(options.startTime);
} else {
time = new Date(options.endTime!);
}
const start = sql.indexOf(macro) + macro.length;
const end = sql.indexOf(')', start);
const fmt = sql.substring(start, end);
const dateStr = format(time, fmt);
const toReplace = sql.substring(start - macro.length, end + 1);
sql = sql.replace(toReplace, dateStr);
return this.applyMacroFunction(macro, sql, options);
}
return sql;
}
metricFindQuery(query: any) {
const baseUrl = this.instanceSettings.url!;
const route = baseUrl.endsWith('/') ? 'query?' : '/query?';
const url = `${baseUrl}${route}sql=${query}`;
return getBackendSrv()
.datasourceRequest({ url })
.then(res => {
return res.data.map((v: any) => ({ text: Object.values(v) }));
});
}
async testDatasource() {
const url = this.instanceSettings.url!;
const response = await getBackendSrv().post(url, this.instanceSettings.jsonData);
return {
status: 'success',
message: response.data,
title: 'Success',
};
}
}