query_ctrl.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import _ from 'lodash';
  2. import { PostgresQueryBuilder } from './query_builder';
  3. import { QueryCtrl } from 'app/plugins/sdk';
  4. import PostgresQuery from './postgres_query';
  5. import sqlPart from './sql_part';
  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. whereAdd: any;
  29. timeColumnSegment: any;
  30. metricColumnSegment: any;
  31. selectMenu: any;
  32. groupBySegment: any;
  33. /** @ngInject **/
  34. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  35. super($scope, $injector);
  36. this.target = this.target;
  37. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  38. this.queryBuilder = new PostgresQueryBuilder(this.target, this.queryModel);
  39. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  40. if (!this.target.rawSql) {
  41. // special handling when in table panel
  42. if (this.panelCtrl.panel.type === 'table') {
  43. this.target.format = 'table';
  44. this.target.rawSql = 'SELECT 1';
  45. } else {
  46. this.target.rawSql = defaultQuery;
  47. }
  48. }
  49. this.schemaSegment = uiSegmentSrv.newSegment(this.target.schema);
  50. if (!this.target.table) {
  51. this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
  52. } else {
  53. this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
  54. }
  55. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  56. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  57. this.buildSelectMenu();
  58. this.buildWhereSegments();
  59. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  60. this.groupBySegment = this.uiSegmentSrv.newPlusButton();
  61. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  62. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  63. }
  64. buildSelectMenu() {
  65. this.selectMenu = [
  66. { text: 'Aggregate', value: 'aggregate' },
  67. { text: 'Math', value: 'math' },
  68. { text: 'Alias', value: 'alias' },
  69. { text: 'Column', value: 'column' },
  70. ];
  71. }
  72. toggleEditorMode() {
  73. this.target.rawQuery = !this.target.rawQuery;
  74. }
  75. getSchemaSegments() {
  76. return this.datasource
  77. .metricFindQuery(this.queryBuilder.buildSchemaQuery())
  78. .then(this.transformToSegments(true))
  79. .catch(this.handleQueryError.bind(this));
  80. }
  81. getTableSegments() {
  82. return this.datasource
  83. .metricFindQuery(this.queryBuilder.buildTableQuery())
  84. .then(this.transformToSegments(true))
  85. .catch(this.handleQueryError.bind(this));
  86. }
  87. getTimeColumnSegments() {
  88. return this.datasource
  89. .metricFindQuery(this.queryBuilder.buildColumnQuery('time'))
  90. .then(this.transformToSegments(true))
  91. .catch(this.handleQueryError.bind(this));
  92. }
  93. getMetricColumnSegments() {
  94. return this.datasource
  95. .metricFindQuery(this.queryBuilder.buildColumnQuery('metric'))
  96. .then(this.transformToSegments(true))
  97. .catch(this.handleQueryError.bind(this));
  98. }
  99. tableChanged() {
  100. this.target.table = this.tableSegment.value;
  101. this.panelCtrl.refresh();
  102. }
  103. schemaChanged() {
  104. this.target.schema = this.schemaSegment.value;
  105. this.panelCtrl.refresh();
  106. }
  107. timeColumnChanged() {
  108. this.target.timeColumn = this.timeColumnSegment.value;
  109. this.panelCtrl.refresh();
  110. }
  111. metricColumnChanged() {
  112. this.target.metricColumn = this.metricColumnSegment.value;
  113. this.panelCtrl.refresh();
  114. }
  115. onDataReceived(dataList) {
  116. this.lastQueryMeta = null;
  117. this.lastQueryError = null;
  118. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  119. if (anySeriesFromQuery) {
  120. this.lastQueryMeta = anySeriesFromQuery.meta;
  121. }
  122. }
  123. onDataError(err) {
  124. if (err.data && err.data.results) {
  125. let queryRes = err.data.results[this.target.refId];
  126. if (queryRes) {
  127. this.lastQueryMeta = queryRes.meta;
  128. this.lastQueryError = queryRes.error;
  129. }
  130. }
  131. }
  132. transformToSegments(addTemplateVars) {
  133. return results => {
  134. var segments = _.map(results, segment => {
  135. return this.uiSegmentSrv.newSegment({
  136. value: segment.text,
  137. expandable: segment.expandable,
  138. });
  139. });
  140. if (addTemplateVars) {
  141. for (let variable of this.templateSrv.variables) {
  142. segments.unshift(
  143. this.uiSegmentSrv.newSegment({
  144. type: 'template',
  145. value: '$' + variable.name,
  146. expandable: true,
  147. })
  148. );
  149. }
  150. }
  151. return segments;
  152. };
  153. }
  154. addSelectPart(selectParts, cat, subitem) {
  155. if ('submenu' in cat) {
  156. this.queryModel.addSelectPart(selectParts, subitem.value);
  157. } else {
  158. this.queryModel.addSelectPart(selectParts, cat.value);
  159. }
  160. this.panelCtrl.refresh();
  161. }
  162. handleSelectPartEvent(selectParts, part, evt) {
  163. switch (evt.name) {
  164. case 'get-param-options': {
  165. switch (part.def.type) {
  166. case 'aggregate':
  167. return this.datasource
  168. .metricFindQuery(this.queryBuilder.buildAggregateQuery())
  169. .then(this.transformToSegments(false))
  170. .catch(this.handleQueryError.bind(this));
  171. case 'column':
  172. return this.datasource
  173. .metricFindQuery(this.queryBuilder.buildColumnQuery('value'))
  174. .then(this.transformToSegments(true))
  175. .catch(this.handleQueryError.bind(this));
  176. }
  177. }
  178. case 'part-param-changed': {
  179. this.panelCtrl.refresh();
  180. break;
  181. }
  182. case 'action': {
  183. this.queryModel.removeSelectPart(selectParts, part);
  184. this.panelCtrl.refresh();
  185. break;
  186. }
  187. case 'get-part-actions': {
  188. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  189. }
  190. }
  191. }
  192. handleGroupByPartEvent(part, index, evt) {
  193. switch (evt.name) {
  194. case 'get-param-options': {
  195. return this.datasource
  196. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  197. .then(this.transformToSegments(true))
  198. .catch(this.handleQueryError.bind(this));
  199. }
  200. case 'part-param-changed': {
  201. this.panelCtrl.refresh();
  202. break;
  203. }
  204. case 'action': {
  205. this.queryModel.removeGroupByPart(part, index);
  206. this.panelCtrl.refresh();
  207. break;
  208. }
  209. case 'get-part-actions': {
  210. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  211. }
  212. }
  213. }
  214. buildWhereSegments() {
  215. // this.whereSegments = [];
  216. // this.whereSegments.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  217. }
  218. handleWherePartEvent(whereParts, part, evt, index) {
  219. switch (evt.name) {
  220. case 'get-param-options': {
  221. switch (evt.param.name) {
  222. case 'left':
  223. return this.datasource
  224. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  225. .then(this.transformToSegments(false))
  226. .catch(this.handleQueryError.bind(this));
  227. case 'right':
  228. return this.datasource
  229. .metricFindQuery(this.queryBuilder.buildValueQuery(part.params[0]))
  230. .then(this.transformToSegments(true))
  231. .catch(this.handleQueryError.bind(this));
  232. case 'op':
  233. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN']));
  234. default:
  235. return this.$q.when([]);
  236. }
  237. }
  238. case 'part-param-changed': {
  239. this.panelCtrl.refresh();
  240. break;
  241. }
  242. case 'action': {
  243. this.queryModel.removeWherePart(part, index);
  244. this.panelCtrl.refresh();
  245. break;
  246. }
  247. case 'get-part-actions': {
  248. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  249. }
  250. }
  251. }
  252. getWhereOptions() {
  253. var options = [];
  254. options.push(this.uiSegmentSrv.newSegment({ type: 'function', value: '$__timeFilter' }));
  255. options.push(this.uiSegmentSrv.newSegment({ type: 'function', value: '$__unixEpochFilter' }));
  256. options.push(this.uiSegmentSrv.newSegment({ type: 'function', value: 'Expression' }));
  257. return this.$q.when(options);
  258. }
  259. whereAddAction(part, index) {
  260. switch (this.whereAdd.type) {
  261. case 'macro': {
  262. this.queryModel.whereParts.push(
  263. sqlPart.create({ type: 'function', name: this.whereAdd.value, params: ['value', '=', 'value'] })
  264. );
  265. }
  266. default: {
  267. this.queryModel.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  268. }
  269. }
  270. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  271. this.panelCtrl.refresh();
  272. }
  273. getGroupByOptions() {
  274. return this.datasource
  275. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  276. .then(tags => {
  277. var options = [];
  278. if (!this.queryModel.hasGroupByTime()) {
  279. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  280. }
  281. for (let tag of tags) {
  282. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  283. }
  284. return options;
  285. })
  286. .catch(this.handleQueryError.bind(this));
  287. }
  288. groupByAction() {
  289. switch (this.groupBySegment.value) {
  290. default: {
  291. this.queryModel.addGroupBy(this.groupBySegment.value);
  292. }
  293. }
  294. var plusButton = this.uiSegmentSrv.newPlusButton();
  295. this.groupBySegment.value = plusButton.value;
  296. this.groupBySegment.html = plusButton.html;
  297. this.panelCtrl.refresh();
  298. }
  299. handleQueryError(err) {
  300. this.error = err.message || 'Failed to issue metric query';
  301. return [];
  302. }
  303. }