query_ctrl.ts 21 KB

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