query_ctrl.ts 16 KB

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