query_ctrl.ts 21 KB

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