query_ctrl.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import _ from 'lodash';
  2. import { PostgresMetaQuery } from './meta_query';
  3. import { QueryCtrl } from 'app/plugins/sdk';
  4. import { SqlPart } from 'app/core/components/sql_part/sql_part';
  5. import PostgresQuery from './postgres_query';
  6. import sqlPart from './sql_part';
  7. export interface QueryMeta {
  8. sql: string;
  9. }
  10. const defaultQuery = `SELECT
  11. $__time(time_column),
  12. value1
  13. FROM
  14. metric_table
  15. WHERE
  16. $__timeFilter(time_column)
  17. `;
  18. export class PostgresQueryCtrl extends QueryCtrl {
  19. static templateUrl = 'partials/query.editor.html';
  20. showLastQuerySQL: boolean;
  21. formats: any[];
  22. queryModel: PostgresQuery;
  23. metaBuilder: PostgresMetaQuery;
  24. lastQueryMeta: QueryMeta;
  25. lastQueryError: string;
  26. showHelp: boolean;
  27. tableSegment: any;
  28. whereAdd: any;
  29. timeColumnSegment: any;
  30. metricColumnSegment: any;
  31. selectMenu: any[];
  32. selectParts: SqlPart[][];
  33. groupParts: SqlPart[];
  34. whereParts: SqlPart[];
  35. groupAdd: any;
  36. /** @ngInject **/
  37. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  38. super($scope, $injector);
  39. this.target = this.target;
  40. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  41. this.metaBuilder = new PostgresMetaQuery(this.target, this.queryModel);
  42. this.updateProjection();
  43. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  44. if (!this.target.rawSql) {
  45. // special handling when in table panel
  46. if (this.panelCtrl.panel.type === 'table') {
  47. this.target.format = 'table';
  48. this.target.rawSql = 'SELECT 1';
  49. } else {
  50. this.target.rawSql = defaultQuery;
  51. }
  52. }
  53. if (!this.target.table) {
  54. this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
  55. } else {
  56. this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
  57. }
  58. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  59. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  60. this.buildSelectMenu();
  61. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  62. this.groupAdd = this.uiSegmentSrv.newPlusButton();
  63. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  64. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  65. }
  66. updateProjection() {
  67. this.selectParts = _.map(this.target.select, function(parts: any) {
  68. return _.map(parts, sqlPart.create).filter(n => n);
  69. });
  70. this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
  71. this.groupParts = _.map(this.target.group, sqlPart.create).filter(n => n);
  72. }
  73. updatePersistedParts() {
  74. this.target.select = _.map(this.selectParts, function(selectParts) {
  75. return _.map(selectParts, function(part: any) {
  76. return { type: part.def.type, params: part.params };
  77. });
  78. });
  79. this.target.where = _.map(this.whereParts, function(part: any) {
  80. return { type: part.def.type, name: part.name, params: part.params };
  81. });
  82. this.target.group = _.map(this.groupParts, function(part: any) {
  83. return { type: part.def.type, params: part.params };
  84. });
  85. }
  86. buildSelectMenu() {
  87. this.selectMenu = [
  88. {
  89. text: 'Aggregate Functions',
  90. value: 'aggregate',
  91. submenu: [
  92. { text: 'Average', value: 'avg' },
  93. { text: 'Count', value: 'count' },
  94. { text: 'Maximum', value: 'max' },
  95. { text: 'Minimum', value: 'min' },
  96. { text: 'Sum', value: 'sum' },
  97. { text: 'Standard deviation', value: 'stddev' },
  98. { text: 'Variance', value: 'variance' },
  99. ],
  100. },
  101. {
  102. text: 'Window Functions',
  103. value: 'window',
  104. submenu: [
  105. { text: 'Increase', value: 'increase' },
  106. { text: 'Rate', value: 'rate' },
  107. { text: 'Sum', value: 'sum' },
  108. ],
  109. },
  110. { text: 'Alias', value: 'alias' },
  111. { text: 'Column', value: 'column' },
  112. ];
  113. }
  114. toggleEditorMode() {
  115. this.target.rawQuery = !this.target.rawQuery;
  116. }
  117. resetPlusButton(button) {
  118. let plusButton = this.uiSegmentSrv.newPlusButton();
  119. button.html = plusButton.html;
  120. button.value = plusButton.value;
  121. }
  122. getTableSegments() {
  123. return this.datasource
  124. .metricFindQuery(this.metaBuilder.buildTableQuery())
  125. .then(this.transformToSegments({}))
  126. .catch(this.handleQueryError.bind(this));
  127. }
  128. tableChanged() {
  129. this.target.table = this.tableSegment.value;
  130. this.panelCtrl.refresh();
  131. }
  132. getTimeColumnSegments() {
  133. return this.datasource
  134. .metricFindQuery(this.metaBuilder.buildColumnQuery('time'))
  135. .then(this.transformToSegments({}))
  136. .catch(this.handleQueryError.bind(this));
  137. }
  138. timeColumnChanged() {
  139. this.target.timeColumn = this.timeColumnSegment.value;
  140. this.panelCtrl.refresh();
  141. }
  142. getMetricColumnSegments() {
  143. return this.datasource
  144. .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
  145. .then(this.transformToSegments({ addNone: true }))
  146. .catch(this.handleQueryError.bind(this));
  147. }
  148. metricColumnChanged() {
  149. this.target.metricColumn = this.metricColumnSegment.value;
  150. this.panelCtrl.refresh();
  151. }
  152. onDataReceived(dataList) {
  153. this.lastQueryMeta = null;
  154. this.lastQueryError = null;
  155. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  156. if (anySeriesFromQuery) {
  157. this.lastQueryMeta = anySeriesFromQuery.meta;
  158. }
  159. }
  160. onDataError(err) {
  161. if (err.data && err.data.results) {
  162. let queryRes = err.data.results[this.target.refId];
  163. if (queryRes) {
  164. this.lastQueryMeta = queryRes.meta;
  165. this.lastQueryError = queryRes.error;
  166. }
  167. }
  168. }
  169. transformToSegments(config) {
  170. return results => {
  171. let segments = _.map(results, segment => {
  172. return this.uiSegmentSrv.newSegment({
  173. value: segment.text,
  174. expandable: segment.expandable,
  175. });
  176. });
  177. if (config.addTemplateVars) {
  178. for (let variable of this.templateSrv.variables) {
  179. let value;
  180. value = '$' + variable.name;
  181. if (config.templateQuoter && variable.multi === false) {
  182. value = config.templateQuoter(value);
  183. }
  184. segments.unshift(
  185. this.uiSegmentSrv.newSegment({
  186. type: 'template',
  187. value: value,
  188. expandable: true,
  189. })
  190. );
  191. }
  192. }
  193. if (config.addNone) {
  194. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  195. }
  196. return segments;
  197. };
  198. }
  199. addSelectPart(selectParts, item, subItem) {
  200. let partModel = sqlPart.create({ type: item.value });
  201. if (subItem) {
  202. partModel.params = [subItem.value];
  203. }
  204. let addAlias = false;
  205. switch (item.value) {
  206. case 'column':
  207. let parts = _.map(selectParts, function(part: any) {
  208. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  209. });
  210. this.selectParts.push(parts);
  211. break;
  212. case 'aggregate':
  213. // add group by if no group by yet
  214. if (this.target.group.length === 0) {
  215. this.addGroup('time', '1m');
  216. }
  217. case 'window':
  218. let index = _.findIndex(selectParts, (p: any) => p.def.type === item.value);
  219. if (index !== -1) {
  220. selectParts[index] = partModel;
  221. } else {
  222. selectParts.splice(1, 0, partModel);
  223. }
  224. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  225. addAlias = true;
  226. }
  227. break;
  228. case 'alias':
  229. addAlias = true;
  230. break;
  231. }
  232. if (addAlias) {
  233. // set initial alias name to column name
  234. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0]] });
  235. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  236. selectParts[selectParts.length - 1] = partModel;
  237. } else {
  238. selectParts.push(partModel);
  239. }
  240. }
  241. this.updatePersistedParts();
  242. this.panelCtrl.refresh();
  243. }
  244. removeSelectPart(selectParts, part) {
  245. if (part.def.type === 'column') {
  246. // remove all parts of column unless its last column
  247. if (this.selectParts.length > 1) {
  248. let modelsIndex = _.indexOf(this.selectParts, selectParts);
  249. this.selectParts.splice(modelsIndex, 1);
  250. }
  251. } else {
  252. let partIndex = _.indexOf(selectParts, part);
  253. selectParts.splice(partIndex, 1);
  254. }
  255. this.updatePersistedParts();
  256. }
  257. handleSelectPartEvent(selectParts, part, evt) {
  258. switch (evt.name) {
  259. case 'get-param-options': {
  260. switch (part.def.type) {
  261. case 'aggregate':
  262. return this.datasource
  263. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  264. .then(this.transformToSegments({}))
  265. .catch(this.handleQueryError.bind(this));
  266. case 'column':
  267. return this.datasource
  268. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  269. .then(this.transformToSegments({}))
  270. .catch(this.handleQueryError.bind(this));
  271. }
  272. }
  273. case 'part-param-changed': {
  274. this.panelCtrl.refresh();
  275. break;
  276. }
  277. case 'action': {
  278. this.removeSelectPart(selectParts, part);
  279. this.panelCtrl.refresh();
  280. break;
  281. }
  282. case 'get-part-actions': {
  283. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  284. }
  285. }
  286. }
  287. onGroupPartEvent(part, index, evt) {
  288. switch (evt.name) {
  289. case 'get-param-options': {
  290. return this.datasource
  291. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  292. .then(this.transformToSegments({}))
  293. .catch(this.handleQueryError.bind(this));
  294. }
  295. case 'part-param-changed': {
  296. this.panelCtrl.refresh();
  297. break;
  298. }
  299. case 'action': {
  300. this.removeGroup(part, index);
  301. this.panelCtrl.refresh();
  302. break;
  303. }
  304. case 'get-part-actions': {
  305. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  306. }
  307. }
  308. }
  309. addGroup(partType, value) {
  310. let params = [value];
  311. if (partType === 'time') {
  312. params = ['1m', 'none'];
  313. }
  314. let partModel = sqlPart.create({ type: partType, params: params });
  315. if (partType === 'time') {
  316. // put timeGroup at start
  317. this.groupParts.splice(0, 0, partModel);
  318. } else {
  319. this.groupParts.push(partModel);
  320. }
  321. // add aggregates when adding group by
  322. for (let selectParts of this.selectParts) {
  323. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  324. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  325. selectParts.splice(1, 0, aggregate);
  326. if (!selectParts.some(part => part.def.type === 'alias')) {
  327. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  328. selectParts.push(alias);
  329. }
  330. }
  331. }
  332. this.updatePersistedParts();
  333. }
  334. removeGroup(part, index) {
  335. if (part.def.type === 'time') {
  336. // remove aggregations
  337. this.selectParts = _.map(this.selectParts, (s: any) => {
  338. return _.filter(s, (part: any) => {
  339. if (part.def.type === 'aggregate') {
  340. return false;
  341. }
  342. return true;
  343. });
  344. });
  345. }
  346. this.groupParts.splice(index, 1);
  347. this.updatePersistedParts();
  348. }
  349. handleWherePartEvent(whereParts, part, evt, index) {
  350. switch (evt.name) {
  351. case 'get-param-options': {
  352. switch (evt.param.name) {
  353. case 'left':
  354. return this.datasource
  355. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  356. .then(this.transformToSegments({}))
  357. .catch(this.handleQueryError.bind(this));
  358. case 'right':
  359. return this.datasource
  360. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  361. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  362. .catch(this.handleQueryError.bind(this));
  363. case 'op':
  364. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  365. default:
  366. return this.$q.when([]);
  367. }
  368. }
  369. case 'part-param-changed': {
  370. this.panelCtrl.refresh();
  371. break;
  372. }
  373. case 'action': {
  374. // remove element
  375. whereParts.splice(index, 1);
  376. this.updatePersistedParts();
  377. this.panelCtrl.refresh();
  378. break;
  379. }
  380. case 'get-part-actions': {
  381. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  382. }
  383. }
  384. }
  385. getWhereOptions() {
  386. var options = [];
  387. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  388. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  389. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  390. return this.$q.when(options);
  391. }
  392. whereAddAction(part, index) {
  393. switch (this.whereAdd.type) {
  394. case 'macro': {
  395. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  396. break;
  397. }
  398. default: {
  399. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  400. }
  401. }
  402. this.updatePersistedParts();
  403. this.resetPlusButton(this.whereAdd);
  404. this.panelCtrl.refresh();
  405. }
  406. getGroupOptions() {
  407. return this.datasource
  408. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  409. .then(tags => {
  410. var options = [];
  411. if (!this.queryModel.hasTimeGroup()) {
  412. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  413. }
  414. for (let tag of tags) {
  415. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  416. }
  417. return options;
  418. })
  419. .catch(this.handleQueryError.bind(this));
  420. }
  421. onGroupAction() {
  422. switch (this.groupAdd.value) {
  423. default: {
  424. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  425. }
  426. }
  427. this.resetPlusButton(this.groupAdd);
  428. this.panelCtrl.refresh();
  429. }
  430. handleQueryError(err) {
  431. this.error = err.message || 'Failed to issue metric query';
  432. return [];
  433. }
  434. }