query_ctrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. if ("submenu" in cat) {
  178. this.queryModel.addSelectPart(selectParts, subitem.value);
  179. } else {
  180. this.queryModel.addSelectPart(selectParts, cat.value);
  181. }
  182. this.panelCtrl.refresh();
  183. }
  184. handleSelectPartEvent(selectParts, part, evt) {
  185. switch (evt.name) {
  186. case 'get-param-options': {
  187. return this.datasource
  188. .metricFindQuery(this.queryBuilder.buildColumnQuery("value"))
  189. .then(this.transformToSegments(true))
  190. .catch(this.handleQueryError.bind(this));
  191. }
  192. case 'part-param-changed': {
  193. this.panelCtrl.refresh();
  194. break;
  195. }
  196. case 'action': {
  197. this.queryModel.removeSelectPart(selectParts, part);
  198. this.panelCtrl.refresh();
  199. break;
  200. }
  201. case 'get-part-actions': {
  202. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  203. }
  204. }
  205. }
  206. handleGroupByPartEvent(part, index, evt) {
  207. switch (evt.name) {
  208. case 'get-param-options': {
  209. return this.datasource
  210. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  211. .then(this.transformToSegments(true))
  212. .catch(this.handleQueryError.bind(this));
  213. }
  214. case 'part-param-changed': {
  215. this.panelCtrl.refresh();
  216. break;
  217. }
  218. case 'action': {
  219. this.queryModel.removeGroupByPart(part, index);
  220. this.panelCtrl.refresh();
  221. break;
  222. }
  223. case 'get-part-actions': {
  224. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  225. }
  226. }
  227. }
  228. buildWhereSegments() {
  229. this.whereSegments = [];
  230. for (let constraint of this.target.where) {
  231. if (constraint.condition) {
  232. this.whereSegments.push(this.uiSegmentSrv.newCondition(constraint.condition));
  233. }
  234. this.whereSegments.push(this.uiSegmentSrv.newKey(constraint.key));
  235. this.whereSegments.push(this.uiSegmentSrv.newOperator(constraint.operator));
  236. this.whereSegments.push(this.uiSegmentSrv.newKeyValue(constraint.value));
  237. }
  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. getWhereSegments(segment, index) {
  245. var query, addTemplateVars;
  246. if (segment.type === 'condition') {
  247. return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
  248. }
  249. if (segment.type === 'operator') {
  250. var columnName = this.whereSegments[index - 1].value;
  251. query = this.queryBuilder.buildDatatypeQuery(columnName);
  252. return this.datasource.metricFindQuery(query)
  253. .then(results => {
  254. var datatype = results[0].text;
  255. switch (datatype) {
  256. case "text":
  257. case "character":
  258. case "character varying":
  259. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '~', '~*','!~','!~*','IN']));
  260. default:
  261. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=']));
  262. }
  263. })
  264. .catch(this.handleQueryError.bind(this));
  265. }
  266. if (segment.type === 'key' || segment.type === 'plus-button') {
  267. query = this.queryBuilder.buildColumnQuery();
  268. addTemplateVars = false;
  269. } else if (segment.type === 'value') {
  270. query = this.queryBuilder.buildValueQuery(this.whereSegments[index -2].value);
  271. addTemplateVars = true;
  272. }
  273. return this.datasource
  274. .metricFindQuery(query)
  275. .then(this.transformToSegments(addTemplateVars))
  276. .then(results => {
  277. if (segment.type === 'key') {
  278. results.splice(0, 0, angular.copy(this.removeWhereFilterSegment));
  279. }
  280. return results;
  281. })
  282. .catch(this.handleQueryError.bind(this));
  283. }
  284. whereSegmentUpdated(segment, index) {
  285. this.whereSegments[index] = segment;
  286. // handle remove where condition
  287. if (segment.value === this.removeWhereFilterSegment.value) {
  288. this.whereSegments.splice(index, 3);
  289. if (this.whereSegments.length === 0) {
  290. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  291. } else if (this.whereSegments.length > 2) {
  292. this.whereSegments.splice(Math.max(index - 1, 0), 1);
  293. if (this.whereSegments[this.whereSegments.length - 1].type !== 'plus-button') {
  294. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  295. }
  296. }
  297. } else {
  298. if (segment.type === 'plus-button') {
  299. if (index > 2) {
  300. this.whereSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
  301. }
  302. this.whereSegments.push(this.uiSegmentSrv.newOperator('='));
  303. this.whereSegments.push(this.uiSegmentSrv.newFake('select value', 'value', 'query-segment-value'));
  304. segment.type = 'key';
  305. segment.cssClass = 'query-segment-key';
  306. }
  307. if (index + 1 === this.whereSegments.length) {
  308. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  309. }
  310. }
  311. this.rebuildTargetWhereConditions();
  312. }
  313. rebuildTargetWhereConditions() {
  314. var where = [];
  315. var tagIndex = 0;
  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. where[tagIndex].value = segment2.value;
  324. } else if (segment2.type === 'template') {
  325. where[tagIndex].value = segment2.value;
  326. } else if (segment2.type === 'condition') {
  327. where.push({ condition: segment2.value });
  328. tagIndex += 1;
  329. } else if (segment2.type === 'operator') {
  330. where[tagIndex].operator = segment2.value;
  331. }
  332. });
  333. this.target.where = where;
  334. this.panelCtrl.refresh();
  335. }
  336. getGroupByOptions() {
  337. return this.datasource
  338. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  339. .then(tags => {
  340. var options = [];
  341. if (!this.queryModel.hasGroupByTime()) {
  342. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  343. }
  344. for (let tag of tags) {
  345. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  346. }
  347. return options;
  348. })
  349. .catch(this.handleQueryError.bind(this));
  350. }
  351. groupByAction() {
  352. switch (this.groupBySegment.value) {
  353. default: {
  354. this.queryModel.addGroupBy(this.groupBySegment.value);
  355. }
  356. }
  357. var plusButton = this.uiSegmentSrv.newPlusButton();
  358. this.groupBySegment.value = plusButton.value;
  359. this.groupBySegment.html = plusButton.html;
  360. this.panelCtrl.refresh();
  361. }
  362. handleQueryError(err) {
  363. this.error = err.message || 'Failed to issue metric query';
  364. return [];
  365. }
  366. }