query_ctrl.ts 19 KB

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