query_ctrl.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import {MysqlDatasource} from './datasource';
  5. import {QueryCtrl} from 'app/plugins/sdk';
  6. export interface MysqlQuery {
  7. refId: string;
  8. format: string;
  9. alias: string;
  10. rawSql: string;
  11. }
  12. export interface QueryMeta {
  13. sql: string;
  14. }
  15. const defaultQuery = `SELECT
  16. UNIX_TIMESTAMP(<time_column>) as time_sec,
  17. <value column> as value,
  18. <series name column> as metric
  19. FROM <table name>
  20. WHERE $__timeFilter(time_column)
  21. ORDER BY <time_column> ASC
  22. `;
  23. export class MysqlQueryCtrl extends QueryCtrl {
  24. static templateUrl = 'partials/query.editor.html';
  25. showLastQuerySQL: boolean;
  26. formats: any[];
  27. target: MysqlQuery;
  28. lastQueryMeta: QueryMeta;
  29. lastQueryError: string;
  30. showHelp: boolean;
  31. /** @ngInject **/
  32. constructor($scope, $injector) {
  33. super($scope, $injector);
  34. this.target.format = this.target.format || 'time_series';
  35. this.target.alias = "";
  36. this.formats = [
  37. {text: 'Time series', value: 'time_series'},
  38. {text: 'Table', value: 'table'},
  39. ];
  40. if (!this.target.rawSql) {
  41. // special handling when in table panel
  42. if (this.panelCtrl.panel.type === 'table') {
  43. this.target.format = 'table';
  44. this.target.rawSql = "SELECT 1";
  45. } else {
  46. this.target.rawSql = defaultQuery;
  47. }
  48. }
  49. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  50. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  51. }
  52. onDataReceived(dataList) {
  53. this.lastQueryMeta = null;
  54. this.lastQueryError = null;
  55. let anySeriesFromQuery = _.find(dataList, {refId: this.target.refId});
  56. if (anySeriesFromQuery) {
  57. this.lastQueryMeta = anySeriesFromQuery.meta;
  58. }
  59. }
  60. onDataError(err) {
  61. if (err.data && err.data.results) {
  62. let queryRes = err.data.results[this.target.refId];
  63. if (queryRes) {
  64. this.lastQueryMeta = queryRes.meta;
  65. this.lastQueryError = queryRes.error;
  66. }
  67. }
  68. }
  69. }