query_ctrl.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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: '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({}))
  79. .catch(this.handleQueryError.bind(this));
  80. }
  81. getTableSegments() {
  82. return this.datasource
  83. .metricFindQuery(this.queryBuilder.buildTableQuery())
  84. .then(this.transformToSegments({}))
  85. .catch(this.handleQueryError.bind(this));
  86. }
  87. getTimeColumnSegments() {
  88. return this.datasource
  89. .metricFindQuery(this.queryBuilder.buildColumnQuery('time'))
  90. .then(this.transformToSegments({}))
  91. .catch(this.handleQueryError.bind(this));
  92. }
  93. getMetricColumnSegments() {
  94. return this.datasource
  95. .metricFindQuery(this.queryBuilder.buildColumnQuery('metric'))
  96. .then(this.transformToSegments({ addNone: 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(config) {
  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 (config.addTemplateVars) {
  141. for (let variable of this.templateSrv.variables) {
  142. var value;
  143. value = '$' + variable.name;
  144. if (config.templateQuoter && variable.multi === false) {
  145. value = config.templateQuoter(value);
  146. }
  147. segments.unshift(
  148. this.uiSegmentSrv.newSegment({
  149. type: 'template',
  150. value: value,
  151. expandable: true,
  152. })
  153. );
  154. }
  155. }
  156. if (config.addNone) {
  157. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'None', expandable: true }));
  158. }
  159. return segments;
  160. };
  161. }
  162. addSelectPart(selectParts, cat, subitem) {
  163. if ('submenu' in cat) {
  164. this.queryModel.addSelectPart(selectParts, subitem.value);
  165. } else {
  166. this.queryModel.addSelectPart(selectParts, cat.value);
  167. }
  168. this.panelCtrl.refresh();
  169. }
  170. handleSelectPartEvent(selectParts, part, evt) {
  171. switch (evt.name) {
  172. case 'get-param-options': {
  173. switch (part.def.type) {
  174. case 'aggregate':
  175. return this.datasource
  176. .metricFindQuery(this.queryBuilder.buildAggregateQuery())
  177. .then(this.transformToSegments({}))
  178. .catch(this.handleQueryError.bind(this));
  179. case 'column':
  180. return this.datasource
  181. .metricFindQuery(this.queryBuilder.buildColumnQuery('value'))
  182. .then(this.transformToSegments({}))
  183. .catch(this.handleQueryError.bind(this));
  184. }
  185. }
  186. case 'part-param-changed': {
  187. this.panelCtrl.refresh();
  188. break;
  189. }
  190. case 'action': {
  191. this.queryModel.removeSelectPart(selectParts, part);
  192. this.panelCtrl.refresh();
  193. break;
  194. }
  195. case 'get-part-actions': {
  196. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  197. }
  198. }
  199. }
  200. handleGroupByPartEvent(part, index, evt) {
  201. switch (evt.name) {
  202. case 'get-param-options': {
  203. return this.datasource
  204. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  205. .then(this.transformToSegments({}))
  206. .catch(this.handleQueryError.bind(this));
  207. }
  208. case 'part-param-changed': {
  209. this.panelCtrl.refresh();
  210. break;
  211. }
  212. case 'action': {
  213. this.queryModel.removeGroupByPart(part, index);
  214. this.panelCtrl.refresh();
  215. break;
  216. }
  217. case 'get-part-actions': {
  218. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  219. }
  220. }
  221. }
  222. buildWhereSegments() {
  223. // this.whereSegments = [];
  224. // this.whereSegments.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  225. }
  226. handleWherePartEvent(whereParts, part, evt, index) {
  227. switch (evt.name) {
  228. case 'get-param-options': {
  229. switch (evt.param.name) {
  230. case 'left':
  231. return this.datasource
  232. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  233. .then(this.transformToSegments({}))
  234. .catch(this.handleQueryError.bind(this));
  235. case 'right':
  236. return this.datasource
  237. .metricFindQuery(this.queryBuilder.buildValueQuery(part.params[0]))
  238. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  239. .catch(this.handleQueryError.bind(this));
  240. case 'op':
  241. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN']));
  242. default:
  243. return this.$q.when([]);
  244. }
  245. }
  246. case 'part-param-changed': {
  247. this.panelCtrl.refresh();
  248. break;
  249. }
  250. case 'action': {
  251. // remove element
  252. whereParts.splice(index, 1);
  253. this.queryModel.updatePersistedParts();
  254. this.panelCtrl.refresh();
  255. break;
  256. }
  257. case 'get-part-actions': {
  258. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  259. }
  260. }
  261. }
  262. getWhereOptions() {
  263. var options = [];
  264. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  265. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  266. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  267. return this.$q.when(options);
  268. }
  269. whereAddAction(part, index) {
  270. switch (this.whereAdd.type) {
  271. case 'macro': {
  272. this.queryModel.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  273. break;
  274. }
  275. default: {
  276. this.queryModel.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  277. }
  278. }
  279. var plusButton = this.uiSegmentSrv.newPlusButton();
  280. this.whereAdd.html = plusButton.html;
  281. this.whereAdd.value = plusButton.value;
  282. this.queryModel.updatePersistedParts();
  283. this.panelCtrl.refresh();
  284. }
  285. getGroupByOptions() {
  286. return this.datasource
  287. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  288. .then(tags => {
  289. var options = [];
  290. if (!this.queryModel.hasGroupByTime()) {
  291. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  292. }
  293. for (let tag of tags) {
  294. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  295. }
  296. return options;
  297. })
  298. .catch(this.handleQueryError.bind(this));
  299. }
  300. groupByAction() {
  301. switch (this.groupByAdd.value) {
  302. default: {
  303. this.queryModel.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  304. }
  305. }
  306. var plusButton = this.uiSegmentSrv.newPlusButton();
  307. this.groupByAdd.html = plusButton.html;
  308. this.groupByAdd.value = plusButton.value;
  309. this.panelCtrl.refresh();
  310. }
  311. handleQueryError(err) {
  312. this.error = err.message || 'Failed to issue metric query';
  313. return [];
  314. }
  315. }