query_ctrl.ts 13 KB

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