query_ctrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import { PostgresQueryBuilder } from './query_builder';
  4. import { QueryCtrl } from 'app/plugins/sdk';
  5. import PostgresQuery from './postgres_query';
  6. export interface QueryMeta {
  7. sql: string;
  8. }
  9. const defaultQuery = `SELECT
  10. $__time(time_column),
  11. value1
  12. FROM
  13. metric_table
  14. WHERE
  15. $__timeFilter(time_column)
  16. `;
  17. export class PostgresQueryCtrl extends QueryCtrl {
  18. static templateUrl = 'partials/query.editor.html';
  19. showLastQuerySQL: boolean;
  20. formats: any[];
  21. queryModel: PostgresQuery;
  22. queryBuilder: PostgresQueryBuilder;
  23. lastQueryMeta: QueryMeta;
  24. lastQueryError: string;
  25. showHelp: boolean;
  26. schemaSegment: any;
  27. tableSegment: any;
  28. whereSegments: any;
  29. timeColumnSegment: any;
  30. metricColumnSegment: any;
  31. selectMenu: any;
  32. groupBySegment: any;
  33. removeWhereFilterSegment: any;
  34. /** @ngInject **/
  35. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  36. super($scope, $injector);
  37. this.target = this.target;
  38. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  39. this.queryBuilder = new PostgresQueryBuilder(this.target, this.queryModel);
  40. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  41. if (!this.target.rawSql) {
  42. // special handling when in table panel
  43. if (this.panelCtrl.panel.type === 'table') {
  44. this.target.format = 'table';
  45. this.target.rawSql = 'SELECT 1';
  46. } else {
  47. this.target.rawSql = defaultQuery;
  48. }
  49. }
  50. this.schemaSegment= uiSegmentSrv.newSegment(this.target.schema);
  51. if (!this.target.table) {
  52. this.tableSegment = uiSegmentSrv.newSegment({value: 'select table',fake: true});
  53. } else {
  54. this.tableSegment= uiSegmentSrv.newSegment(this.target.table);
  55. }
  56. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  57. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  58. this.buildSelectMenu();
  59. this.buildWhereSegments();
  60. this.groupBySegment = this.uiSegmentSrv.newPlusButton();
  61. this.removeWhereFilterSegment = uiSegmentSrv.newSegment({
  62. fake: true,
  63. value: '-- remove filter --',
  64. });
  65. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  66. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  67. }
  68. buildSelectMenu() {
  69. this.selectMenu = [
  70. {text: "aggregate", value: "aggregate"},
  71. {text: "math", value: "math"},
  72. {text: "alias", value: "alias"},
  73. {text: "column", value: "column"},
  74. ];
  75. }
  76. toggleEditorMode() {
  77. this.target.rawQuery = !this.target.rawQuery;
  78. }
  79. getSchemaSegments() {
  80. return this.datasource
  81. .metricFindQuery(this.queryBuilder.buildSchemaQuery())
  82. .then(this.transformToSegments(true))
  83. .catch(this.handleQueryError.bind(this));
  84. }
  85. getTableSegments() {
  86. return this.datasource
  87. .metricFindQuery(this.queryBuilder.buildTableQuery())
  88. .then(this.transformToSegments(true))
  89. .catch(this.handleQueryError.bind(this));
  90. }
  91. getTimeColumnSegments() {
  92. return this.datasource
  93. .metricFindQuery(this.queryBuilder.buildColumnQuery("time"))
  94. .then(this.transformToSegments(true))
  95. .catch(this.handleQueryError.bind(this));
  96. }
  97. getMetricColumnSegments() {
  98. return this.datasource
  99. .metricFindQuery(this.queryBuilder.buildColumnQuery("metric"))
  100. .then(this.transformToSegments(true))
  101. .catch(this.handleQueryError.bind(this));
  102. }
  103. tableChanged() {
  104. this.target.table = this.tableSegment.value;
  105. this.panelCtrl.refresh();
  106. }
  107. schemaChanged() {
  108. this.target.schema = this.schemaSegment.value;
  109. this.panelCtrl.refresh();
  110. }
  111. timeColumnChanged() {
  112. this.target.timeColumn = this.timeColumnSegment.value;
  113. this.panelCtrl.refresh();
  114. }
  115. metricColumnChanged() {
  116. this.target.metricColumn = this.metricColumnSegment.value;
  117. this.panelCtrl.refresh();
  118. }
  119. onDataReceived(dataList) {
  120. this.lastQueryMeta = null;
  121. this.lastQueryError = null;
  122. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  123. if (anySeriesFromQuery) {
  124. this.lastQueryMeta = anySeriesFromQuery.meta;
  125. }
  126. }
  127. onDataError(err) {
  128. if (err.data && err.data.results) {
  129. let queryRes = err.data.results[this.target.refId];
  130. if (queryRes) {
  131. this.lastQueryMeta = queryRes.meta;
  132. this.lastQueryError = queryRes.error;
  133. }
  134. }
  135. }
  136. transformToSegments(addTemplateVars) {
  137. return results => {
  138. var segments = _.map(results, segment => {
  139. return this.uiSegmentSrv.newSegment({
  140. value: segment.text,
  141. expandable: segment.expandable,
  142. });
  143. });
  144. if (addTemplateVars) {
  145. for (let variable of this.templateSrv.variables) {
  146. segments.unshift(
  147. this.uiSegmentSrv.newSegment({
  148. type: 'template',
  149. value: '$' + variable.name,
  150. expandable: true,
  151. })
  152. );
  153. }
  154. }
  155. return segments;
  156. };
  157. }
  158. addSelectPart(selectParts, cat, subitem) {
  159. if ("submenu" in cat) {
  160. this.queryModel.addSelectPart(selectParts, subitem.value);
  161. } else {
  162. this.queryModel.addSelectPart(selectParts, cat.value);
  163. }
  164. this.panelCtrl.refresh();
  165. }
  166. handleSelectPartEvent(selectParts, part, evt) {
  167. switch (evt.name) {
  168. case 'get-param-options': {
  169. switch (part.def.type) {
  170. case "aggregate":
  171. return this.datasource
  172. .metricFindQuery(this.queryBuilder.buildAggregateQuery())
  173. .then(this.transformToSegments(false))
  174. .catch(this.handleQueryError.bind(this));
  175. case "column":
  176. return this.datasource
  177. .metricFindQuery(this.queryBuilder.buildColumnQuery("value"))
  178. .then(this.transformToSegments(true))
  179. .catch(this.handleQueryError.bind(this));
  180. }
  181. }
  182. case 'part-param-changed': {
  183. this.panelCtrl.refresh();
  184. break;
  185. }
  186. case 'action': {
  187. this.queryModel.removeSelectPart(selectParts, part);
  188. this.panelCtrl.refresh();
  189. break;
  190. }
  191. case 'get-part-actions': {
  192. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  193. }
  194. }
  195. }
  196. handleGroupByPartEvent(part, index, evt) {
  197. switch (evt.name) {
  198. case 'get-param-options': {
  199. return this.datasource
  200. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  201. .then(this.transformToSegments(true))
  202. .catch(this.handleQueryError.bind(this));
  203. }
  204. case 'part-param-changed': {
  205. this.panelCtrl.refresh();
  206. break;
  207. }
  208. case 'action': {
  209. this.queryModel.removeGroupByPart(part, index);
  210. this.panelCtrl.refresh();
  211. break;
  212. }
  213. case 'get-part-actions': {
  214. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  215. }
  216. }
  217. }
  218. buildWhereSegments() {
  219. this.whereSegments = [];
  220. for (let constraint of this.target.where) {
  221. if (constraint.condition) {
  222. this.whereSegments.push(this.uiSegmentSrv.newCondition(constraint.condition));
  223. }
  224. this.whereSegments.push(this.uiSegmentSrv.newKey(constraint.key));
  225. this.whereSegments.push(this.uiSegmentSrv.newOperator(constraint.operator));
  226. this.whereSegments.push(this.uiSegmentSrv.newKeyValue(constraint.value));
  227. }
  228. var count = this.whereSegments.length;
  229. var lastSegment = this.whereSegments[Math.max(count - 1, 0)];
  230. if (!lastSegment || lastSegment.type !== 'plus-button') {
  231. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  232. }
  233. }
  234. getWhereSegments(segment, index) {
  235. var query, addTemplateVars;
  236. if (segment.type === 'condition') {
  237. return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
  238. }
  239. if (segment.type === 'operator') {
  240. var columnName = this.whereSegments[index - 1].value;
  241. query = this.queryBuilder.buildDatatypeQuery(columnName);
  242. return this.datasource.metricFindQuery(query)
  243. .then(results => {
  244. var datatype = results[0].text;
  245. switch (datatype) {
  246. case "text":
  247. case "character":
  248. case "character varying":
  249. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '~', '~*','!~','!~*','IN']));
  250. default:
  251. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=']));
  252. }
  253. })
  254. .catch(this.handleQueryError.bind(this));
  255. }
  256. if (segment.type === 'key' || segment.type === 'plus-button') {
  257. query = this.queryBuilder.buildColumnQuery();
  258. addTemplateVars = false;
  259. } else if (segment.type === 'value') {
  260. query = this.queryBuilder.buildValueQuery(this.whereSegments[index -2].value);
  261. addTemplateVars = true;
  262. }
  263. return this.datasource
  264. .metricFindQuery(query)
  265. .then(this.transformToSegments(addTemplateVars))
  266. .then(results => {
  267. if (segment.type === 'key') {
  268. results.splice(0, 0, angular.copy(this.removeWhereFilterSegment));
  269. }
  270. return results;
  271. })
  272. .catch(this.handleQueryError.bind(this));
  273. }
  274. whereSegmentUpdated(segment, index) {
  275. this.whereSegments[index] = segment;
  276. // handle remove where condition
  277. if (segment.value === this.removeWhereFilterSegment.value) {
  278. this.whereSegments.splice(index, 3);
  279. if (this.whereSegments.length === 0) {
  280. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  281. } else if (this.whereSegments.length > 2) {
  282. this.whereSegments.splice(Math.max(index - 1, 0), 1);
  283. if (this.whereSegments[this.whereSegments.length - 1].type !== 'plus-button') {
  284. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  285. }
  286. }
  287. } else {
  288. if (segment.type === 'plus-button') {
  289. if (index > 2) {
  290. this.whereSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
  291. }
  292. this.whereSegments.push(this.uiSegmentSrv.newOperator('='));
  293. this.whereSegments.push(this.uiSegmentSrv.newFake('select value', 'value', 'query-segment-value'));
  294. segment.type = 'key';
  295. segment.cssClass = 'query-segment-key';
  296. }
  297. if (index + 1 === this.whereSegments.length) {
  298. this.whereSegments.push(this.uiSegmentSrv.newPlusButton());
  299. }
  300. }
  301. this.rebuildTargetWhereConditions();
  302. }
  303. rebuildTargetWhereConditions() {
  304. var where = [];
  305. var tagIndex = 0;
  306. _.each(this.whereSegments, (segment2, index) => {
  307. if (segment2.type === 'key') {
  308. if (where.length === 0) {
  309. where.push({});
  310. }
  311. where[tagIndex].key = segment2.value;
  312. } else if (segment2.type === 'value') {
  313. where[tagIndex].value = segment2.value;
  314. } else if (segment2.type === 'template') {
  315. where[tagIndex].value = segment2.value;
  316. } else if (segment2.type === 'condition') {
  317. where.push({ condition: segment2.value });
  318. tagIndex += 1;
  319. } else if (segment2.type === 'operator') {
  320. where[tagIndex].operator = segment2.value;
  321. }
  322. });
  323. this.target.where = where;
  324. this.panelCtrl.refresh();
  325. }
  326. getGroupByOptions() {
  327. return this.datasource
  328. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  329. .then(tags => {
  330. var options = [];
  331. if (!this.queryModel.hasGroupByTime()) {
  332. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  333. }
  334. for (let tag of tags) {
  335. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  336. }
  337. return options;
  338. })
  339. .catch(this.handleQueryError.bind(this));
  340. }
  341. groupByAction() {
  342. switch (this.groupBySegment.value) {
  343. default: {
  344. this.queryModel.addGroupBy(this.groupBySegment.value);
  345. }
  346. }
  347. var plusButton = this.uiSegmentSrv.newPlusButton();
  348. this.groupBySegment.value = plusButton.value;
  349. this.groupBySegment.html = plusButton.html;
  350. this.panelCtrl.refresh();
  351. }
  352. handleQueryError(err) {
  353. this.error = err.message || 'Failed to issue metric query';
  354. return [];
  355. }
  356. }