query_ctrl.ts 17 KB

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