query_ctrl.ts 16 KB

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