query_ctrl.ts 13 KB

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