query_ctrl.ts 13 KB

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