query_ctrl.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import _ from 'lodash';
  2. import { PostgresMetaQuery } from './meta_query';
  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. metaBuilder: PostgresMetaQuery;
  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.metaBuilder = new PostgresMetaQuery(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.metaBuilder.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.metaBuilder.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.metaBuilder.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.metaBuilder.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, item) {
  192. let partModel = sqlPart.create({ type: item.value });
  193. let addAlias = false;
  194. switch (item.value) {
  195. case 'column':
  196. let parts = _.map(selectParts, function(part: any) {
  197. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  198. });
  199. this.selectModels.push(parts);
  200. break;
  201. case 'aggregate':
  202. case 'special':
  203. let index = _.findIndex(selectParts, (p: any) => p.def.type === item.value);
  204. if (index !== -1) {
  205. selectParts[index] = partModel;
  206. } else {
  207. selectParts.splice(1, 0, partModel);
  208. }
  209. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  210. addAlias = true;
  211. }
  212. break;
  213. case 'alias':
  214. addAlias = true;
  215. break;
  216. }
  217. if (addAlias) {
  218. // set initial alias name to column name
  219. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0]] });
  220. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  221. selectParts[selectParts.length - 1] = partModel;
  222. } else {
  223. selectParts.push(partModel);
  224. }
  225. }
  226. this.updatePersistedParts();
  227. this.panelCtrl.refresh();
  228. }
  229. removeSelectPart(selectParts, part) {
  230. if (part.def.type === 'column') {
  231. // remove all parts of column unless its last column
  232. if (this.selectModels.length > 1) {
  233. let modelsIndex = _.indexOf(this.selectModels, selectParts);
  234. this.selectModels.splice(modelsIndex, 1);
  235. }
  236. } else {
  237. let partIndex = _.indexOf(selectParts, part);
  238. selectParts.splice(partIndex, 1);
  239. }
  240. this.updatePersistedParts();
  241. }
  242. handleSelectPartEvent(selectParts, part, evt) {
  243. switch (evt.name) {
  244. case 'get-param-options': {
  245. switch (part.def.type) {
  246. case 'aggregate':
  247. return this.datasource
  248. .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  249. .then(this.transformToSegments({}))
  250. .catch(this.handleQueryError.bind(this));
  251. case 'column':
  252. return this.datasource
  253. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  254. .then(this.transformToSegments({}))
  255. .catch(this.handleQueryError.bind(this));
  256. }
  257. }
  258. case 'part-param-changed': {
  259. this.panelCtrl.refresh();
  260. break;
  261. }
  262. case 'action': {
  263. this.removeSelectPart(selectParts, part);
  264. this.panelCtrl.refresh();
  265. break;
  266. }
  267. case 'get-part-actions': {
  268. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  269. }
  270. }
  271. }
  272. handleGroupByPartEvent(part, index, evt) {
  273. switch (evt.name) {
  274. case 'get-param-options': {
  275. return this.datasource
  276. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  277. .then(this.transformToSegments({}))
  278. .catch(this.handleQueryError.bind(this));
  279. }
  280. case 'part-param-changed': {
  281. this.panelCtrl.refresh();
  282. break;
  283. }
  284. case 'action': {
  285. this.removeGroupBy(part, index);
  286. this.panelCtrl.refresh();
  287. break;
  288. }
  289. case 'get-part-actions': {
  290. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  291. }
  292. }
  293. }
  294. addGroupBy(partType, value) {
  295. let params = [value];
  296. if (partType === 'time') {
  297. params = ['1m', 'none'];
  298. }
  299. let partModel = sqlPart.create({ type: partType, params: params });
  300. if (partType === 'time') {
  301. // put timeGroup at start
  302. this.groupByParts.splice(0, 0, partModel);
  303. } else {
  304. this.groupByParts.push(partModel);
  305. }
  306. // add aggregates when adding group by
  307. for (let selectParts of this.selectModels) {
  308. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  309. let aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  310. selectParts.splice(1, 0, aggregate);
  311. if (!selectParts.some(part => part.def.type === 'alias')) {
  312. let alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  313. selectParts.push(alias);
  314. }
  315. }
  316. }
  317. this.updatePersistedParts();
  318. }
  319. removeGroupBy(part, index) {
  320. if (part.def.type === 'time') {
  321. // remove aggregations
  322. this.selectModels = _.map(this.selectModels, (s: any) => {
  323. return _.filter(s, (part: any) => {
  324. if (part.def.type === 'aggregate') {
  325. return false;
  326. }
  327. return true;
  328. });
  329. });
  330. }
  331. this.groupByParts.splice(index, 1);
  332. this.updatePersistedParts();
  333. }
  334. handleWherePartEvent(whereParts, part, evt, index) {
  335. switch (evt.name) {
  336. case 'get-param-options': {
  337. switch (evt.param.name) {
  338. case 'left':
  339. return this.datasource
  340. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  341. .then(this.transformToSegments({}))
  342. .catch(this.handleQueryError.bind(this));
  343. case 'right':
  344. return this.datasource
  345. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  346. .then(this.transformToSegments({ addTemplateVars: true, templateQuoter: this.queryModel.quoteLiteral }))
  347. .catch(this.handleQueryError.bind(this));
  348. case 'op':
  349. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '<=', '>', '>=', 'IN', 'NOT IN']));
  350. default:
  351. return this.$q.when([]);
  352. }
  353. }
  354. case 'part-param-changed': {
  355. this.panelCtrl.refresh();
  356. break;
  357. }
  358. case 'action': {
  359. // remove element
  360. whereParts.splice(index, 1);
  361. this.updatePersistedParts();
  362. this.panelCtrl.refresh();
  363. break;
  364. }
  365. case 'get-part-actions': {
  366. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  367. }
  368. }
  369. }
  370. getWhereOptions() {
  371. var options = [];
  372. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  373. // options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  374. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  375. return this.$q.when(options);
  376. }
  377. whereAddAction(part, index) {
  378. switch (this.whereAdd.type) {
  379. case 'macro': {
  380. this.whereParts.push(sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] }));
  381. break;
  382. }
  383. default: {
  384. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  385. }
  386. }
  387. this.updatePersistedParts();
  388. this.resetPlusButton(this.whereAdd);
  389. this.panelCtrl.refresh();
  390. }
  391. getGroupByOptions() {
  392. return this.datasource
  393. .metricFindQuery(this.metaBuilder.buildColumnQuery('groupby'))
  394. .then(tags => {
  395. var options = [];
  396. if (!this.queryModel.hasGroupByTime()) {
  397. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time(1m,none)' }));
  398. }
  399. for (let tag of tags) {
  400. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  401. }
  402. return options;
  403. })
  404. .catch(this.handleQueryError.bind(this));
  405. }
  406. groupByAction() {
  407. switch (this.groupByAdd.value) {
  408. default: {
  409. this.addGroupBy(this.groupByAdd.type, this.groupByAdd.value);
  410. }
  411. }
  412. this.resetPlusButton(this.groupByAdd);
  413. this.panelCtrl.refresh();
  414. }
  415. handleQueryError(err) {
  416. this.error = err.message || 'Failed to issue metric query';
  417. return [];
  418. }
  419. }