query_ctrl.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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[0] = 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. case 'aggregate':
  252. // add group by if no group by yet
  253. if (this.target.group.length === 0) {
  254. this.addGroup('time', '1m');
  255. }
  256. let aggIndex = this.findAggregateIndex(selectParts);
  257. if (aggIndex !== -1) {
  258. // replace current aggregation
  259. selectParts[aggIndex] = partModel;
  260. } else {
  261. selectParts.splice(1, 0, partModel);
  262. }
  263. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  264. addAlias = true;
  265. }
  266. break;
  267. case 'moving_window':
  268. case 'window':
  269. let windowIndex = this.findWindowIndex(selectParts);
  270. if (windowIndex !== -1) {
  271. // replace current window function
  272. selectParts[windowIndex] = partModel;
  273. } else {
  274. let aggIndex = this.findAggregateIndex(selectParts);
  275. if (aggIndex !== -1) {
  276. selectParts.splice(aggIndex + 1, 0, partModel);
  277. } else {
  278. selectParts.splice(1, 0, partModel);
  279. }
  280. }
  281. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  282. addAlias = true;
  283. }
  284. break;
  285. case 'alias':
  286. addAlias = true;
  287. break;
  288. }
  289. if (addAlias) {
  290. // set initial alias name to column name
  291. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0]] });
  292. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  293. selectParts[selectParts.length - 1] = partModel;
  294. } else {
  295. selectParts.push(partModel);
  296. }
  297. }
  298. this.updatePersistedParts();
  299. this.panelCtrl.refresh();
  300. }
  301. removeSelectPart(selectParts, part) {
  302. if (part.def.type === 'column') {
  303. // remove all parts of column unless its last column
  304. if (this.selectParts.length > 1) {
  305. let modelsIndex = _.indexOf(this.selectParts, selectParts);
  306. this.selectParts.splice(modelsIndex, 1);
  307. }
  308. } else {
  309. let partIndex = _.indexOf(selectParts, part);
  310. selectParts.splice(partIndex, 1);
  311. }
  312. this.updatePersistedParts();
  313. }
  314. handleSelectPartEvent(selectParts, part, evt) {
  315. switch (evt.name) {
  316. case 'get-param-options': {
  317. switch (part.def.type) {
  318. case 'aggregate':
  319. return this.datasource
  320. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  321. .then(this.transformToSegments({}))
  322. .catch(this.handleQueryError.bind(this));
  323. case 'column':
  324. return this.datasource
  325. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  326. .then(this.transformToSegments({}))
  327. .catch(this.handleQueryError.bind(this));
  328. }
  329. }
  330. case 'part-param-changed': {
  331. this.panelCtrl.refresh();
  332. break;
  333. }
  334. case 'action': {
  335. this.removeSelectPart(selectParts, part);
  336. this.panelCtrl.refresh();
  337. break;
  338. }
  339. case 'get-part-actions': {
  340. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  341. }
  342. }
  343. }
  344. handleGroupPartEvent(part, index, evt) {
  345. switch (evt.name) {
  346. case 'get-param-options': {
  347. return this.datasource
  348. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  349. .then(this.transformToSegments({}))
  350. .catch(this.handleQueryError.bind(this));
  351. }
  352. case 'part-param-changed': {
  353. this.panelCtrl.refresh();
  354. break;
  355. }
  356. case 'action': {
  357. this.removeGroup(part, index);
  358. this.panelCtrl.refresh();
  359. break;
  360. }
  361. case 'get-part-actions': {
  362. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  363. }
  364. }
  365. }
  366. addGroup(partType, value) {
  367. let params = [value];
  368. if (partType === 'time') {
  369. params = ['1m', 'none'];
  370. }
  371. let partModel = sqlPart.create({ type: partType, params: params });
  372. if (partType === 'time') {
  373. // put timeGroup at start
  374. this.groupParts.splice(0, 0, partModel);
  375. } else {
  376. this.groupParts.push(partModel);
  377. }
  378. // add aggregates when adding group by
  379. for (let selectParts of this.selectParts) {
  380. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  381. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  382. selectParts.splice(1, 0, aggregate);
  383. if (!selectParts.some(part => part.def.type === 'alias')) {
  384. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  385. selectParts.push(alias);
  386. }
  387. }
  388. }
  389. this.updatePersistedParts();
  390. }
  391. removeGroup(part, index) {
  392. if (part.def.type === 'time') {
  393. // remove aggregations
  394. this.selectParts = _.map(this.selectParts, (s: any) => {
  395. return _.filter(s, (part: any) => {
  396. if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
  397. return false;
  398. }
  399. return true;
  400. });
  401. });
  402. }
  403. this.groupParts.splice(index, 1);
  404. this.updatePersistedParts();
  405. }
  406. handleWherePartEvent(whereParts, part, evt, index) {
  407. switch (evt.name) {
  408. case 'get-param-options': {
  409. switch (evt.param.name) {
  410. case 'left':
  411. return this.datasource
  412. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  413. .then(this.transformToSegments({}))
  414. .catch(this.handleQueryError.bind(this));
  415. case 'right':
  416. return this.datasource
  417. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  418. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  419. .catch(this.handleQueryError.bind(this));
  420. case 'op':
  421. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  422. default:
  423. return this.$q.when([]);
  424. }
  425. }
  426. case 'part-param-changed': {
  427. this.panelCtrl.refresh();
  428. break;
  429. }
  430. case 'action': {
  431. // remove element
  432. whereParts.splice(index, 1);
  433. this.updatePersistedParts();
  434. this.panelCtrl.refresh();
  435. break;
  436. }
  437. case 'get-part-actions': {
  438. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  439. }
  440. }
  441. }
  442. getWhereOptions() {
  443. var options = [];
  444. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  445. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  446. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  447. return this.$q.when(options);
  448. }
  449. addWhereAction(part, index) {
  450. switch (this.whereAdd.type) {
  451. case 'macro': {
  452. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  453. break;
  454. }
  455. default: {
  456. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  457. }
  458. }
  459. this.updatePersistedParts();
  460. this.resetPlusButton(this.whereAdd);
  461. this.panelCtrl.refresh();
  462. }
  463. getGroupOptions() {
  464. return this.datasource
  465. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  466. .then(tags => {
  467. var options = [];
  468. if (!this.queryModel.hasTimeGroup()) {
  469. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  470. }
  471. for (let tag of tags) {
  472. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  473. }
  474. return options;
  475. })
  476. .catch(this.handleQueryError.bind(this));
  477. }
  478. addGroupAction() {
  479. switch (this.groupAdd.value) {
  480. default: {
  481. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  482. }
  483. }
  484. this.resetPlusButton(this.groupAdd);
  485. this.panelCtrl.refresh();
  486. }
  487. handleQueryError(err) {
  488. this.error = err.message || 'Failed to issue metric query';
  489. return [];
  490. }
  491. }