query_ctrl.ts 18 KB

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