query_ctrl.ts 15 KB

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