query_ctrl.ts 20 KB

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