query_ctrl.ts 14 KB

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