query_ctrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import { PostgresQueryBuilder } from './query_builder';
  4. import { QueryCtrl } from 'app/plugins/sdk';
  5. import queryPart from './query_part';
  6. import PostgresQuery from './postgres_query';
  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. queryBuilder: PostgresQueryBuilder;
  24. lastQueryMeta: QueryMeta;
  25. lastQueryError: string;
  26. showHelp: boolean;
  27. schemaSegment: any;
  28. tableSegment: any;
  29. whereSegments: any;
  30. timeColumnSegment: any;
  31. metricColumnSegment: any;
  32. selectMenu: any;
  33. groupBySegment: any;
  34. removeWhereFilterSegment: any;
  35. /** @ngInject **/
  36. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  37. super($scope, $injector);
  38. this.target = this.target;
  39. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  40. this.queryBuilder = new PostgresQueryBuilder(this.target, this.queryModel);
  41. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  42. if (!this.target.rawSql) {
  43. // special handling when in table panel
  44. if (this.panelCtrl.panel.type === 'table') {
  45. this.target.format = 'table';
  46. this.target.rawSql = 'SELECT 1';
  47. } else {
  48. this.target.rawSql = defaultQuery;
  49. }
  50. }
  51. this.schemaSegment= uiSegmentSrv.newSegment(this.target.schema);
  52. if (!this.target.table) {
  53. this.tableSegment = uiSegmentSrv.newSegment({value: 'select table',fake: true});
  54. } else {
  55. this.tableSegment= uiSegmentSrv.newSegment(this.target.table);
  56. }
  57. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  58. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  59. this.buildSelectMenu();
  60. this.buildWhereSegments();
  61. this.groupBySegment = this.uiSegmentSrv.newPlusButton();
  62. this.removeWhereFilterSegment = uiSegmentSrv.newSegment({
  63. fake: true,
  64. value: '-- remove filter --',
  65. });
  66. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  67. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  68. }
  69. buildSelectMenu() {
  70. if (!queryPart.hasAggregates()) {
  71. this.datasource.metricFindQuery(this.queryBuilder.buildAggregateQuery())
  72. .then(results => {
  73. queryPart.clearAggregates();
  74. _.map(results, segment => { queryPart.registerAggregate(segment.text); });
  75. })
  76. .catch(this.handleQueryError.bind(this));
  77. }
  78. var categories = queryPart.getCategories();
  79. this.selectMenu = _.reduce(
  80. categories,
  81. function(memo, cat, key) {
  82. var menu = {
  83. text: key,
  84. submenu: cat.map(item => {
  85. return { text: item.type, value: item.type };
  86. }),
  87. };
  88. memo.push(menu);
  89. return memo;
  90. },
  91. []
  92. );
  93. }
  94. toggleEditorMode() {
  95. this.target.rawQuery = !this.target.rawQuery;
  96. }
  97. getSchemaSegments() {
  98. return this.datasource
  99. .metricFindQuery(this.queryBuilder.buildSchemaQuery())
  100. .then(this.transformToSegments(true))
  101. .catch(this.handleQueryError.bind(this));
  102. }
  103. getTableSegments() {
  104. return this.datasource
  105. .metricFindQuery(this.queryBuilder.buildTableQuery())
  106. .then(this.transformToSegments(true))
  107. .catch(this.handleQueryError.bind(this));
  108. }
  109. getTimeColumnSegments() {
  110. return this.datasource
  111. .metricFindQuery(this.queryBuilder.buildColumnQuery("time"))
  112. .then(this.transformToSegments(true))
  113. .catch(this.handleQueryError.bind(this));
  114. }
  115. getMetricColumnSegments() {
  116. return this.datasource
  117. .metricFindQuery(this.queryBuilder.buildColumnQuery("metric"))
  118. .then(this.transformToSegments(true))
  119. .catch(this.handleQueryError.bind(this));
  120. }
  121. tableChanged() {
  122. this.target.table = this.tableSegment.value;
  123. this.panelCtrl.refresh();
  124. }
  125. schemaChanged() {
  126. this.target.schema = this.schemaSegment.value;
  127. this.panelCtrl.refresh();
  128. }
  129. timeColumnChanged() {
  130. this.target.timeColumn = this.timeColumnSegment.value;
  131. this.panelCtrl.refresh();
  132. }
  133. metricColumnChanged() {
  134. this.target.metricColumn = this.metricColumnSegment.value;
  135. this.panelCtrl.refresh();
  136. }
  137. onDataReceived(dataList) {
  138. this.lastQueryMeta = null;
  139. this.lastQueryError = null;
  140. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  141. if (anySeriesFromQuery) {
  142. this.lastQueryMeta = anySeriesFromQuery.meta;
  143. }
  144. }
  145. onDataError(err) {
  146. if (err.data && err.data.results) {
  147. let queryRes = err.data.results[this.target.refId];
  148. if (queryRes) {
  149. this.lastQueryMeta = queryRes.meta;
  150. this.lastQueryError = queryRes.error;
  151. }
  152. }
  153. }
  154. transformToSegments(addTemplateVars) {
  155. return results => {
  156. var segments = _.map(results, segment => {
  157. return this.uiSegmentSrv.newSegment({
  158. value: segment.text,
  159. expandable: segment.expandable,
  160. });
  161. });
  162. if (addTemplateVars) {
  163. for (let variable of this.templateSrv.variables) {
  164. segments.unshift(
  165. this.uiSegmentSrv.newSegment({
  166. type: 'template',
  167. value: '$' + variable.name,
  168. expandable: true,
  169. })
  170. );
  171. }
  172. }
  173. return segments;
  174. };
  175. }
  176. addSelectPart(selectParts, cat, subitem) {
  177. this.queryModel.addSelectPart(selectParts, subitem.value);
  178. this.panelCtrl.refresh();
  179. }
  180. handleSelectPartEvent(selectParts, part, evt) {
  181. switch (evt.name) {
  182. case 'get-param-options': {
  183. return this.datasource
  184. .metricFindQuery(this.queryBuilder.buildColumnQuery("value"))
  185. .then(this.transformToSegments(true))
  186. .catch(this.handleQueryError.bind(this));
  187. }
  188. case 'part-param-changed': {
  189. this.panelCtrl.refresh();
  190. break;
  191. }
  192. case 'action': {
  193. this.queryModel.removeSelectPart(selectParts, part);
  194. this.panelCtrl.refresh();
  195. break;
  196. }
  197. case 'get-part-actions': {
  198. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  199. }
  200. }
  201. }
  202. handleGroupByPartEvent(part, index, evt) {
  203. switch (evt.name) {
  204. case 'get-param-options': {
  205. return this.datasource
  206. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  207. .then(this.transformToSegments(true))
  208. .catch(this.handleQueryError.bind(this));
  209. }
  210. case 'part-param-changed': {
  211. this.panelCtrl.refresh();
  212. break;
  213. }
  214. case 'action': {
  215. this.queryModel.removeGroupByPart(part, index);
  216. this.panelCtrl.refresh();
  217. break;
  218. }
  219. case 'get-part-actions': {
  220. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  221. }
  222. }
  223. }
  224. buildWhereSegments() {
  225. this.whereSegments = [];
  226. for (let constraint of this.target.where) {
  227. if (constraint.condition) {
  228. this.whereSegments.push(this.uiSegmentSrv.newCondition(constraint.condition));
  229. }
  230. this.whereSegments.push(this.uiSegmentSrv.newKey(constraint.key));
  231. this.whereSegments.push(this.uiSegmentSrv.newOperator(constraint.operator));
  232. this.whereSegments.push(this.uiSegmentSrv.newKeyValue(constraint.value));
  233. }
  234. var count = this.whereSegments.length;
  235. var lastSegment = this.whereSegments[Math.max(count - 1, 0)];
  236. if (!lastSegment || lastSegment.type !== 'plus-button') {
  237. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  238. }
  239. }
  240. getWhereSegments(segment, index) {
  241. var query, addTemplateVars;
  242. if (segment.type === 'condition') {
  243. return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
  244. }
  245. if (segment.type === 'operator') {
  246. var columnName = this.whereSegments[index - 1].value;
  247. query = this.queryBuilder.buildDatatypeQuery(columnName);
  248. return this.datasource.metricFindQuery(query)
  249. .then(results => {
  250. var datatype = results[0].text;
  251. switch (datatype) {
  252. case "text":
  253. case "character":
  254. case "character varying":
  255. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '~', '~*','!~','!~*','IN']));
  256. default:
  257. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=']));
  258. }
  259. })
  260. .catch(this.handleQueryError.bind(this));
  261. }
  262. if (segment.type === 'key' || segment.type === 'plus-button') {
  263. query = this.queryBuilder.buildColumnQuery();
  264. addTemplateVars = false;
  265. } else if (segment.type === 'value') {
  266. query = this.queryBuilder.buildValueQuery(this.whereSegments[index -2].value);
  267. addTemplateVars = true;
  268. }
  269. return this.datasource
  270. .metricFindQuery(query)
  271. .then(this.transformToSegments(addTemplateVars))
  272. .then(results => {
  273. if (segment.type === 'key') {
  274. results.splice(0, 0, angular.copy(this.removeWhereFilterSegment));
  275. }
  276. return results;
  277. })
  278. .catch(this.handleQueryError.bind(this));
  279. }
  280. whereSegmentUpdated(segment, index) {
  281. this.whereSegments[index] = segment;
  282. // handle remove where condition
  283. if (segment.value === this.removeWhereFilterSegment.value) {
  284. this.whereSegments.splice(index, 3);
  285. if (this.whereSegments.length === 0) {
  286. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  287. } else if (this.whereSegments.length > 2) {
  288. this.whereSegments.splice(Math.max(index - 1, 0), 1);
  289. if (this.whereSegments[this.whereSegments.length - 1].type !== 'plus-button') {
  290. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  291. }
  292. }
  293. } else {
  294. if (segment.type === 'plus-button') {
  295. if (index > 2) {
  296. this.whereSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
  297. }
  298. this.whereSegments.push(this.uiSegmentSrv.newOperator('='));
  299. this.whereSegments.push(this.uiSegmentSrv.newFake('select value', 'value', 'query-segment-value'));
  300. segment.type = 'key';
  301. segment.cssClass = 'query-segment-key';
  302. }
  303. if (index + 1 === this.whereSegments.length) {
  304. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  305. }
  306. }
  307. this.rebuildTargetWhereConditions();
  308. }
  309. rebuildTargetWhereConditions() {
  310. var where = [];
  311. var tagIndex = 0;
  312. _.each(this.whereSegments, (segment2, index) => {
  313. if (segment2.type === 'key') {
  314. if (where.length === 0) {
  315. where.push({});
  316. }
  317. where[tagIndex].key = segment2.value;
  318. } else if (segment2.type === 'value') {
  319. where[tagIndex].value = segment2.value;
  320. } else if (segment2.type === 'template') {
  321. where[tagIndex].value = segment2.value;
  322. } else if (segment2.type === 'condition') {
  323. where.push({ condition: segment2.value });
  324. tagIndex += 1;
  325. } else if (segment2.type === 'operator') {
  326. where[tagIndex].operator = segment2.value;
  327. }
  328. });
  329. this.target.where = where;
  330. this.panelCtrl.refresh();
  331. }
  332. getGroupByOptions() {
  333. return this.datasource
  334. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  335. .then(tags => {
  336. var options = [];
  337. if (!this.queryModel.hasGroupByTime()) {
  338. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  339. }
  340. for (let tag of tags) {
  341. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  342. }
  343. return options;
  344. })
  345. .catch(this.handleQueryError.bind(this));
  346. }
  347. groupByAction() {
  348. switch (this.groupBySegment.value) {
  349. default: {
  350. this.queryModel.addGroupBy(this.groupBySegment.value);
  351. }
  352. }
  353. var plusButton = this.uiSegmentSrv.newPlusButton();
  354. this.groupBySegment.value = plusButton.value;
  355. this.groupBySegment.html = plusButton.html;
  356. this.panelCtrl.refresh();
  357. }
  358. handleQueryError(err) {
  359. this.error = err.message || 'Failed to issue metric query';
  360. return [];
  361. }
  362. }