query_ctrl.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. selectModels: SqlPart[][];
  33. groupByParts: SqlPart[][];
  34. whereParts: SqlPart[][];
  35. groupByAdd: 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.groupByAdd = 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.selectModels = _.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.groupByParts = _.map(this.target.groupBy, sqlPart.create).filter(n => n);
  72. }
  73. updatePersistedParts() {
  74. this.target.select = _.map(this.selectModels, 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.groupBy = _.map(this.groupByParts, function(part: any) {
  83. return { type: part.def.type, params: part.params };
  84. });
  85. }
  86. buildSelectMenu() {
  87. this.selectMenu = [
  88. { text: 'Aggregate', value: 'aggregate' },
  89. { text: 'Special', value: 'special' },
  90. { text: 'Alias', value: 'alias' },
  91. { text: 'Column', value: 'column' },
  92. ];
  93. }
  94. toggleEditorMode() {
  95. this.target.rawQuery = !this.target.rawQuery;
  96. }
  97. resetPlusButton(button) {
  98. let plusButton = this.uiSegmentSrv.newPlusButton();
  99. button.html = plusButton.html;
  100. button.value = plusButton.value;
  101. }
  102. getTableSegments() {
  103. return this.datasource
  104. .metricFindQuery(this.metaBuilder.buildTableQuery())
  105. .then(this.transformToSegments({}))
  106. .catch(this.handleQueryError.bind(this));
  107. }
  108. tableChanged() {
  109. this.target.table = this.tableSegment.value;
  110. this.panelCtrl.refresh();
  111. }
  112. getTimeColumnSegments() {
  113. return this.datasource
  114. .metricFindQuery(this.metaBuilder.buildColumnQuery('time'))
  115. .then(this.transformToSegments({}))
  116. .catch(this.handleQueryError.bind(this));
  117. }
  118. timeColumnChanged() {
  119. this.target.timeColumn = this.timeColumnSegment.value;
  120. this.panelCtrl.refresh();
  121. }
  122. getMetricColumnSegments() {
  123. return this.datasource
  124. .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
  125. .then(this.transformToSegments({ addNone: true }))
  126. .catch(this.handleQueryError.bind(this));
  127. }
  128. metricColumnChanged() {
  129. this.target.metricColumn = this.metricColumnSegment.value;
  130. this.panelCtrl.refresh();
  131. }
  132. onDataReceived(dataList) {
  133. this.lastQueryMeta = null;
  134. this.lastQueryError = null;
  135. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  136. if (anySeriesFromQuery) {
  137. this.lastQueryMeta = anySeriesFromQuery.meta;
  138. }
  139. }
  140. onDataError(err) {
  141. if (err.data && err.data.results) {
  142. let queryRes = err.data.results[this.target.refId];
  143. if (queryRes) {
  144. this.lastQueryMeta = queryRes.meta;
  145. this.lastQueryError = queryRes.error;
  146. }
  147. }
  148. }
  149. transformToSegments(config) {
  150. return results => {
  151. let segments = _.map(results, segment => {
  152. return this.uiSegmentSrv.newSegment({
  153. value: segment.text,
  154. expandable: segment.expandable,
  155. });
  156. });
  157. if (config.addTemplateVars) {
  158. for (let variable of this.templateSrv.variables) {
  159. let value;
  160. value = '$' + variable.name;
  161. if (config.templateQuoter && variable.multi === false) {
  162. value = config.templateQuoter(value);
  163. }
  164. segments.unshift(
  165. this.uiSegmentSrv.newSegment({
  166. type: 'template',
  167. value: value,
  168. expandable: true,
  169. })
  170. );
  171. }
  172. }
  173. if (config.addNone) {
  174. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  175. }
  176. return segments;
  177. };
  178. }
  179. addSelectPart(selectParts, item) {
  180. let partModel = sqlPart.create({ type: item.value });
  181. let addAlias = false;
  182. switch (item.value) {
  183. case 'column':
  184. let parts = _.map(selectParts, function(part: any) {
  185. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  186. });
  187. this.selectModels.push(parts);
  188. break;
  189. case 'aggregate':
  190. // add group by if no group by yet
  191. if (this.target.groupBy.length === 0) {
  192. this.addGroupBy('time', '1m');
  193. }
  194. case 'special':
  195. let index = _.findIndex(selectParts, (p: any) => p.def.type === item.value);
  196. if (index !== -1) {
  197. selectParts[index] = partModel;
  198. } else {
  199. selectParts.splice(1, 0, partModel);
  200. }
  201. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  202. addAlias = true;
  203. }
  204. break;
  205. case 'alias':
  206. addAlias = true;
  207. break;
  208. }
  209. if (addAlias) {
  210. // set initial alias name to column name
  211. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0]] });
  212. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  213. selectParts[selectParts.length - 1] = partModel;
  214. } else {
  215. selectParts.push(partModel);
  216. }
  217. }
  218. this.updatePersistedParts();
  219. this.panelCtrl.refresh();
  220. }
  221. removeSelectPart(selectParts, part) {
  222. if (part.def.type === 'column') {
  223. // remove all parts of column unless its last column
  224. if (this.selectModels.length > 1) {
  225. let modelsIndex = _.indexOf(this.selectModels, selectParts);
  226. this.selectModels.splice(modelsIndex, 1);
  227. }
  228. } else {
  229. let partIndex = _.indexOf(selectParts, part);
  230. selectParts.splice(partIndex, 1);
  231. }
  232. this.updatePersistedParts();
  233. }
  234. handleSelectPartEvent(selectParts, part, evt) {
  235. switch (evt.name) {
  236. case 'get-param-options': {
  237. switch (part.def.type) {
  238. case 'aggregate':
  239. return this.datasource
  240. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  241. .then(this.transformToSegments({}))
  242. .catch(this.handleQueryError.bind(this));
  243. case 'column':
  244. return this.datasource
  245. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  246. .then(this.transformToSegments({}))
  247. .catch(this.handleQueryError.bind(this));
  248. }
  249. }
  250. case 'part-param-changed': {
  251. this.panelCtrl.refresh();
  252. break;
  253. }
  254. case 'action': {
  255. this.removeSelectPart(selectParts, part);
  256. this.panelCtrl.refresh();
  257. break;
  258. }
  259. case 'get-part-actions': {
  260. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  261. }
  262. }
  263. }
  264. handleGroupByPartEvent(part, index, evt) {
  265. switch (evt.name) {
  266. case 'get-param-options': {
  267. return this.datasource
  268. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  269. .then(this.transformToSegments({}))
  270. .catch(this.handleQueryError.bind(this));
  271. }
  272. case 'part-param-changed': {
  273. this.panelCtrl.refresh();
  274. break;
  275. }
  276. case 'action': {
  277. this.removeGroupBy(part, index);
  278. this.panelCtrl.refresh();
  279. break;
  280. }
  281. case 'get-part-actions': {
  282. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  283. }
  284. }
  285. }
  286. addGroupBy(partType, value) {
  287. let params = [value];
  288. if (partType === 'time') {
  289. params = ['1m', 'none'];
  290. }
  291. let partModel = sqlPart.create({ type: partType, params: params });
  292. if (partType === 'time') {
  293. // put timeGroup at start
  294. this.groupByParts.splice(0, 0, partModel);
  295. } else {
  296. this.groupByParts.push(partModel);
  297. }
  298. // add aggregates when adding group by
  299. for (let selectParts of this.selectModels) {
  300. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  301. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  302. selectParts.splice(1, 0, aggregate);
  303. if (!selectParts.some(part => part.def.type === 'alias')) {
  304. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  305. selectParts.push(alias);
  306. }
  307. }
  308. }
  309. this.updatePersistedParts();
  310. }
  311. removeGroupBy(part, index) {
  312. if (part.def.type === 'time') {
  313. // remove aggregations
  314. this.selectModels = _.map(this.selectModels, (s: any) => {
  315. return _.filter(s, (part: any) => {
  316. if (part.def.type === 'aggregate') {
  317. return false;
  318. }
  319. return true;
  320. });
  321. });
  322. }
  323. this.groupByParts.splice(index, 1);
  324. this.updatePersistedParts();
  325. }
  326. handleWherePartEvent(whereParts, part, evt, index) {
  327. switch (evt.name) {
  328. case 'get-param-options': {
  329. switch (evt.param.name) {
  330. case 'left':
  331. return this.datasource
  332. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  333. .then(this.transformToSegments({}))
  334. .catch(this.handleQueryError.bind(this));
  335. case 'right':
  336. return this.datasource
  337. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  338. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  339. .catch(this.handleQueryError.bind(this));
  340. case 'op':
  341. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  342. default:
  343. return this.$q.when([]);
  344. }
  345. }
  346. case 'part-param-changed': {
  347. this.panelCtrl.refresh();
  348. break;
  349. }
  350. case 'action': {
  351. // remove element
  352. whereParts.splice(index, 1);
  353. this.updatePersistedParts();
  354. this.panelCtrl.refresh();
  355. break;
  356. }
  357. case 'get-part-actions': {
  358. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  359. }
  360. }
  361. }
  362. getWhereOptions() {
  363. var options = [];
  364. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  365. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  366. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  367. return this.$q.when(options);
  368. }
  369. whereAddAction(part, index) {
  370. switch (this.whereAdd.type) {
  371. case 'macro': {
  372. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  373. break;
  374. }
  375. default: {
  376. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  377. }
  378. }
  379. this.updatePersistedParts();
  380. this.resetPlusButton(this.whereAdd);
  381. this.panelCtrl.refresh();
  382. }
  383. getGroupByOptions() {
  384. return this.datasource
  385. .metricFindQuery(this.metaBuilder.buildColumnQuery('groupby'))
  386. .then(tags => {
  387. var options = [];
  388. if (!this.queryModel.hasGroupByTime()) {
  389. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  390. }
  391. for (let tag of tags) {
  392. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  393. }
  394. return options;
  395. })
  396. .catch(this.handleQueryError.bind(this));
  397. }
  398. groupByAction() {
  399. switch (this.groupByAdd.value) {
  400. default: {
  401. this.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  402. }
  403. }
  404. this.resetPlusButton(this.groupByAdd);
  405. this.panelCtrl.refresh();
  406. }
  407. handleQueryError(err) {
  408. this.error = err.message || 'Failed to issue metric query';
  409. return [];
  410. }
  411. }