query_ctrl.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import _ from 'lodash';
  2. import appEvents from 'app/core/app_events';
  3. import { MysqlMetaQuery } from './meta_query';
  4. import { QueryCtrl } from 'app/plugins/sdk';
  5. import { SqlPart } from 'app/core/components/sql_part/sql_part';
  6. import MysqlQuery from './mysql_query';
  7. import sqlPart from './sql_part';
  8. import { auto, IQService } from 'angular';
  9. import { TemplateSrv } from 'app/features/templating/template_srv';
  10. export interface QueryMeta {
  11. sql: string;
  12. }
  13. const defaultQuery = `SELECT
  14. UNIX_TIMESTAMP(<time_column>) as time_sec,
  15. <value column> as value,
  16. <series name column> as metric
  17. FROM <table name>
  18. WHERE $__timeFilter(time_column)
  19. ORDER BY <time_column> ASC
  20. `;
  21. export class MysqlQueryCtrl extends QueryCtrl {
  22. static templateUrl = 'partials/query.editor.html';
  23. showLastQuerySQL: boolean;
  24. formats: any[];
  25. lastQueryMeta: QueryMeta;
  26. lastQueryError: string;
  27. showHelp: boolean;
  28. queryModel: MysqlQuery;
  29. metaBuilder: MysqlMetaQuery;
  30. tableSegment: any;
  31. whereAdd: any;
  32. timeColumnSegment: any;
  33. metricColumnSegment: any;
  34. selectMenu: any[];
  35. selectParts: SqlPart[][];
  36. groupParts: SqlPart[];
  37. whereParts: SqlPart[];
  38. groupAdd: any;
  39. /** @ngInject */
  40. constructor(
  41. $scope: any,
  42. $injector: auto.IInjectorService,
  43. private templateSrv: TemplateSrv,
  44. private $q: IQService,
  45. private uiSegmentSrv: any
  46. ) {
  47. super($scope, $injector);
  48. this.target = this.target;
  49. this.queryModel = new MysqlQuery(this.target, templateSrv, this.panel.scopedVars);
  50. this.metaBuilder = new MysqlMetaQuery(this.target, this.queryModel);
  51. this.updateProjection();
  52. this.formats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  53. if (!this.target.rawSql) {
  54. // special handling when in table panel
  55. if (this.panelCtrl.panel.type === 'table') {
  56. this.target.format = 'table';
  57. this.target.rawSql = 'SELECT 1';
  58. this.target.rawQuery = true;
  59. } else {
  60. this.target.rawSql = defaultQuery;
  61. this.datasource.metricFindQuery(this.metaBuilder.findMetricTable()).then((result: any) => {
  62. if (result.length > 0) {
  63. this.target.table = result[0].text;
  64. let segment = this.uiSegmentSrv.newSegment(this.target.table);
  65. this.tableSegment.html = segment.html;
  66. this.tableSegment.value = segment.value;
  67. this.target.timeColumn = result[1].text;
  68. segment = this.uiSegmentSrv.newSegment(this.target.timeColumn);
  69. this.timeColumnSegment.html = segment.html;
  70. this.timeColumnSegment.value = segment.value;
  71. this.target.timeColumnType = 'timestamp';
  72. this.target.select = [[{ type: 'column', params: [result[2].text] }]];
  73. this.updateProjection();
  74. this.panelCtrl.refresh();
  75. }
  76. });
  77. }
  78. }
  79. if (!this.target.table) {
  80. this.tableSegment = uiSegmentSrv.newSegment({ value: 'select table', fake: true });
  81. } else {
  82. this.tableSegment = uiSegmentSrv.newSegment(this.target.table);
  83. }
  84. this.timeColumnSegment = uiSegmentSrv.newSegment(this.target.timeColumn);
  85. this.metricColumnSegment = uiSegmentSrv.newSegment(this.target.metricColumn);
  86. this.buildSelectMenu();
  87. this.whereAdd = this.uiSegmentSrv.newPlusButton();
  88. this.groupAdd = this.uiSegmentSrv.newPlusButton();
  89. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  90. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  91. }
  92. updateProjection() {
  93. this.selectParts = _.map(this.target.select, (parts: any) => {
  94. return _.map(parts, sqlPart.create).filter(n => n);
  95. });
  96. this.whereParts = _.map(this.target.where, sqlPart.create).filter(n => n);
  97. this.groupParts = _.map(this.target.group, sqlPart.create).filter(n => n);
  98. }
  99. updatePersistedParts() {
  100. this.target.select = _.map(this.selectParts, selectParts => {
  101. return _.map(selectParts, (part: any) => {
  102. return { type: part.def.type, datatype: part.datatype, params: part.params };
  103. });
  104. });
  105. this.target.where = _.map(this.whereParts, (part: any) => {
  106. return { type: part.def.type, datatype: part.datatype, name: part.name, params: part.params };
  107. });
  108. this.target.group = _.map(this.groupParts, (part: any) => {
  109. return { type: part.def.type, datatype: part.datatype, params: part.params };
  110. });
  111. }
  112. buildSelectMenu() {
  113. this.selectMenu = [];
  114. const aggregates = {
  115. text: 'Aggregate Functions',
  116. value: 'aggregate',
  117. submenu: [
  118. { text: 'Average', value: 'avg' },
  119. { text: 'Count', value: 'count' },
  120. { text: 'Maximum', value: 'max' },
  121. { text: 'Minimum', value: 'min' },
  122. { text: 'Sum', value: 'sum' },
  123. { text: 'Standard deviation', value: 'stddev' },
  124. { text: 'Variance', value: 'variance' },
  125. ],
  126. };
  127. this.selectMenu.push(aggregates);
  128. this.selectMenu.push({ text: 'Alias', value: 'alias' });
  129. this.selectMenu.push({ text: 'Column', value: 'column' });
  130. }
  131. toggleEditorMode() {
  132. if (this.target.rawQuery) {
  133. appEvents.emit('confirm-modal', {
  134. title: 'Warning',
  135. text2: 'Switching to query builder may overwrite your raw SQL.',
  136. icon: 'fa-exclamation',
  137. yesText: 'Switch',
  138. onConfirm: () => {
  139. this.target.rawQuery = !this.target.rawQuery;
  140. },
  141. });
  142. } else {
  143. this.target.rawQuery = !this.target.rawQuery;
  144. }
  145. }
  146. resetPlusButton(button: { html: any; value: any }) {
  147. const plusButton = this.uiSegmentSrv.newPlusButton();
  148. button.html = plusButton.html;
  149. button.value = plusButton.value;
  150. }
  151. getTableSegments() {
  152. return this.datasource
  153. .metricFindQuery(this.metaBuilder.buildTableQuery())
  154. .then(this.transformToSegments({}))
  155. .catch(this.handleQueryError.bind(this));
  156. }
  157. tableChanged() {
  158. this.target.table = this.tableSegment.value;
  159. this.target.where = [];
  160. this.target.group = [];
  161. this.updateProjection();
  162. const segment = this.uiSegmentSrv.newSegment('none');
  163. this.metricColumnSegment.html = segment.html;
  164. this.metricColumnSegment.value = segment.value;
  165. this.target.metricColumn = 'none';
  166. const task1 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('time')).then((result: any) => {
  167. // check if time column is still valid
  168. if (result.length > 0 && !_.find(result, (r: any) => r.text === this.target.timeColumn)) {
  169. const segment = this.uiSegmentSrv.newSegment(result[0].text);
  170. this.timeColumnSegment.html = segment.html;
  171. this.timeColumnSegment.value = segment.value;
  172. }
  173. return this.timeColumnChanged(false);
  174. });
  175. const task2 = this.datasource.metricFindQuery(this.metaBuilder.buildColumnQuery('value')).then((result: any) => {
  176. if (result.length > 0) {
  177. this.target.select = [[{ type: 'column', params: [result[0].text] }]];
  178. this.updateProjection();
  179. }
  180. });
  181. this.$q.all([task1, task2]).then(() => {
  182. this.panelCtrl.refresh();
  183. });
  184. }
  185. getTimeColumnSegments() {
  186. return this.datasource
  187. .metricFindQuery(this.metaBuilder.buildColumnQuery('time'))
  188. .then(this.transformToSegments({}))
  189. .catch(this.handleQueryError.bind(this));
  190. }
  191. timeColumnChanged(refresh?: boolean) {
  192. this.target.timeColumn = this.timeColumnSegment.value;
  193. return this.datasource
  194. .metricFindQuery(this.metaBuilder.buildDatatypeQuery(this.target.timeColumn))
  195. .then((result: any) => {
  196. if (result.length === 1) {
  197. if (this.target.timeColumnType !== result[0].text) {
  198. this.target.timeColumnType = result[0].text;
  199. }
  200. let partModel;
  201. if (this.queryModel.hasUnixEpochTimecolumn()) {
  202. partModel = sqlPart.create({ type: 'macro', name: '$__unixEpochFilter', params: [] });
  203. } else {
  204. partModel = sqlPart.create({ type: 'macro', name: '$__timeFilter', params: [] });
  205. }
  206. if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
  207. // replace current macro
  208. this.whereParts[0] = partModel;
  209. } else {
  210. this.whereParts.splice(0, 0, partModel);
  211. }
  212. }
  213. this.updatePersistedParts();
  214. if (refresh !== false) {
  215. this.panelCtrl.refresh();
  216. }
  217. });
  218. }
  219. getMetricColumnSegments() {
  220. return this.datasource
  221. .metricFindQuery(this.metaBuilder.buildColumnQuery('metric'))
  222. .then(this.transformToSegments({ addNone: true }))
  223. .catch(this.handleQueryError.bind(this));
  224. }
  225. metricColumnChanged() {
  226. this.target.metricColumn = this.metricColumnSegment.value;
  227. this.panelCtrl.refresh();
  228. }
  229. onDataReceived(dataList: any) {
  230. this.lastQueryMeta = null;
  231. this.lastQueryError = null;
  232. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  233. if (anySeriesFromQuery) {
  234. this.lastQueryMeta = anySeriesFromQuery.meta;
  235. }
  236. }
  237. onDataError(err: any) {
  238. if (err.data && err.data.results) {
  239. const queryRes = err.data.results[this.target.refId];
  240. if (queryRes) {
  241. this.lastQueryMeta = queryRes.meta;
  242. this.lastQueryError = queryRes.error;
  243. }
  244. }
  245. }
  246. transformToSegments(config: any) {
  247. return (results: any) => {
  248. const segments = _.map(results, segment => {
  249. return this.uiSegmentSrv.newSegment({
  250. value: segment.text,
  251. expandable: segment.expandable,
  252. });
  253. });
  254. if (config.addTemplateVars) {
  255. for (const variable of this.templateSrv.variables) {
  256. let value;
  257. value = '$' + variable.name;
  258. if (config.templateQuoter && variable.multi === false) {
  259. value = config.templateQuoter(value);
  260. }
  261. segments.unshift(
  262. this.uiSegmentSrv.newSegment({
  263. type: 'template',
  264. value: value,
  265. expandable: true,
  266. })
  267. );
  268. }
  269. }
  270. if (config.addNone) {
  271. segments.unshift(this.uiSegmentSrv.newSegment({ type: 'template', value: 'none', expandable: true }));
  272. }
  273. return segments;
  274. };
  275. }
  276. findAggregateIndex(selectParts: any) {
  277. return _.findIndex(selectParts, (p: any) => p.def.type === 'aggregate' || p.def.type === 'percentile');
  278. }
  279. findWindowIndex(selectParts: any) {
  280. return _.findIndex(selectParts, (p: any) => p.def.type === 'window' || p.def.type === 'moving_window');
  281. }
  282. addSelectPart(selectParts: any[], item: { value: any }, subItem: { type: any; value: any }) {
  283. let partType = item.value;
  284. if (subItem && subItem.type) {
  285. partType = subItem.type;
  286. }
  287. let partModel = sqlPart.create({ type: partType });
  288. if (subItem) {
  289. partModel.params[0] = subItem.value;
  290. }
  291. let addAlias = false;
  292. switch (partType) {
  293. case 'column':
  294. const parts = _.map(selectParts, (part: any) => {
  295. return sqlPart.create({ type: part.def.type, params: _.clone(part.params) });
  296. });
  297. this.selectParts.push(parts);
  298. break;
  299. case 'percentile':
  300. case 'aggregate':
  301. // add group by if no group by yet
  302. if (this.target.group.length === 0) {
  303. this.addGroup('time', '$__interval');
  304. }
  305. const aggIndex = this.findAggregateIndex(selectParts);
  306. if (aggIndex !== -1) {
  307. // replace current aggregation
  308. selectParts[aggIndex] = partModel;
  309. } else {
  310. selectParts.splice(1, 0, partModel);
  311. }
  312. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  313. addAlias = true;
  314. }
  315. break;
  316. case 'moving_window':
  317. case 'window':
  318. const windowIndex = this.findWindowIndex(selectParts);
  319. if (windowIndex !== -1) {
  320. // replace current window function
  321. selectParts[windowIndex] = partModel;
  322. } else {
  323. const aggIndex = this.findAggregateIndex(selectParts);
  324. if (aggIndex !== -1) {
  325. selectParts.splice(aggIndex + 1, 0, partModel);
  326. } else {
  327. selectParts.splice(1, 0, partModel);
  328. }
  329. }
  330. if (!_.find(selectParts, (p: any) => p.def.type === 'alias')) {
  331. addAlias = true;
  332. }
  333. break;
  334. case 'alias':
  335. addAlias = true;
  336. break;
  337. }
  338. if (addAlias) {
  339. // set initial alias name to column name
  340. partModel = sqlPart.create({ type: 'alias', params: [selectParts[0].params[0].replace(/"/g, '')] });
  341. if (selectParts[selectParts.length - 1].def.type === 'alias') {
  342. selectParts[selectParts.length - 1] = partModel;
  343. } else {
  344. selectParts.push(partModel);
  345. }
  346. }
  347. this.updatePersistedParts();
  348. this.panelCtrl.refresh();
  349. }
  350. removeSelectPart(selectParts: any, part: { def: { type: string } }) {
  351. if (part.def.type === 'column') {
  352. // remove all parts of column unless its last column
  353. if (this.selectParts.length > 1) {
  354. const modelsIndex = _.indexOf(this.selectParts, selectParts);
  355. this.selectParts.splice(modelsIndex, 1);
  356. }
  357. } else {
  358. const partIndex = _.indexOf(selectParts, part);
  359. selectParts.splice(partIndex, 1);
  360. }
  361. this.updatePersistedParts();
  362. }
  363. handleSelectPartEvent(selectParts: any, part: { def: any }, evt: { name: any }) {
  364. switch (evt.name) {
  365. case 'get-param-options': {
  366. switch (part.def.type) {
  367. // case 'aggregate':
  368. // return this.datasource
  369. // .metricFindQuery(this.metaBuilder.buildAggregateQuery())
  370. // .then(this.transformToSegments({}))
  371. // .catch(this.handleQueryError.bind(this));
  372. case 'column':
  373. return this.datasource
  374. .metricFindQuery(this.metaBuilder.buildColumnQuery('value'))
  375. .then(this.transformToSegments({}))
  376. .catch(this.handleQueryError.bind(this));
  377. }
  378. }
  379. case 'part-param-changed': {
  380. this.updatePersistedParts();
  381. this.panelCtrl.refresh();
  382. break;
  383. }
  384. case 'action': {
  385. this.removeSelectPart(selectParts, part);
  386. this.panelCtrl.refresh();
  387. break;
  388. }
  389. case 'get-part-actions': {
  390. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  391. }
  392. }
  393. }
  394. handleGroupPartEvent(part: any, index: any, evt: { name: any }) {
  395. switch (evt.name) {
  396. case 'get-param-options': {
  397. return this.datasource
  398. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  399. .then(this.transformToSegments({}))
  400. .catch(this.handleQueryError.bind(this));
  401. }
  402. case 'part-param-changed': {
  403. this.updatePersistedParts();
  404. this.panelCtrl.refresh();
  405. break;
  406. }
  407. case 'action': {
  408. this.removeGroup(part, index);
  409. this.panelCtrl.refresh();
  410. break;
  411. }
  412. case 'get-part-actions': {
  413. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  414. }
  415. }
  416. }
  417. addGroup(partType: string, value: string) {
  418. let params = [value];
  419. if (partType === 'time') {
  420. params = ['$__interval', 'none'];
  421. }
  422. const partModel = sqlPart.create({ type: partType, params: params });
  423. if (partType === 'time') {
  424. // put timeGroup at start
  425. this.groupParts.splice(0, 0, partModel);
  426. } else {
  427. this.groupParts.push(partModel);
  428. }
  429. // add aggregates when adding group by
  430. for (const selectParts of this.selectParts) {
  431. if (!selectParts.some(part => part.def.type === 'aggregate')) {
  432. const aggregate = sqlPart.create({ type: 'aggregate', params: ['avg'] });
  433. selectParts.splice(1, 0, aggregate);
  434. if (!selectParts.some(part => part.def.type === 'alias')) {
  435. const alias = sqlPart.create({ type: 'alias', params: [selectParts[0].part.params[0]] });
  436. selectParts.push(alias);
  437. }
  438. }
  439. }
  440. this.updatePersistedParts();
  441. }
  442. removeGroup(part: { def: { type: string } }, index: number) {
  443. if (part.def.type === 'time') {
  444. // remove aggregations
  445. this.selectParts = _.map(this.selectParts, (s: any) => {
  446. return _.filter(s, (part: any) => {
  447. if (part.def.type === 'aggregate' || part.def.type === 'percentile') {
  448. return false;
  449. }
  450. return true;
  451. });
  452. });
  453. }
  454. this.groupParts.splice(index, 1);
  455. this.updatePersistedParts();
  456. }
  457. handleWherePartEvent(whereParts: any, part: any, evt: any, index: any) {
  458. switch (evt.name) {
  459. case 'get-param-options': {
  460. switch (evt.param.name) {
  461. case 'left':
  462. return this.datasource
  463. .metricFindQuery(this.metaBuilder.buildColumnQuery())
  464. .then(this.transformToSegments({}))
  465. .catch(this.handleQueryError.bind(this));
  466. case 'right':
  467. if (['int', 'bigint', 'double', 'datetime'].indexOf(part.datatype) > -1) {
  468. // don't do value lookups for numerical fields
  469. return this.$q.when([]);
  470. } else {
  471. return this.datasource
  472. .metricFindQuery(this.metaBuilder.buildValueQuery(part.params[0]))
  473. .then(
  474. this.transformToSegments({
  475. addTemplateVars: true,
  476. templateQuoter: (v: string) => {
  477. return this.queryModel.quoteLiteral(v);
  478. },
  479. })
  480. )
  481. .catch(this.handleQueryError.bind(this));
  482. }
  483. case 'op':
  484. return this.$q.when(this.uiSegmentSrv.newOperators(this.metaBuilder.getOperators(part.datatype)));
  485. default:
  486. return this.$q.when([]);
  487. }
  488. }
  489. case 'part-param-changed': {
  490. this.updatePersistedParts();
  491. this.datasource.metricFindQuery(this.metaBuilder.buildDatatypeQuery(part.params[0])).then((d: any) => {
  492. if (d.length === 1) {
  493. part.datatype = d[0].text;
  494. }
  495. });
  496. this.panelCtrl.refresh();
  497. break;
  498. }
  499. case 'action': {
  500. // remove element
  501. whereParts.splice(index, 1);
  502. this.updatePersistedParts();
  503. this.panelCtrl.refresh();
  504. break;
  505. }
  506. case 'get-part-actions': {
  507. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  508. }
  509. }
  510. }
  511. getWhereOptions() {
  512. const options = [];
  513. if (this.queryModel.hasUnixEpochTimecolumn()) {
  514. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__unixEpochFilter' }));
  515. } else {
  516. options.push(this.uiSegmentSrv.newSegment({ type: 'macro', value: '$__timeFilter' }));
  517. }
  518. options.push(this.uiSegmentSrv.newSegment({ type: 'expression', value: 'Expression' }));
  519. return this.$q.when(options);
  520. }
  521. addWhereAction(part: any, index: number) {
  522. switch (this.whereAdd.type) {
  523. case 'macro': {
  524. const partModel = sqlPart.create({ type: 'macro', name: this.whereAdd.value, params: [] });
  525. if (this.whereParts.length >= 1 && this.whereParts[0].def.type === 'macro') {
  526. // replace current macro
  527. this.whereParts[0] = partModel;
  528. } else {
  529. this.whereParts.splice(0, 0, partModel);
  530. }
  531. break;
  532. }
  533. default: {
  534. this.whereParts.push(sqlPart.create({ type: 'expression', params: ['value', '=', 'value'] }));
  535. }
  536. }
  537. this.updatePersistedParts();
  538. this.resetPlusButton(this.whereAdd);
  539. this.panelCtrl.refresh();
  540. }
  541. getGroupOptions() {
  542. return this.datasource
  543. .metricFindQuery(this.metaBuilder.buildColumnQuery('group'))
  544. .then((tags: any) => {
  545. const options = [];
  546. if (!this.queryModel.hasTimeGroup()) {
  547. options.push(this.uiSegmentSrv.newSegment({ type: 'time', value: 'time($__interval,none)' }));
  548. }
  549. for (const tag of tags) {
  550. options.push(this.uiSegmentSrv.newSegment({ type: 'column', value: tag.text }));
  551. }
  552. return options;
  553. })
  554. .catch(this.handleQueryError.bind(this));
  555. }
  556. addGroupAction() {
  557. switch (this.groupAdd.value) {
  558. default: {
  559. this.addGroup(this.groupAdd.type, this.groupAdd.value);
  560. }
  561. }
  562. this.resetPlusButton(this.groupAdd);
  563. this.panelCtrl.refresh();
  564. }
  565. handleQueryError(err: any): any[] {
  566. this.error = err.message || 'Failed to issue metric query';
  567. return [];
  568. }
  569. }