grafana/public/app/plugins/datasource/postgres/postgres_query.ts

328 lines
8.7 KiB
TypeScript
Raw Normal View History

2018-01-30 15:13:55 -06:00
import _ from 'lodash';
import sqlPart from './sql_part';
2018-01-30 15:13:55 -06:00
export default class PostgresQuery {
target: any;
selectModels: any[];
queryBuilder: any;
groupByParts: any[];
whereParts: any[];
2018-01-30 15:13:55 -06:00
templateSrv: any;
scopedVars: any;
/** @ngInject */
constructor(target, templateSrv?, scopedVars?) {
this.target = target;
this.templateSrv = templateSrv;
this.scopedVars = scopedVars;
target.schema = target.schema || 'public';
target.format = target.format || 'time_series';
target.timeColumn = target.timeColumn || 'time';
2018-02-08 03:25:32 -06:00
target.metricColumn = target.metricColumn || 'None';
2018-01-30 15:13:55 -06:00
2018-02-08 03:25:32 -06:00
target.groupBy = target.groupBy || [];
target.where = target.where || [];
2018-03-03 13:57:00 -06:00
target.select = target.select || [[{ type: 'column', params: ['value'] }]];
2018-01-30 15:13:55 -06:00
// handle pre query gui panels gracefully
if (!('rawQuery' in this.target)) {
if ('rawSql' in target) {
// pre query gui panel
target.rawQuery = true;
} else {
// new panel
target.rawQuery = false;
}
}
2018-03-14 12:09:47 -05:00
// give interpolateQueryStr access to this
this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
2018-03-14 17:03:32 -05:00
this.updateProjection();
2018-01-30 15:13:55 -06:00
}
2018-07-06 02:28:34 -05:00
// remove identifier quoting from identifier to use in metadata queries
unquoteIdentifier(value) {
2018-07-06 02:28:34 -05:00
if (value[0] === '"' && value[value.length - 1] === '"') {
return value.substring(1, value.length - 1).replace('""', '"');
} else {
return value;
}
}
2018-02-08 03:25:32 -06:00
quoteIdentifier(value) {
return '"' + value.replace('"', '""') + '"';
2018-02-08 03:25:32 -06:00
}
quoteLiteral(value) {
return "'" + value.replace("'", "''") + "'";
2018-01-30 15:57:38 -06:00
}
2018-01-30 15:13:55 -06:00
updateProjection() {
this.selectModels = _.map(this.target.select, function(parts: any) {
return _.map(parts, sqlPart.create).filter(n => n);
2018-01-30 15:13:55 -06:00
});
this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
this.groupByParts = _.map(this.target.groupBy, sqlPart.create).filter(n => n);
2018-01-30 15:13:55 -06:00
}
updatePersistedParts() {
this.target.select = _.map(this.selectModels, function(selectParts) {
return _.map(selectParts, function(part: any) {
return { type: part.def.type, params: part.params };
});
});
this.target.where = _.map(this.whereParts, function(part: any) {
return { type: part.def.type, name: part.name, params: part.params };
});
this.target.groupBy = _.map(this.groupByParts, function(part: any) {
return { type: part.def.type, params: part.params };
});
2018-01-30 15:13:55 -06:00
}
hasGroupByTime() {
return _.find(this.target.groupBy, (g: any) => g.type === 'time');
}
2018-07-05 03:19:22 -05:00
addGroupBy(partType, value) {
2018-07-11 06:03:06 -05:00
let partModel = sqlPart.create({ type: partType, params: [value] });
let partCount = this.target.groupBy.length;
2018-01-30 15:13:55 -06:00
if (partCount === 0) {
this.target.groupBy.push(partModel.part);
2018-07-05 03:19:22 -05:00
} else if (partType === 'time') {
// put timeGroup at start
2018-01-30 15:13:55 -06:00
this.target.groupBy.splice(0, 0, partModel.part);
} else {
this.target.groupBy.push(partModel.part);
}
2018-07-05 03:19:22 -05:00
if (partType === 'time') {
partModel.part.params = ['1m', 'none'];
}
2018-07-10 04:14:00 -05:00
// add aggregates when adding group by
for (let i = 0; i < this.target.select.length; i++) {
var selectParts = this.target.select[i];
if (!selectParts.some(part => part.type === 'aggregate')) {
selectParts.splice(1, 0, { type: 'aggregate', params: ['avg'] });
2018-07-10 04:32:23 -05:00
if (!selectParts.some(part => part.type === 'alias')) {
selectParts.push({ type: 'alias', params: [selectParts[0].params[0]] });
}
2018-07-10 04:14:00 -05:00
}
}
2018-01-30 15:13:55 -06:00
this.updateProjection();
}
removeGroupByPart(part, index) {
if (part.def.type === 'time') {
// remove aggregations
this.target.select = _.map(this.target.select, (s: any) => {
return _.filter(s, (part: any) => {
if (part.type === 'aggregate') {
2018-01-30 15:13:55 -06:00
return false;
}
return true;
});
});
}
this.target.groupBy.splice(index, 1);
this.updateProjection();
}
removeSelectPart(selectParts, part) {
// if we remove the field remove the whole statement
2018-03-03 13:57:00 -06:00
if (part.def.type === 'column') {
2018-01-30 15:13:55 -06:00
if (this.selectModels.length > 1) {
2018-07-11 06:03:06 -05:00
let modelsIndex = _.indexOf(this.selectModels, selectParts);
2018-01-30 15:13:55 -06:00
this.selectModels.splice(modelsIndex, 1);
}
} else {
2018-07-11 06:03:06 -05:00
let partIndex = _.indexOf(selectParts, part);
2018-01-30 15:13:55 -06:00
selectParts.splice(partIndex, 1);
}
this.updatePersistedParts();
}
addSelectPart(selectParts, type) {
2018-07-11 06:03:06 -05:00
let partModel = sqlPart.create({ type: type });
2018-01-30 15:13:55 -06:00
partModel.def.addStrategy(selectParts, partModel, this);
this.updatePersistedParts();
}
interpolateQueryStr(value, variable, defaultFormatFn) {
// if no multi or include all do not regexEscape
if (!variable.multi && !variable.includeAll) {
return value;
}
if (typeof value === 'string') {
2018-03-14 12:09:47 -05:00
return this.quoteLiteral(value);
2018-01-30 15:13:55 -06:00
}
2018-07-11 06:03:06 -05:00
let escapedValues = _.map(value, this.quoteLiteral);
2018-03-13 17:33:40 -05:00
return '(' + escapedValues.join(',') + ')';
2018-01-30 15:13:55 -06:00
}
render(interpolate?) {
let target = this.target;
let query;
2018-01-30 15:13:55 -06:00
if (target.rawQuery) {
2018-01-30 15:13:55 -06:00
if (interpolate) {
return this.templateSrv.replace(target.rawSql, this.scopedVars, this.interpolateQueryStr);
} else {
return target.rawSql;
}
}
query = this.buildQuery(target);
if (interpolate) {
query = this.templateSrv.replace(query, this.scopedVars, this.interpolateQueryStr);
}
2018-07-11 05:33:37 -05:00
this.target.rawSql = query;
return query;
}
2018-07-11 04:00:12 -05:00
buildTimeColumn(target) {
let timeGroup = this.hasGroupByTime();
let query;
2018-03-04 12:35:43 -06:00
if (timeGroup) {
2018-07-11 06:03:06 -05:00
let args;
if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') {
args = timeGroup.params.join(',');
2018-03-04 12:35:43 -06:00
} else {
args = timeGroup.params[0];
}
2018-07-11 04:00:12 -05:00
query = '$__timeGroup(' + target.timeColumn + ',' + args + ')';
2018-03-03 13:57:00 -06:00
} else {
2018-07-11 04:00:12 -05:00
query = target.timeColumn + ' AS "time"';
2018-05-21 05:10:18 -05:00
}
2018-07-11 04:00:12 -05:00
return query;
}
2018-07-11 05:33:37 -05:00
buildMetricColumn(target) {
let query = '';
if (this.target.metricColumn !== 'None') {
query += ',' + this.target.metricColumn + ' AS metric';
}
return query;
}
buildValueColumns(target) {
let query = '';
for (let i = 0; i < target.select.length; i++) {
query += ', ' + this.buildValueColumn(target, target.select[i]);
}
return query;
}
2018-07-11 06:03:06 -05:00
buildValueColumn(target, column) {
let query = '';
let columnName = _.find(column, (g: any) => g.type === 'column');
query = columnName.params[0];
let aggregate = _.find(column, (g: any) => g.type === 'aggregate');
if (aggregate) {
query = aggregate.params[0] + '(' + query + ')';
2018-07-11 06:03:06 -05:00
}
let special = _.find(column, (g: any) => g.type === 'special');
if (special) {
let over = '';
if (target.metricColumn) {
over = 'PARTITION BY ' + target.metricColumn;
}
switch (special.params[0]) {
case 'increase':
query = query + ' - lag(' + query + ') OVER (' + over + ')';
break;
case 'rate':
let timeColumn = target.timeColumn;
query = '(' + query + ' - lag(' + query + ') OVER (' + over + '))';
query += '/extract(epoch from ' + timeColumn + ' - lag(' + timeColumn + ') OVER (' + over + '))';
break;
}
}
let alias = _.find(column, (g: any) => g.type === 'alias');
if (alias) {
query += ' AS ' + this.quoteIdentifier(alias.params[0]);
}
return query;
2018-07-11 06:03:06 -05:00
}
2018-07-11 04:50:02 -05:00
buildWhereClause(target) {
let query = '';
2018-07-11 06:03:06 -05:00
let conditions = _.map(target.where, (tag, index) => {
switch (tag.type) {
case 'macro':
return tag.name + '(' + target.timeColumn + ')';
break;
case 'expression':
return tag.params.join(' ');
break;
}
2018-01-30 15:13:55 -06:00
});
if (conditions.length > 0) {
2018-07-11 04:50:02 -05:00
query = ' WHERE ' + conditions.join(' AND ');
}
return query;
}
2018-07-11 05:20:24 -05:00
buildGroupByClause(target) {
let query = '';
let groupBySection = '';
2018-07-11 04:50:02 -05:00
for (let i = 0; i < this.groupByParts.length; i++) {
2018-07-11 06:03:06 -05:00
let part = this.groupByParts[i];
2018-01-30 15:13:55 -06:00
if (i > 0) {
2018-03-03 13:57:00 -06:00
groupBySection += ', ';
}
if (part.def.type === 'time') {
2018-03-04 12:35:43 -06:00
groupBySection += '1';
2018-03-03 13:57:00 -06:00
} else {
groupBySection += part.render('');
2018-01-30 15:13:55 -06:00
}
}
if (groupBySection.length) {
2018-07-11 05:20:24 -05:00
query = ' GROUP BY ' + groupBySection;
if (this.target.metricColumn !== 'None') {
query += ',2';
2018-05-21 05:10:18 -05:00
}
2018-01-30 15:13:55 -06:00
}
2018-07-11 05:20:24 -05:00
return query;
}
buildQuery(target) {
let query = 'SELECT ';
query += this.buildTimeColumn(target);
2018-07-11 05:33:37 -05:00
query += this.buildMetricColumn(target);
2018-07-11 05:20:24 -05:00
query += this.buildValueColumns(target);
query += ' FROM ' + target.schema + '.' + target.table;
query += this.buildWhereClause(target);
query += this.buildGroupByClause(target);
2018-01-30 15:13:55 -06:00
2018-03-04 12:35:43 -06:00
query += ' ORDER BY 1';
2018-01-30 15:13:55 -06:00
return query;
}
}