query_ctrl.ts 12 KB

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