query_ctrl.ts 12 KB

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