query_ctrl.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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, datatype: part.datatype, params: part.params };
  78. });
  79. });
  80. this.target.where = _.map(this.whereParts, function(part: any) {
  81. return { type: part.def.type, datatype: part.datatype, name: part.name, params: part.params };
  82. });
  83. this.target.group = _.map(this.groupParts, function(part: any) {
  84. return { type: part.def.type, datatype: part.datatype, 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.updatePersistedParts();
  341. this.panelCtrl.refresh();
  342. break;
  343. }
  344. case 'action': {
  345. this.removeSelectPart(selectParts, part);
  346. this.panelCtrl.refresh();
  347. break;
  348. }
  349. case 'get-part-actions': {
  350. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  351. }
  352. }
  353. }
  354. handleGroupPartEvent(part, index, evt) {
  355. switch (evt.name) {
  356. case 'get-param-options': {
  357. return this.datasource
  358. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  359. .then(this.transformToSegments({}))
  360. .catch(this.handleQueryError.bind(this));
  361. }
  362. case 'part-param-changed': {
  363. this.updatePersistedParts();
  364. this.panelCtrl.refresh();
  365. break;
  366. }
  367. case 'action': {
  368. this.removeGroup(part, index);
  369. this.panelCtrl.refresh();
  370. break;
  371. }
  372. case 'get-part-actions': {
  373. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  374. }
  375. }
  376. }
  377. addGroup(partType, value) {
  378. let params = [value];
  379. if (partType === 'time') {
  380. params = ['1m', 'none'];
  381. }
  382. let partModel = sqlPart.create({ type: partType, params: params });
  383. if (partType === 'time') {
  384. // put timeGroup at start
  385. this.groupParts.splice(0, 0, partModel);
  386. } else {
  387. this.groupParts.push(partModel);
  388. }
  389. // add aggregates when adding group by
  390. for (let selectParts of this.selectParts) {
  391. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  392. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  393. selectParts.splice(1, 0, aggregate);
  394. if (!selectParts.some(part => part.def.type === 'alias')) {
  395. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  396. selectParts.push(alias);
  397. }
  398. }
  399. }
  400. this.updatePersistedParts();
  401. }
  402. removeGroup(part, index) {
  403. if (part.def.type === 'time') {
  404. // remove aggregations
  405. this.selectParts = _.map(this.selectParts, (s: any) => {
  406. return _.filter(s, (part: any) => {
  407. if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
  408. return false;
  409. }
  410. return true;
  411. });
  412. });
  413. }
  414. this.groupParts.splice(index, 1);
  415. this.updatePersistedParts();
  416. }
  417. handleWherePartEvent(whereParts, part, evt, index) {
  418. switch (evt.name) {
  419. case 'get-param-options': {
  420. switch (evt.param.name) {
  421. case 'left':
  422. return this.datasource
  423. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  424. .then(this.transformToSegments({}))
  425. .catch(this.handleQueryError.bind(this));
  426. case 'right':
  427. if (['int4', 'int8', 'float4', 'float8', 'timestamp', 'timestamptz'].indexOf(part.datatype) > -1) {
  428. // don't do value lookups for numerical fields
  429. return this.$q.when([]);
  430. } else {
  431. return this.datasource
  432. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  433. .then(
  434. this.transformToSegments({
  435. addTemplateVars: true,
  436. templateQuoter: (v: string) => {
  437. return this.queryModel.quoteLiteral(v);
  438. },
  439. })
  440. )
  441. .catch(this.handleQueryError.bind(this));
  442. }
  443. case 'op':
  444. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  445. default:
  446. return this.$q.when([]);
  447. }
  448. }
  449. case 'part-param-changed': {
  450. this.updatePersistedParts();
  451. this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(part.params[0])).then((d: any) => {
  452. if (d.length === 1) {
  453. part.datatype = d[0].text;
  454. }
  455. });
  456. this.panelCtrl.refresh();
  457. break;
  458. }
  459. case 'action': {
  460. // remove element
  461. whereParts.splice(index, 1);
  462. this.updatePersistedParts();
  463. this.panelCtrl.refresh();
  464. break;
  465. }
  466. case 'get-part-actions': {
  467. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  468. }
  469. }
  470. }
  471. getWhereOptions() {
  472. var options = [];
  473. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  474. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  475. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  476. return this.$q.when(options);
  477. }
  478. addWhereAction(part, index) {
  479. switch (this.whereAdd.type) {
  480. case 'macro': {
  481. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  482. break;
  483. }
  484. default: {
  485. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  486. }
  487. }
  488. this.updatePersistedParts();
  489. this.resetPlusButton(this.whereAdd);
  490. this.panelCtrl.refresh();
  491. }
  492. getGroupOptions() {
  493. return this.datasource
  494. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  495. .then(tags => {
  496. var options = [];
  497. if (!this.queryModel.hasTimeGroup()) {
  498. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  499. }
  500. for (let tag of tags) {
  501. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  502. }
  503. return options;
  504. })
  505. .catch(this.handleQueryError.bind(this));
  506. }
  507. addGroupAction() {
  508. switch (this.groupAdd.value) {
  509. default: {
  510. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  511. }
  512. }
  513. this.resetPlusButton(this.groupAdd);
  514. this.panelCtrl.refresh();
  515. }
  516. handleQueryError(err) {
  517. this.error = err.message || 'Failed to issue metric query';
  518. return [];
  519. }
  520. }