query_ctrl.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  35. if (!this.target.rawSql) {
  36. // special handling when in table panel
  37. if (this.panelCtrl.panel.type === 'table') {
  38. this.target.format = 'table';
  39. this.target.rawSql = 'SELECT 1';
  40. } else {
  41. this.target.rawSql = defaultQuery;
  42. }
  43. }
  44. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  45. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  46. }
  47. onDataReceived(dataList) {
  48. this.lastQueryMeta = null;
  49. this.lastQueryError = null;
  50. let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId });
  51. if (anySeriesFromQuery) {
  52. this.lastQueryMeta = anySeriesFromQuery.meta;
  53. }
  54. }
  55. onDataError(err) {
  56. if (err.data && err.data.results) {
  57. let queryRes = err.data.results[this.target.refId];
  58. if (queryRes) {
  59. this.lastQueryMeta = queryRes.meta;
  60. this.lastQueryError = queryRes.error;
  61. }
  62. }
  63. }
  64. }