query_ctrl.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. groupByAdd: 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.groupByAdd = 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: 'Special', value: 'special' },
  69. { text: 'Alias', value: 'alias' },
  70. { text: 'Column', value: 'column' },
  71. ];
  72. }
  73. toggleEditorMode() {
  74. this.target.rawQuery = !this.target.rawQuery;
  75. }
  76. getSchemaSegments() {
  77. return this.datasource
  78. .metricFindQuery(this.queryBuilder.buildSchemaQuery())
  79. .then(this.transformToSegments({}))
  80. .catch(this.handleQueryError.bind(this));
  81. }
  82. getTableSegments() {
  83. return this.datasource
  84. .metricFindQuery(this.queryBuilder.buildTableQuery())
  85. .then(this.transformToSegments({}))
  86. .catch(this.handleQueryError.bind(this));
  87. }
  88. getTimeColumnSegments() {
  89. return this.datasource
  90. .metricFindQuery(this.queryBuilder.buildColumnQuery('time'))
  91. .then(this.transformToSegments({}))
  92. .catch(this.handleQueryError.bind(this));
  93. }
  94. getMetricColumnSegments() {
  95. return this.datasource
  96. .metricFindQuery(this.queryBuilder.buildColumnQuery('metric'))
  97. .then(this.transformToSegments({ addNone: true }))
  98. .catch(this.handleQueryError.bind(this));
  99. }
  100. tableChanged() {
  101. this.target.table = this.tableSegment.value;
  102. this.panelCtrl.refresh();
  103. }
  104. schemaChanged() {
  105. this.target.schema = this.schemaSegment.value;
  106. this.panelCtrl.refresh();
  107. }
  108. timeColumnChanged() {
  109. this.target.timeColumn = this.timeColumnSegment.value;
  110. this.panelCtrl.refresh();
  111. }
  112. metricColumnChanged() {
  113. this.target.metricColumn = this.metricColumnSegment.value;
  114. this.panelCtrl.refresh();
  115. }
  116. onDataReceived(dataList) {
  117. this.lastQueryMeta = null;
  118. this.lastQueryError = null;
  119. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  120. if (anySeriesFromQuery) {
  121. this.lastQueryMeta = anySeriesFromQuery.meta;
  122. }
  123. }
  124. onDataError(err) {
  125. if (err.data && err.data.results) {
  126. let queryRes = err.data.results[this.target.refId];
  127. if (queryRes) {
  128. this.lastQueryMeta = queryRes.meta;
  129. this.lastQueryError = queryRes.error;
  130. }
  131. }
  132. }
  133. transformToSegments(config) {
  134. return results => {
  135. var segments = _.map(results, segment => {
  136. return this.uiSegmentSrv.newSegment({
  137. value: segment.text,
  138. expandable: segment.expandable,
  139. });
  140. });
  141. if (config.addTemplateVars) {
  142. for (let variable of this.templateSrv.variables) {
  143. var value;
  144. value = '$' + variable.name;
  145. if (config.templateQuoter && variable.multi === false) {
  146. value = config.templateQuoter(value);
  147. }
  148. segments.unshift(
  149. this.uiSegmentSrv.newSegment({
  150. type: 'template',
  151. value: value,
  152. expandable: true,
  153. })
  154. );
  155. }
  156. }
  157. if (config.addNone) {
  158. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'None', expandable: true }));
  159. }
  160. return segments;
  161. };
  162. }
  163. addSelectPart(selectParts, cat, subitem) {
  164. if ('submenu' in cat) {
  165. this.queryModel.addSelectPart(selectParts, subitem.value);
  166. } else {
  167. this.queryModel.addSelectPart(selectParts, cat.value);
  168. }
  169. this.panelCtrl.refresh();
  170. }
  171. handleSelectPartEvent(selectParts, part, evt) {
  172. switch (evt.name) {
  173. case 'get-param-options': {
  174. switch (part.def.type) {
  175. case 'aggregate':
  176. return this.datasource
  177. .metricFindQuery(this.queryBuilder.buildAggregateQuery())
  178. .then(this.transformToSegments({}))
  179. .catch(this.handleQueryError.bind(this));
  180. case 'column':
  181. return this.datasource
  182. .metricFindQuery(this.queryBuilder.buildColumnQuery('value'))
  183. .then(this.transformToSegments({}))
  184. .catch(this.handleQueryError.bind(this));
  185. }
  186. }
  187. case 'part-param-changed': {
  188. this.panelCtrl.refresh();
  189. break;
  190. }
  191. case 'action': {
  192. this.queryModel.removeSelectPart(selectParts, part);
  193. this.panelCtrl.refresh();
  194. break;
  195. }
  196. case 'get-part-actions': {
  197. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  198. }
  199. }
  200. }
  201. handleGroupByPartEvent(part, index, evt) {
  202. switch (evt.name) {
  203. case 'get-param-options': {
  204. return this.datasource
  205. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  206. .then(this.transformToSegments({}))
  207. .catch(this.handleQueryError.bind(this));
  208. }
  209. case 'part-param-changed': {
  210. this.panelCtrl.refresh();
  211. break;
  212. }
  213. case 'action': {
  214. this.queryModel.removeGroupByPart(part, index);
  215. this.panelCtrl.refresh();
  216. break;
  217. }
  218. case 'get-part-actions': {
  219. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  220. }
  221. }
  222. }
  223. buildWhereSegments() {
  224. // this.whereSegments = [];
  225. // this.whereSegments.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  226. }
  227. handleWherePartEvent(whereParts, part, evt, index) {
  228. switch (evt.name) {
  229. case 'get-param-options': {
  230. switch (evt.param.name) {
  231. case 'left':
  232. return this.datasource
  233. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  234. .then(this.transformToSegments({}))
  235. .catch(this.handleQueryError.bind(this));
  236. case 'right':
  237. return this.datasource
  238. .metricFindQuery(this.queryBuilder.buildValueQuery(part.params[0]))
  239. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  240. .catch(this.handleQueryError.bind(this));
  241. case 'op':
  242. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN']));
  243. default:
  244. return this.$q.when([]);
  245. }
  246. }
  247. case 'part-param-changed': {
  248. this.panelCtrl.refresh();
  249. break;
  250. }
  251. case 'action': {
  252. // remove element
  253. whereParts.splice(index, 1);
  254. this.queryModel.updatePersistedParts();
  255. this.panelCtrl.refresh();
  256. break;
  257. }
  258. case 'get-part-actions': {
  259. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  260. }
  261. }
  262. }
  263. getWhereOptions() {
  264. var options = [];
  265. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  266. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  267. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  268. return this.$q.when(options);
  269. }
  270. whereAddAction(part, index) {
  271. switch (this.whereAdd.type) {
  272. case 'macro': {
  273. this.queryModel.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  274. break;
  275. }
  276. default: {
  277. this.queryModel.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  278. }
  279. }
  280. var plusButton = this.uiSegmentSrv.newPlusButton();
  281. this.whereAdd.html = plusButton.html;
  282. this.whereAdd.value = plusButton.value;
  283. this.queryModel.updatePersistedParts();
  284. this.panelCtrl.refresh();
  285. }
  286. getGroupByOptions() {
  287. return this.datasource
  288. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  289. .then(tags => {
  290. var options = [];
  291. if (!this.queryModel.hasGroupByTime()) {
  292. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  293. }
  294. for (let tag of tags) {
  295. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  296. }
  297. return options;
  298. })
  299. .catch(this.handleQueryError.bind(this));
  300. }
  301. groupByAction() {
  302. switch (this.groupByAdd.value) {
  303. default: {
  304. this.queryModel.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  305. }
  306. }
  307. var plusButton = this.uiSegmentSrv.newPlusButton();
  308. this.groupByAdd.html = plusButton.html;
  309. this.groupByAdd.value = plusButton.value;
  310. this.panelCtrl.refresh();
  311. }
  312. handleQueryError(err) {
  313. this.error = err.message || 'Failed to issue metric query';
  314. return [];
  315. }
  316. }