query_ctrl.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. this.target.rawQuery = true;
  51. } else {
  52. this.target.rawSql = defaultQuery;
  53. this.datasource.metricFindQuery(this.metaBuilder.findMetricTable()).then(result => {
  54. if (result.length > 0) {
  55. this.target.table = result[0].text;
  56. let segment = this.uiSegmentSrv.newSegment(this.target.table);
  57. this.tableSegment.html = segment.html;
  58. this.tableSegment.value = segment.value;
  59. this.target.timeColumn = result[1].text;
  60. segment = this.uiSegmentSrv.newSegment(this.target.timeColumn);
  61. this.timeColumnSegment.html = segment.html;
  62. this.timeColumnSegment.value = segment.value;
  63. this.target.timeColumnType = 'timestamp';
  64. this.target.select = [[{ type: 'column', params: [result[2].text] }]];
  65. this.updateProjection();
  66. this.panelCtrl.refresh();
  67. }
  68. });
  69. }
  70. }
  71. if (!this.target.table) {
  72. this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
  73. } else {
  74. this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
  75. }
  76. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  77. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  78. this.buildSelectMenu();
  79. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  80. this.groupAdd = this.uiSegmentSrv.newPlusButton();
  81. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  82. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  83. }
  84. updateProjection() {
  85. this.selectParts = _.map(this.target.select, function(parts: any) {
  86. return _.map(parts, sqlPart.create).filter(n => n);
  87. });
  88. this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
  89. this.groupParts = _.map(this.target.group, sqlPart.create).filter(n => n);
  90. }
  91. updatePersistedParts() {
  92. this.target.select = _.map(this.selectParts, function(selectParts) {
  93. return _.map(selectParts, function(part: any) {
  94. return { type: part.def.type, datatype: part.datatype, params: part.params };
  95. });
  96. });
  97. this.target.where = _.map(this.whereParts, function(part: any) {
  98. return { type: part.def.type, datatype: part.datatype, name: part.name, params: part.params };
  99. });
  100. this.target.group = _.map(this.groupParts, function(part: any) {
  101. return { type: part.def.type, datatype: part.datatype, params: part.params };
  102. });
  103. }
  104. buildSelectMenu() {
  105. this.selectMenu = [];
  106. let aggregates = {
  107. text: 'Aggregate Functions',
  108. value: 'aggregate',
  109. submenu: [
  110. { text: 'Average', value: 'avg' },
  111. { text: 'Count', value: 'count' },
  112. { text: 'Maximum', value: 'max' },
  113. { text: 'Minimum', value: 'min' },
  114. { text: 'Sum', value: 'sum' },
  115. { text: 'Standard deviation', value: 'stddev' },
  116. { text: 'Variance', value: 'variance' },
  117. ],
  118. };
  119. // first and last aggregate are timescaledb specific
  120. if (this.datasource.jsonData.timescaledb === true) {
  121. aggregates.submenu.push({ text: 'First', value: 'first' });
  122. aggregates.submenu.push({ text: 'Last', value: 'last' });
  123. }
  124. this.selectMenu.push(aggregates);
  125. // ordered set aggregates require postgres 9.4+
  126. if (this.datasource.jsonData.postgresVersion >= 904) {
  127. let aggregates2 = {
  128. text: 'Ordered-Set Aggregate Functions',
  129. value: 'percentile',
  130. submenu: [
  131. { text: 'Percentile (continuous)', value: 'percentile_cont' },
  132. { text: 'Percentile (discrete)', value: 'percentile_disc' },
  133. ],
  134. };
  135. this.selectMenu.push(aggregates2);
  136. }
  137. let windows = {
  138. text: 'Window Functions',
  139. value: 'window',
  140. submenu: [
  141. { text: 'Increase', value: 'increase' },
  142. { text: 'Rate', value: 'rate' },
  143. { text: 'Sum', value: 'sum' },
  144. { text: 'Moving Average', value: 'avg', type: 'moving_window' },
  145. ],
  146. };
  147. this.selectMenu.push(windows);
  148. this.selectMenu.push({ text: 'Alias', value: 'alias' });
  149. this.selectMenu.push({ text: 'Column', value: 'column' });
  150. }
  151. toggleEditorMode() {
  152. if (this.target.rawQuery) {
  153. appEvents.emit('confirm-modal', {
  154. title: 'Warning',
  155. text2: 'Switching to query builder may overwrite your raw SQL.',
  156. icon: 'fa-exclamation',
  157. yesText: 'Switch',
  158. onConfirm: () => {
  159. this.target.rawQuery = !this.target.rawQuery;
  160. },
  161. });
  162. } else {
  163. this.target.rawQuery = !this.target.rawQuery;
  164. }
  165. }
  166. resetPlusButton(button) {
  167. let plusButton = this.uiSegmentSrv.newPlusButton();
  168. button.html = plusButton.html;
  169. button.value = plusButton.value;
  170. }
  171. getTableSegments() {
  172. return this.datasource
  173. .metricFindQuery(this.metaBuilder.buildTableQuery())
  174. .then(this.transformToSegments({}))
  175. .catch(this.handleQueryError.bind(this));
  176. }
  177. tableChanged() {
  178. this.target.table = this.tableSegment.value;
  179. this.target.where = [];
  180. this.target.group = [];
  181. this.updateProjection();
  182. let task1 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('time')).then(result => {
  183. // check if time column is still valid
  184. if (result.length > 0 && !_.find(result, (r: any) => r.text === this.target.timeColumn)) {
  185. let segment = this.uiSegmentSrv.newSegment(result[0].text);
  186. this.timeColumnSegment.html = segment.html;
  187. this.timeColumnSegment.value = segment.value;
  188. }
  189. return this.timeColumnChanged(false);
  190. });
  191. let task2 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('value')).then(result => {
  192. if (result.length > 0) {
  193. this.target.select = [[{ type: 'column', params: [result[0].text] }]];
  194. this.updateProjection();
  195. }
  196. });
  197. this.$q.all([task1, task2]).then(() => {
  198. this.panelCtrl.refresh();
  199. });
  200. }
  201. getTimeColumnSegments() {
  202. return this.datasource
  203. .metricFindQuery(this.metaBuilder.buildColumnQuery('time'))
  204. .then(this.transformToSegments({}))
  205. .catch(this.handleQueryError.bind(this));
  206. }
  207. timeColumnChanged(refresh?: boolean) {
  208. this.target.timeColumn = this.timeColumnSegment.value;
  209. return this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(this.target.timeColumn)).then(result => {
  210. if (result.length === 1) {
  211. if (this.target.timeColumnType !== result[0].text) {
  212. this.target.timeColumnType = result[0].text;
  213. }
  214. let partModel;
  215. if (this.queryModel.hasUnixEpochTimecolumn()) {
  216. partModel = sqlPart.create({ type: 'macro', name: '$__unixEpochFilter', params: [] });
  217. } else {
  218. partModel = sqlPart.create({ type: 'macro', name: '$__timeFilter', params: [] });
  219. }
  220. if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
  221. // replace current macro
  222. this.whereParts[0] = partModel;
  223. } else {
  224. this.whereParts.splice(0, 0, partModel);
  225. }
  226. }
  227. this.updatePersistedParts();
  228. if (refresh !== false) {
  229. this.panelCtrl.refresh();
  230. }
  231. });
  232. }
  233. getMetricColumnSegments() {
  234. return this.datasource
  235. .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
  236. .then(this.transformToSegments({ addNone: true }))
  237. .catch(this.handleQueryError.bind(this));
  238. }
  239. metricColumnChanged() {
  240. this.target.metricColumn = this.metricColumnSegment.value;
  241. this.panelCtrl.refresh();
  242. }
  243. onDataReceived(dataList) {
  244. this.lastQueryMeta = null;
  245. this.lastQueryError = null;
  246. const anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  247. if (anySeriesFromQuery) {
  248. this.lastQueryMeta = anySeriesFromQuery.meta;
  249. }
  250. }
  251. onDataError(err) {
  252. if (err.data && err.data.results) {
  253. const queryRes = err.data.results[this.target.refId];
  254. if (queryRes) {
  255. this.lastQueryMeta = queryRes.meta;
  256. this.lastQueryError = queryRes.error;
  257. }
  258. }
  259. }
  260. transformToSegments(config) {
  261. return results => {
  262. let segments = _.map(results, segment => {
  263. return this.uiSegmentSrv.newSegment({
  264. value: segment.text,
  265. expandable: segment.expandable,
  266. });
  267. });
  268. if (config.addTemplateVars) {
  269. for (let variable of this.templateSrv.variables) {
  270. let value;
  271. value = '$' + variable.name;
  272. if (config.templateQuoter && variable.multi === false) {
  273. value = config.templateQuoter(value);
  274. }
  275. segments.unshift(
  276. this.uiSegmentSrv.newSegment({
  277. type: 'template',
  278. value: value,
  279. expandable: true,
  280. })
  281. );
  282. }
  283. }
  284. if (config.addNone) {
  285. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  286. }
  287. return segments;
  288. };
  289. }
  290. findAggregateIndex(selectParts) {
  291. return _.findIndex(selectParts, (p: any) => p.def.type === 'aggregate' || p.def.type === 'percentile');
  292. }
  293. findWindowIndex(selectParts) {
  294. return _.findIndex(selectParts, (p: any) => p.def.type === 'window' || p.def.type === 'moving_window');
  295. }
  296. addSelectPart(selectParts, item, subItem) {
  297. let partType = item.value;
  298. if (subItem && subItem.type) {
  299. partType = subItem.type;
  300. }
  301. let partModel = sqlPart.create({ type: partType });
  302. if (subItem) {
  303. partModel.params[0] = subItem.value;
  304. }
  305. let addAlias = false;
  306. switch (partType) {
  307. case 'column':
  308. let parts = _.map(selectParts, function(part: any) {
  309. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  310. });
  311. this.selectParts.push(parts);
  312. break;
  313. case 'percentile':
  314. case 'aggregate':
  315. // add group by if no group by yet
  316. if (this.target.group.length === 0) {
  317. this.addGroup('time', '$__interval');
  318. }
  319. let aggIndex = this.findAggregateIndex(selectParts);
  320. if (aggIndex !== -1) {
  321. // replace current aggregation
  322. selectParts[aggIndex] = partModel;
  323. } else {
  324. selectParts.splice(1, 0, partModel);
  325. }
  326. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  327. addAlias = true;
  328. }
  329. break;
  330. case 'moving_window':
  331. case 'window':
  332. let windowIndex = this.findWindowIndex(selectParts);
  333. if (windowIndex !== -1) {
  334. // replace current window function
  335. selectParts[windowIndex] = partModel;
  336. } else {
  337. let aggIndex = this.findAggregateIndex(selectParts);
  338. if (aggIndex !== -1) {
  339. selectParts.splice(aggIndex + 1, 0, partModel);
  340. } else {
  341. selectParts.splice(1, 0, partModel);
  342. }
  343. }
  344. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  345. addAlias = true;
  346. }
  347. break;
  348. case 'alias':
  349. addAlias = true;
  350. break;
  351. }
  352. if (addAlias) {
  353. // set initial alias name to column name
  354. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0].replace(/"/g, '')] });
  355. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  356. selectParts[selectParts.length - 1] = partModel;
  357. } else {
  358. selectParts.push(partModel);
  359. }
  360. }
  361. this.updatePersistedParts();
  362. this.panelCtrl.refresh();
  363. }
  364. removeSelectPart(selectParts, part) {
  365. if (part.def.type === 'column') {
  366. // remove all parts of column unless its last column
  367. if (this.selectParts.length > 1) {
  368. let modelsIndex = _.indexOf(this.selectParts, selectParts);
  369. this.selectParts.splice(modelsIndex, 1);
  370. }
  371. } else {
  372. let partIndex = _.indexOf(selectParts, part);
  373. selectParts.splice(partIndex, 1);
  374. }
  375. this.updatePersistedParts();
  376. }
  377. handleSelectPartEvent(selectParts, part, evt) {
  378. switch (evt.name) {
  379. case 'get-param-options': {
  380. switch (part.def.type) {
  381. case 'aggregate':
  382. return this.datasource
  383. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  384. .then(this.transformToSegments({}))
  385. .catch(this.handleQueryError.bind(this));
  386. case 'column':
  387. return this.datasource
  388. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  389. .then(this.transformToSegments({}))
  390. .catch(this.handleQueryError.bind(this));
  391. }
  392. }
  393. case 'part-param-changed': {
  394. this.updatePersistedParts();
  395. this.panelCtrl.refresh();
  396. break;
  397. }
  398. case 'action': {
  399. this.removeSelectPart(selectParts, part);
  400. this.panelCtrl.refresh();
  401. break;
  402. }
  403. case 'get-part-actions': {
  404. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  405. }
  406. }
  407. }
  408. handleGroupPartEvent(part, index, evt) {
  409. switch (evt.name) {
  410. case 'get-param-options': {
  411. return this.datasource
  412. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  413. .then(this.transformToSegments({}))
  414. .catch(this.handleQueryError.bind(this));
  415. }
  416. case 'part-param-changed': {
  417. this.updatePersistedParts();
  418. this.panelCtrl.refresh();
  419. break;
  420. }
  421. case 'action': {
  422. this.removeGroup(part, index);
  423. this.panelCtrl.refresh();
  424. break;
  425. }
  426. case 'get-part-actions': {
  427. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  428. }
  429. }
  430. }
  431. addGroup(partType, value) {
  432. let params = [value];
  433. if (partType === 'time') {
  434. params = ['$__interval', 'none'];
  435. }
  436. let partModel = sqlPart.create({ type: partType, params: params });
  437. if (partType === 'time') {
  438. // put timeGroup at start
  439. this.groupParts.splice(0, 0, partModel);
  440. } else {
  441. this.groupParts.push(partModel);
  442. }
  443. // add aggregates when adding group by
  444. for (let selectParts of this.selectParts) {
  445. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  446. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  447. selectParts.splice(1, 0, aggregate);
  448. if (!selectParts.some(part => part.def.type === 'alias')) {
  449. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  450. selectParts.push(alias);
  451. }
  452. }
  453. }
  454. this.updatePersistedParts();
  455. }
  456. removeGroup(part, index) {
  457. if (part.def.type === 'time') {
  458. // remove aggregations
  459. this.selectParts = _.map(this.selectParts, (s: any) => {
  460. return _.filter(s, (part: any) => {
  461. if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
  462. return false;
  463. }
  464. return true;
  465. });
  466. });
  467. }
  468. this.groupParts.splice(index, 1);
  469. this.updatePersistedParts();
  470. }
  471. handleWherePartEvent(whereParts, part, evt, index) {
  472. switch (evt.name) {
  473. case 'get-param-options': {
  474. switch (evt.param.name) {
  475. case 'left':
  476. return this.datasource
  477. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  478. .then(this.transformToSegments({}))
  479. .catch(this.handleQueryError.bind(this));
  480. case 'right':
  481. if (['int4', 'int8', 'float4', 'float8', 'timestamp', 'timestamptz'].indexOf(part.datatype) > -1) {
  482. // don't do value lookups for numerical fields
  483. return this.$q.when([]);
  484. } else {
  485. return this.datasource
  486. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  487. .then(
  488. this.transformToSegments({
  489. addTemplateVars: true,
  490. templateQuoter: (v: string) => {
  491. return this.queryModel.quoteLiteral(v);
  492. },
  493. })
  494. )
  495. .catch(this.handleQueryError.bind(this));
  496. }
  497. case 'op':
  498. return this.$q.when(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));
  499. default:
  500. return this.$q.when([]);
  501. }
  502. }
  503. case 'part-param-changed': {
  504. this.updatePersistedParts();
  505. this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(part.params[0])).then((d: any) => {
  506. if (d.length === 1) {
  507. part.datatype = d[0].text;
  508. }
  509. });
  510. this.panelCtrl.refresh();
  511. break;
  512. }
  513. case 'action': {
  514. // remove element
  515. whereParts.splice(index, 1);
  516. this.updatePersistedParts();
  517. this.panelCtrl.refresh();
  518. break;
  519. }
  520. case 'get-part-actions': {
  521. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  522. }
  523. }
  524. }
  525. getWhereOptions() {
  526. var options = [];
  527. if (this.queryModel.hasUnixEpochTimecolumn()) {
  528. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  529. } else {
  530. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  531. }
  532. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  533. return this.$q.when(options);
  534. }
  535. addWhereAction(part, index) {
  536. switch (this.whereAdd.type) {
  537. case 'macro': {
  538. let partModel = sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] });
  539. if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
  540. // replace current macro
  541. this.whereParts[0] = partModel;
  542. } else {
  543. this.whereParts.splice(0, 0, partModel);
  544. }
  545. break;
  546. }
  547. default: {
  548. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  549. }
  550. }
  551. this.updatePersistedParts();
  552. this.resetPlusButton(this.whereAdd);
  553. this.panelCtrl.refresh();
  554. }
  555. getGroupOptions() {
  556. return this.datasource
  557. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  558. .then(tags => {
  559. var options = [];
  560. if (!this.queryModel.hasTimeGroup()) {
  561. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time($__interval,none)' }));
  562. }
  563. for (let tag of tags) {
  564. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  565. }
  566. return options;
  567. })
  568. .catch(this.handleQueryError.bind(this));
  569. }
  570. addGroupAction() {
  571. switch (this.groupAdd.value) {
  572. default: {
  573. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  574. }
  575. }
  576. this.resetPlusButton(this.groupAdd);
  577. this.panelCtrl.refresh();
  578. }
  579. handleQueryError(err) {
  580. this.error = err.message || 'Failed to issue metric query';
  581. return [];
  582. }
  583. }