query_ctrl.ts 1.9 KB

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