query_ctrl.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import _ from 'lodash';
  2. import { PostgresQueryBuilder } from './query_builder';
  3. import { QueryCtrl } from 'app/plugins/sdk';
  4. import { SqlPart } from 'app/core/components/sql_part/sql_part';
  5. import PostgresQuery from './postgres_query';
  6. import sqlPart from './sql_part';
  7. export interface QueryMeta {
  8. sql: string;
  9. }
  10. const defaultQuery = `SELECT
  11. $__time(time_column),
  12. value1
  13. FROM
  14. metric_table
  15. WHERE
  16. $__timeFilter(time_column)
  17. `;
  18. export class PostgresQueryCtrl extends QueryCtrl {
  19. static templateUrl = 'partials/query.editor.html';
  20. showLastQuerySQL: boolean;
  21. formats: any[];
  22. queryModel: PostgresQuery;
  23. queryBuilder: PostgresQueryBuilder;
  24. lastQueryMeta: QueryMeta;
  25. lastQueryError: string;
  26. showHelp: boolean;
  27. schemaSegment: any;
  28. tableSegment: any;
  29. whereAdd: any;
  30. timeColumnSegment: any;
  31. metricColumnSegment: any;
  32. selectMenu: any[];
  33. selectModels: SqlPart[][];
  34. groupByParts: SqlPart[][];
  35. whereParts: SqlPart[][];
  36. groupByAdd: any;
  37. /** @ngInject **/
  38. constructor($scope, $injector, private templateSrv, private $q, private uiSegmentSrv) {
  39. super($scope, $injector);
  40. this.target = this.target;
  41. this.queryModel = new PostgresQuery(this.target, templateSrv, this.panel.scopedVars);
  42. this.queryBuilder = new PostgresQueryBuilder(this.target, this.queryModel);
  43. this.updateProjection();
  44. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  45. if (!this.target.rawSql) {
  46. // special handling when in table panel
  47. if (this.panelCtrl.panel.type === 'table') {
  48. this.target.format = 'table';
  49. this.target.rawSql = 'SELECT 1';
  50. } else {
  51. this.target.rawSql = defaultQuery;
  52. }
  53. }
  54. this.schemaSegment = uiSegmentSrv.newSegment(this.target.schema);
  55. if (!this.target.table) {
  56. this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
  57. } else {
  58. this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
  59. }
  60. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  61. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  62. this.buildSelectMenu();
  63. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  64. this.groupByAdd = this.uiSegmentSrv.newPlusButton();
  65. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  66. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  67. }
  68. updateProjection() {
  69. this.selectModels = _.map(this.target.select, function(parts: any) {
  70. return _.map(parts, sqlPart.create).filter(n => n);
  71. });
  72. this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
  73. this.groupByParts = _.map(this.target.groupBy, sqlPart.create).filter(n => n);
  74. }
  75. updatePersistedParts() {
  76. this.target.select = _.map(this.selectModels, function(selectParts) {
  77. return _.map(selectParts, function(part: any) {
  78. return { type: part.def.type, params: part.params };
  79. });
  80. });
  81. this.target.where = _.map(this.whereParts, function(part: any) {
  82. return { type: part.def.type, name: part.name, params: part.params };
  83. });
  84. this.target.groupBy = _.map(this.groupByParts, function(part: any) {
  85. return { type: part.def.type, params: part.params };
  86. });
  87. }
  88. buildSelectMenu() {
  89. this.selectMenu = [
  90. { text: 'Aggregate', value: 'aggregate' },
  91. { text: 'Special', value: 'special' },
  92. { text: 'Alias', value: 'alias' },
  93. { text: 'Column', value: 'column' },
  94. ];
  95. }
  96. toggleEditorMode() {
  97. this.target.rawQuery = !this.target.rawQuery;
  98. }
  99. resetPlusButton(button) {
  100. let plusButton = this.uiSegmentSrv.newPlusButton();
  101. button.html = plusButton.html;
  102. button.value = plusButton.value;
  103. }
  104. getSchemaSegments() {
  105. return this.datasource
  106. .metricFindQuery(this.queryBuilder.buildSchemaQuery())
  107. .then(this.transformToSegments({}))
  108. .catch(this.handleQueryError.bind(this));
  109. }
  110. schemaChanged() {
  111. this.target.schema = this.schemaSegment.value;
  112. this.panelCtrl.refresh();
  113. }
  114. getTableSegments() {
  115. return this.datasource
  116. .metricFindQuery(this.queryBuilder.buildTableQuery())
  117. .then(this.transformToSegments({}))
  118. .catch(this.handleQueryError.bind(this));
  119. }
  120. tableChanged() {
  121. this.target.table = this.tableSegment.value;
  122. this.panelCtrl.refresh();
  123. }
  124. getTimeColumnSegments() {
  125. return this.datasource
  126. .metricFindQuery(this.queryBuilder.buildColumnQuery('time'))
  127. .then(this.transformToSegments({}))
  128. .catch(this.handleQueryError.bind(this));
  129. }
  130. timeColumnChanged() {
  131. this.target.timeColumn = this.timeColumnSegment.value;
  132. this.panelCtrl.refresh();
  133. }
  134. getMetricColumnSegments() {
  135. return this.datasource
  136. .metricFindQuery(this.queryBuilder.buildColumnQuery('metric'))
  137. .then(this.transformToSegments({ addNone: true }))
  138. .catch(this.handleQueryError.bind(this));
  139. }
  140. metricColumnChanged() {
  141. this.target.metricColumn = this.metricColumnSegment.value;
  142. this.panelCtrl.refresh();
  143. }
  144. onDataReceived(dataList) {
  145. this.lastQueryMeta = null;
  146. this.lastQueryError = null;
  147. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  148. if (anySeriesFromQuery) {
  149. this.lastQueryMeta = anySeriesFromQuery.meta;
  150. }
  151. }
  152. onDataError(err) {
  153. if (err.data && err.data.results) {
  154. let queryRes = err.data.results[this.target.refId];
  155. if (queryRes) {
  156. this.lastQueryMeta = queryRes.meta;
  157. this.lastQueryError = queryRes.error;
  158. }
  159. }
  160. }
  161. transformToSegments(config) {
  162. return results => {
  163. let segments = _.map(results, segment => {
  164. return this.uiSegmentSrv.newSegment({
  165. value: segment.text,
  166. expandable: segment.expandable,
  167. });
  168. });
  169. if (config.addTemplateVars) {
  170. for (let variable of this.templateSrv.variables) {
  171. let value;
  172. value = '$' + variable.name;
  173. if (config.templateQuoter && variable.multi === false) {
  174. value = config.templateQuoter(value);
  175. }
  176. segments.unshift(
  177. this.uiSegmentSrv.newSegment({
  178. type: 'template',
  179. value: value,
  180. expandable: true,
  181. })
  182. );
  183. }
  184. }
  185. if (config.addNone) {
  186. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  187. }
  188. return segments;
  189. };
  190. }
  191. addSelectPart(selectParts, cat, subitem) {
  192. let partModel = sqlPart.create({ type: cat.value });
  193. partModel.def.addStrategy(selectParts, partModel, this);
  194. this.updatePersistedParts();
  195. this.panelCtrl.refresh();
  196. }
  197. removeSelectPart(selectParts, part) {
  198. if (part.def.type === 'column') {
  199. // remove all parts of column unless its last column
  200. if (this.selectModels.length > 1) {
  201. let modelsIndex = _.indexOf(this.selectModels, selectParts);
  202. this.selectModels.splice(modelsIndex, 1);
  203. }
  204. } else {
  205. let partIndex = _.indexOf(selectParts, part);
  206. selectParts.splice(partIndex, 1);
  207. }
  208. this.updatePersistedParts();
  209. }
  210. handleSelectPartEvent(selectParts, part, evt) {
  211. switch (evt.name) {
  212. case 'get-param-options': {
  213. switch (part.def.type) {
  214. case 'aggregate':
  215. return this.datasource
  216. .metricFindQuery(this.queryBuilder.buildAggregateQuery())
  217. .then(this.transformToSegments({}))
  218. .catch(this.handleQueryError.bind(this));
  219. case 'column':
  220. return this.datasource
  221. .metricFindQuery(this.queryBuilder.buildColumnQuery('value'))
  222. .then(this.transformToSegments({}))
  223. .catch(this.handleQueryError.bind(this));
  224. }
  225. }
  226. case 'part-param-changed': {
  227. this.panelCtrl.refresh();
  228. break;
  229. }
  230. case 'action': {
  231. this.removeSelectPart(selectParts, part);
  232. this.panelCtrl.refresh();
  233. break;
  234. }
  235. case 'get-part-actions': {
  236. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  237. }
  238. }
  239. }
  240. handleGroupByPartEvent(part, index, evt) {
  241. switch (evt.name) {
  242. case 'get-param-options': {
  243. return this.datasource
  244. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  245. .then(this.transformToSegments({}))
  246. .catch(this.handleQueryError.bind(this));
  247. }
  248. case 'part-param-changed': {
  249. this.panelCtrl.refresh();
  250. break;
  251. }
  252. case 'action': {
  253. this.removeGroupBy(part, index);
  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. addGroupBy(partType, value) {
  263. let params = [value];
  264. if (partType === 'time') {
  265. params = ['1m', 'none'];
  266. }
  267. let partModel = sqlPart.create({ type: partType, params: params });
  268. if (partType === 'time') {
  269. // put timeGroup at start
  270. this.groupByParts.splice(0, 0, partModel);
  271. } else {
  272. this.groupByParts.push(partModel);
  273. }
  274. // add aggregates when adding group by
  275. for (let selectParts of this.selectModels) {
  276. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  277. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  278. selectParts.splice(1, 0, aggregate);
  279. if (!selectParts.some(part => part.def.type === 'alias')) {
  280. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  281. selectParts.push(alias);
  282. }
  283. }
  284. }
  285. this.updatePersistedParts();
  286. }
  287. removeGroupBy(part, index) {
  288. if (part.def.type === 'time') {
  289. // remove aggregations
  290. this.selectModels = _.map(this.selectModels, (s: any) => {
  291. return _.filter(s, (part: any) => {
  292. if (part.def.type === 'aggregate') {
  293. return false;
  294. }
  295. return true;
  296. });
  297. });
  298. }
  299. this.groupByParts.splice(index, 1);
  300. this.updatePersistedParts();
  301. }
  302. handleWherePartEvent(whereParts, part, evt, index) {
  303. switch (evt.name) {
  304. case 'get-param-options': {
  305. switch (evt.param.name) {
  306. case 'left':
  307. return this.datasource
  308. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  309. .then(this.transformToSegments({}))
  310. .catch(this.handleQueryError.bind(this));
  311. case 'right':
  312. return this.datasource
  313. .metricFindQuery(this.queryBuilder.buildValueQuery(part.params[0]))
  314. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  315. .catch(this.handleQueryError.bind(this));
  316. case 'op':
  317. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN']));
  318. default:
  319. return this.$q.when([]);
  320. }
  321. }
  322. case 'part-param-changed': {
  323. this.panelCtrl.refresh();
  324. break;
  325. }
  326. case 'action': {
  327. // remove element
  328. whereParts.splice(index, 1);
  329. this.updatePersistedParts();
  330. this.panelCtrl.refresh();
  331. break;
  332. }
  333. case 'get-part-actions': {
  334. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  335. }
  336. }
  337. }
  338. getWhereOptions() {
  339. var options = [];
  340. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  341. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  342. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  343. return this.$q.when(options);
  344. }
  345. whereAddAction(part, index) {
  346. switch (this.whereAdd.type) {
  347. case 'macro': {
  348. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  349. break;
  350. }
  351. default: {
  352. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  353. }
  354. }
  355. this.updatePersistedParts();
  356. this.resetPlusButton(this.whereAdd);
  357. this.panelCtrl.refresh();
  358. }
  359. getGroupByOptions() {
  360. return this.datasource
  361. .metricFindQuery(this.queryBuilder.buildColumnQuery())
  362. .then(tags => {
  363. var options = [];
  364. if (!this.queryModel.hasGroupByTime()) {
  365. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  366. }
  367. for (let tag of tags) {
  368. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  369. }
  370. return options;
  371. })
  372. .catch(this.handleQueryError.bind(this));
  373. }
  374. groupByAction() {
  375. switch (this.groupByAdd.value) {
  376. default: {
  377. this.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  378. }
  379. }
  380. this.resetPlusButton(this.groupByAdd);
  381. this.panelCtrl.refresh();
  382. }
  383. handleQueryError(err) {
  384. this.error = err.message || 'Failed to issue metric query';
  385. return [];
  386. }
  387. }