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