query_ctrl.ts 12 KB

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