query_ctrl.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(this.target.timeColumn)).then(result => {
  169. if (result.length === 1) {
  170. this.target.timeColumnType = result[0];
  171. }
  172. });
  173. this.panelCtrl.refresh();
  174. }
  175. getMetricColumnSegments() {
  176. return this.datasource
  177. .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
  178. .then(this.transformToSegments({ addNone: true }))
  179. .catch(this.handleQueryError.bind(this));
  180. }
  181. metricColumnChanged() {
  182. this.target.metricColumn = this.metricColumnSegment.value;
  183. this.panelCtrl.refresh();
  184. }
  185. onDataReceived(dataList) {
  186. this.lastQueryMeta = null;
  187. this.lastQueryError = null;
  188. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  189. if (anySeriesFromQuery) {
  190. this.lastQueryMeta = anySeriesFromQuery.meta;
  191. }
  192. }
  193. onDataError(err) {
  194. if (err.data && err.data.results) {
  195. let queryRes = err.data.results[this.target.refId];
  196. if (queryRes) {
  197. this.lastQueryMeta = queryRes.meta;
  198. this.lastQueryError = queryRes.error;
  199. }
  200. }
  201. }
  202. transformToSegments(config) {
  203. return results => {
  204. let segments = _.map(results, segment => {
  205. return this.uiSegmentSrv.newSegment({
  206. value: segment.text,
  207. expandable: segment.expandable,
  208. });
  209. });
  210. if (config.addTemplateVars) {
  211. for (let variable of this.templateSrv.variables) {
  212. let value;
  213. value = '$' + variable.name;
  214. if (config.templateQuoter && variable.multi === false) {
  215. value = config.templateQuoter(value);
  216. }
  217. segments.unshift(
  218. this.uiSegmentSrv.newSegment({
  219. type: 'template',
  220. value: value,
  221. expandable: true,
  222. })
  223. );
  224. }
  225. }
  226. if (config.addNone) {
  227. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  228. }
  229. return segments;
  230. };
  231. }
  232. findAggregateIndex(selectParts) {
  233. return _.findIndex(selectParts, (p: any) => p.def.type === 'aggregate' || p.def.type === 'percentile');
  234. }
  235. findWindowIndex(selectParts) {
  236. return _.findIndex(selectParts, (p: any) => p.def.type === 'window' || p.def.type === 'moving_window');
  237. }
  238. addSelectPart(selectParts, item, subItem) {
  239. let partType = item.value;
  240. if (subItem && subItem.type) {
  241. partType = subItem.type;
  242. }
  243. let partModel = sqlPart.create({ type: partType });
  244. if (subItem) {
  245. partModel.params[0] = subItem.value;
  246. }
  247. let addAlias = false;
  248. switch (partType) {
  249. case 'column':
  250. let parts = _.map(selectParts, function(part: any) {
  251. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  252. });
  253. this.selectParts.push(parts);
  254. break;
  255. case 'percentile':
  256. case 'aggregate':
  257. // add group by if no group by yet
  258. if (this.target.group.length === 0) {
  259. this.addGroup('time', '1m');
  260. }
  261. let aggIndex = this.findAggregateIndex(selectParts);
  262. if (aggIndex !== -1) {
  263. // replace current aggregation
  264. selectParts[aggIndex] = partModel;
  265. } else {
  266. selectParts.splice(1, 0, partModel);
  267. }
  268. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  269. addAlias = true;
  270. }
  271. break;
  272. case 'moving_window':
  273. case 'window':
  274. let windowIndex = this.findWindowIndex(selectParts);
  275. if (windowIndex !== -1) {
  276. // replace current window function
  277. selectParts[windowIndex] = partModel;
  278. } else {
  279. let aggIndex = this.findAggregateIndex(selectParts);
  280. if (aggIndex !== -1) {
  281. selectParts.splice(aggIndex + 1, 0, partModel);
  282. } else {
  283. selectParts.splice(1, 0, partModel);
  284. }
  285. }
  286. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  287. addAlias = true;
  288. }
  289. break;
  290. case 'alias':
  291. addAlias = true;
  292. break;
  293. }
  294. if (addAlias) {
  295. // set initial alias name to column name
  296. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0]] });
  297. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  298. selectParts[selectParts.length - 1] = partModel;
  299. } else {
  300. selectParts.push(partModel);
  301. }
  302. }
  303. this.updatePersistedParts();
  304. this.panelCtrl.refresh();
  305. }
  306. removeSelectPart(selectParts, part) {
  307. if (part.def.type === 'column') {
  308. // remove all parts of column unless its last column
  309. if (this.selectParts.length > 1) {
  310. let modelsIndex = _.indexOf(this.selectParts, selectParts);
  311. this.selectParts.splice(modelsIndex, 1);
  312. }
  313. } else {
  314. let partIndex = _.indexOf(selectParts, part);
  315. selectParts.splice(partIndex, 1);
  316. }
  317. this.updatePersistedParts();
  318. }
  319. handleSelectPartEvent(selectParts, part, evt) {
  320. switch (evt.name) {
  321. case 'get-param-options': {
  322. switch (part.def.type) {
  323. case 'aggregate':
  324. return this.datasource
  325. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  326. .then(this.transformToSegments({}))
  327. .catch(this.handleQueryError.bind(this));
  328. case 'column':
  329. return this.datasource
  330. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  331. .then(this.transformToSegments({}))
  332. .catch(this.handleQueryError.bind(this));
  333. }
  334. }
  335. case 'part-param-changed': {
  336. this.panelCtrl.refresh();
  337. break;
  338. }
  339. case 'action': {
  340. this.removeSelectPart(selectParts, part);
  341. this.panelCtrl.refresh();
  342. break;
  343. }
  344. case 'get-part-actions': {
  345. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  346. }
  347. }
  348. }
  349. handleGroupPartEvent(part, index, evt) {
  350. switch (evt.name) {
  351. case 'get-param-options': {
  352. return this.datasource
  353. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  354. .then(this.transformToSegments({}))
  355. .catch(this.handleQueryError.bind(this));
  356. }
  357. case 'part-param-changed': {
  358. this.panelCtrl.refresh();
  359. break;
  360. }
  361. case 'action': {
  362. this.removeGroup(part, index);
  363. this.panelCtrl.refresh();
  364. break;
  365. }
  366. case 'get-part-actions': {
  367. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  368. }
  369. }
  370. }
  371. addGroup(partType, value) {
  372. let params = [value];
  373. if (partType === 'time') {
  374. params = ['1m', 'none'];
  375. }
  376. let partModel = sqlPart.create({ type: partType, params: params });
  377. if (partType === 'time') {
  378. // put timeGroup at start
  379. this.groupParts.splice(0, 0, partModel);
  380. } else {
  381. this.groupParts.push(partModel);
  382. }
  383. // add aggregates when adding group by
  384. for (let selectParts of this.selectParts) {
  385. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  386. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  387. selectParts.splice(1, 0, aggregate);
  388. if (!selectParts.some(part => part.def.type === 'alias')) {
  389. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  390. selectParts.push(alias);
  391. }
  392. }
  393. }
  394. this.updatePersistedParts();
  395. }
  396. removeGroup(part, index) {
  397. if (part.def.type === 'time') {
  398. // remove aggregations
  399. this.selectParts = _.map(this.selectParts, (s: any) => {
  400. return _.filter(s, (part: any) => {
  401. if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
  402. return false;
  403. }
  404. return true;
  405. });
  406. });
  407. }
  408. this.groupParts.splice(index, 1);
  409. this.updatePersistedParts();
  410. }
  411. handleWherePartEvent(whereParts, part, evt, index) {
  412. switch (evt.name) {
  413. case 'get-param-options': {
  414. switch (evt.param.name) {
  415. case 'left':
  416. return this.datasource
  417. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  418. .then(this.transformToSegments({}))
  419. .catch(this.handleQueryError.bind(this));
  420. case 'right':
  421. return this.datasource
  422. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  423. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  424. .catch(this.handleQueryError.bind(this));
  425. case 'op':
  426. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  427. default:
  428. return this.$q.when([]);
  429. }
  430. }
  431. case 'part-param-changed': {
  432. this.panelCtrl.refresh();
  433. break;
  434. }
  435. case 'action': {
  436. // remove element
  437. whereParts.splice(index, 1);
  438. this.updatePersistedParts();
  439. this.panelCtrl.refresh();
  440. break;
  441. }
  442. case 'get-part-actions': {
  443. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  444. }
  445. }
  446. }
  447. getWhereOptions() {
  448. var options = [];
  449. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  450. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  451. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  452. return this.$q.when(options);
  453. }
  454. addWhereAction(part, index) {
  455. switch (this.whereAdd.type) {
  456. case 'macro': {
  457. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  458. break;
  459. }
  460. default: {
  461. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  462. }
  463. }
  464. this.updatePersistedParts();
  465. this.resetPlusButton(this.whereAdd);
  466. this.panelCtrl.refresh();
  467. }
  468. getGroupOptions() {
  469. return this.datasource
  470. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  471. .then(tags => {
  472. var options = [];
  473. if (!this.queryModel.hasTimeGroup()) {
  474. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  475. }
  476. for (let tag of tags) {
  477. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  478. }
  479. return options;
  480. })
  481. .catch(this.handleQueryError.bind(this));
  482. }
  483. addGroupAction() {
  484. switch (this.groupAdd.value) {
  485. default: {
  486. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  487. }
  488. }
  489. this.resetPlusButton(this.groupAdd);
  490. this.panelCtrl.refresh();
  491. }
  492. handleQueryError(err) {
  493. this.error = err.message || 'Failed to issue metric query';
  494. return [];
  495. }
  496. }