influx_query_model.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import _ from 'lodash';
  2. import queryPart from './query_part';
  3. import kbn from 'app/core/utils/kbn';
  4. import { InfluxQuery, InfluxQueryTag } from './types';
  5. import { ScopedVars } from '@grafana/ui';
  6. import { TemplateSrv } from 'app/features/templating/template_srv';
  7. export default class InfluxQueryModel {
  8. target: InfluxQuery;
  9. selectModels: any[];
  10. queryBuilder: any;
  11. groupByParts: any;
  12. templateSrv: any;
  13. scopedVars: any;
  14. refId: string;
  15. /** @ngInject */
  16. constructor(target: InfluxQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
  17. this.target = target;
  18. this.templateSrv = templateSrv;
  19. this.scopedVars = scopedVars;
  20. target.policy = target.policy || 'default';
  21. target.resultFormat = target.resultFormat || 'time_series';
  22. target.orderByTime = target.orderByTime || 'ASC';
  23. target.tags = target.tags || [];
  24. target.groupBy = target.groupBy || [{ type: 'time', params: ['$__interval'] }, { type: 'fill', params: ['null'] }];
  25. target.select = target.select || [[{ type: 'field', params: ['value'] }, { type: 'mean', params: [] }]];
  26. this.updateProjection();
  27. }
  28. updateProjection() {
  29. this.selectModels = _.map(this.target.select, (parts: any) => {
  30. return _.map(parts, queryPart.create);
  31. });
  32. this.groupByParts = _.map(this.target.groupBy, queryPart.create);
  33. }
  34. updatePersistedParts() {
  35. this.target.select = _.map(this.selectModels, selectParts => {
  36. return _.map(selectParts, (part: any) => {
  37. return { type: part.def.type, params: part.params };
  38. });
  39. });
  40. }
  41. hasGroupByTime() {
  42. return _.find(this.target.groupBy, (g: any) => g.type === 'time');
  43. }
  44. hasFill() {
  45. return _.find(this.target.groupBy, (g: any) => g.type === 'fill');
  46. }
  47. addGroupBy(value: string) {
  48. const stringParts = value.match(/^(\w+)\((.*)\)$/);
  49. const typePart = stringParts[1];
  50. const arg = stringParts[2];
  51. const partModel = queryPart.create({ type: typePart, params: [arg] });
  52. const partCount = this.target.groupBy.length;
  53. if (partCount === 0) {
  54. this.target.groupBy.push(partModel.part);
  55. } else if (typePart === 'time') {
  56. this.target.groupBy.splice(0, 0, partModel.part);
  57. } else if (typePart === 'tag') {
  58. if (this.target.groupBy[partCount - 1].type === 'fill') {
  59. this.target.groupBy.splice(partCount - 1, 0, partModel.part);
  60. } else {
  61. this.target.groupBy.push(partModel.part);
  62. }
  63. } else {
  64. this.target.groupBy.push(partModel.part);
  65. }
  66. this.updateProjection();
  67. }
  68. removeGroupByPart(part: { def: { type: string } }, index: number) {
  69. const categories = queryPart.getCategories();
  70. if (part.def.type === 'time') {
  71. // remove fill
  72. this.target.groupBy = _.filter(this.target.groupBy, (g: any) => g.type !== 'fill');
  73. // remove aggregations
  74. this.target.select = _.map(this.target.select, (s: any) => {
  75. return _.filter(s, (part: any) => {
  76. const partModel = queryPart.create(part);
  77. if (partModel.def.category === categories.Aggregations) {
  78. return false;
  79. }
  80. if (partModel.def.category === categories.Selectors) {
  81. return false;
  82. }
  83. return true;
  84. });
  85. });
  86. }
  87. this.target.groupBy.splice(index, 1);
  88. this.updateProjection();
  89. }
  90. removeSelect(index: number) {
  91. this.target.select.splice(index, 1);
  92. this.updateProjection();
  93. }
  94. removeSelectPart(selectParts: any[], part: any) {
  95. // if we remove the field remove the whole statement
  96. if (part.def.type === 'field') {
  97. if (this.selectModels.length > 1) {
  98. const modelsIndex = _.indexOf(this.selectModels, selectParts);
  99. this.selectModels.splice(modelsIndex, 1);
  100. }
  101. } else {
  102. const partIndex = _.indexOf(selectParts, part);
  103. selectParts.splice(partIndex, 1);
  104. }
  105. this.updatePersistedParts();
  106. }
  107. addSelectPart(selectParts: any[], type: string) {
  108. const partModel = queryPart.create({ type: type });
  109. partModel.def.addStrategy(selectParts, partModel, this);
  110. this.updatePersistedParts();
  111. }
  112. private renderTagCondition(tag: InfluxQueryTag, index: number, interpolate: boolean) {
  113. let str = '';
  114. let operator = tag.operator;
  115. let value = tag.value;
  116. if (index > 0) {
  117. str = (tag.condition || 'AND') + ' ';
  118. }
  119. if (!operator) {
  120. if (/^\/.*\/$/.test(value)) {
  121. operator = '=~';
  122. } else {
  123. operator = '=';
  124. }
  125. }
  126. // quote value unless regex
  127. if (operator !== '=~' && operator !== '!~') {
  128. if (interpolate) {
  129. value = this.templateSrv.replace(value, this.scopedVars);
  130. }
  131. if (operator !== '>' && operator !== '<') {
  132. value = "'" + value.replace(/\\/g, '\\\\').replace(/\'/g, "\\'") + "'";
  133. }
  134. } else if (interpolate) {
  135. value = this.templateSrv.replace(value, this.scopedVars, 'regex');
  136. }
  137. return str + '"' + tag.key + '" ' + operator + ' ' + value;
  138. }
  139. getMeasurementAndPolicy(interpolate: any) {
  140. let policy = this.target.policy;
  141. let measurement = this.target.measurement || 'measurement';
  142. if (!measurement.match('^/.*/$')) {
  143. measurement = '"' + measurement + '"';
  144. } else if (interpolate) {
  145. measurement = this.templateSrv.replace(measurement, this.scopedVars, 'regex');
  146. }
  147. if (policy !== 'default') {
  148. policy = '"' + this.target.policy + '".';
  149. } else {
  150. policy = '';
  151. }
  152. return policy + measurement;
  153. }
  154. interpolateQueryStr(value: any[], variable: { multi: any; includeAll: any }, defaultFormatFn: any) {
  155. // if no multi or include all do not regexEscape
  156. if (!variable.multi && !variable.includeAll) {
  157. return value;
  158. }
  159. if (typeof value === 'string') {
  160. return kbn.regexEscape(value);
  161. }
  162. const escapedValues = _.map(value, kbn.regexEscape);
  163. return '(' + escapedValues.join('|') + ')';
  164. }
  165. render(interpolate?: boolean) {
  166. const target = this.target;
  167. if (target.rawQuery) {
  168. if (interpolate) {
  169. return this.templateSrv.replace(target.query, this.scopedVars, this.interpolateQueryStr);
  170. } else {
  171. return target.query;
  172. }
  173. }
  174. let query = 'SELECT ';
  175. let i, y;
  176. for (i = 0; i < this.selectModels.length; i++) {
  177. const parts = this.selectModels[i];
  178. let selectText = '';
  179. for (y = 0; y < parts.length; y++) {
  180. const part = parts[y];
  181. selectText = part.render(selectText);
  182. }
  183. if (i > 0) {
  184. query += ', ';
  185. }
  186. query += selectText;
  187. }
  188. query += ' FROM ' + this.getMeasurementAndPolicy(interpolate) + ' WHERE ';
  189. const conditions = _.map(target.tags, (tag, index) => {
  190. return this.renderTagCondition(tag, index, interpolate);
  191. });
  192. if (conditions.length > 0) {
  193. query += '(' + conditions.join(' ') + ') AND ';
  194. }
  195. query += '$timeFilter';
  196. let groupBySection = '';
  197. for (i = 0; i < this.groupByParts.length; i++) {
  198. const part = this.groupByParts[i];
  199. if (i > 0) {
  200. // for some reason fill has no separator
  201. groupBySection += part.def.type === 'fill' ? ' ' : ', ';
  202. }
  203. groupBySection += part.render('');
  204. }
  205. if (groupBySection.length) {
  206. query += ' GROUP BY ' + groupBySection;
  207. }
  208. if (target.fill) {
  209. query += ' fill(' + target.fill + ')';
  210. }
  211. if (target.orderByTime === 'DESC') {
  212. query += ' ORDER BY time DESC';
  213. }
  214. if (target.limit) {
  215. query += ' LIMIT ' + target.limit;
  216. }
  217. if (target.slimit) {
  218. query += ' SLIMIT ' + target.slimit;
  219. }
  220. if (target.tz) {
  221. query += " tz('" + target.tz + "')";
  222. }
  223. return query;
  224. }
  225. renderAdhocFilters(filters: any[]) {
  226. const conditions = _.map(filters, (tag, index) => {
  227. return this.renderTagCondition(tag, index, false);
  228. });
  229. return conditions.join(' ');
  230. }
  231. }