query_ctrl.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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({}))
  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. 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({}))
  175. .catch(this.handleQueryError.bind(this));
  176. case 'column':
  177. return this.datasource
  178. .metricFindQuery(this.queryBuilder.buildColumnQuery('value'))
  179. .then(this.transformToSegments({}))
  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({}))
  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. // this.whereSegments.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  222. }
  223. handleWherePartEvent(whereParts, part, evt, index) {
  224. switch (evt.name) {
  225. case 'get-param-options': {
  226. switch (evt.param.name) {
  227. case 'left':
  228. return this.datasource
  229. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  230. .then(this.transformToSegments({}))
  231. .catch(this.handleQueryError.bind(this));
  232. case 'right':
  233. return this.datasource
  234. .metricFindQuery(this.queryBuilder.buildValueQuery(part.params[0]))
  235. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  236. .catch(this.handleQueryError.bind(this));
  237. case 'op':
  238. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN']));
  239. default:
  240. return this.$q.when([]);
  241. }
  242. }
  243. case 'part-param-changed': {
  244. this.panelCtrl.refresh();
  245. break;
  246. }
  247. case 'action': {
  248. // remove element
  249. whereParts.splice(index, 1);
  250. this.queryModel.updatePersistedParts();
  251. this.panelCtrl.refresh();
  252. break;
  253. }
  254. case 'get-part-actions': {
  255. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  256. }
  257. }
  258. }
  259. getWhereOptions() {
  260. var options = [];
  261. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  262. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  263. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  264. return this.$q.when(options);
  265. }
  266. whereAddAction(part, index) {
  267. switch (this.whereAdd.type) {
  268. case 'macro': {
  269. this.queryModel.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  270. break;
  271. }
  272. default: {
  273. this.queryModel.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  274. }
  275. }
  276. var plusButton = this.uiSegmentSrv.newPlusButton();
  277. this.whereAdd.html = plusButton.html;
  278. this.whereAdd.value = plusButton.value;
  279. this.queryModel.updatePersistedParts();
  280. this.panelCtrl.refresh();
  281. }
  282. getGroupByOptions() {
  283. return this.datasource
  284. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  285. .then(tags => {
  286. var options = [];
  287. if (!this.queryModel.hasGroupByTime()) {
  288. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  289. }
  290. for (let tag of tags) {
  291. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  292. }
  293. return options;
  294. })
  295. .catch(this.handleQueryError.bind(this));
  296. }
  297. groupByAction() {
  298. switch (this.groupByAdd.value) {
  299. default: {
  300. this.queryModel.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  301. }
  302. }
  303. var plusButton = this.uiSegmentSrv.newPlusButton();
  304. this.groupByAdd.html = plusButton.html;
  305. this.groupByAdd.value = plusButton.value;
  306. this.panelCtrl.refresh();
  307. }
  308. handleQueryError(err) {
  309. this.error = err.message || 'Failed to issue metric query';
  310. return [];
  311. }
  312. }