query_ctrl.ts 2.0 KB

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