Class: Grafana::SqlDatasource

Inherits:
AbstractDatasource show all
Defined in:
lib/grafana/sql_datasource.rb

Overview

Implements the interface to all SQL based datasources (tested with PostgreSQL and MariaDB/MySQL).

Instance Attribute Summary

Attributes inherited from AbstractDatasource

#model

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AbstractDatasource

build_instance, #category, #id, inherited, #initialize, #name, #replace_variables, #type, #uid

Constructor Details

This class inherits a constructor from Grafana::AbstractDatasource

Class Method Details

.handles?(model) ⇒ Boolean

Returns:

  • (Boolean)

See Also:



7
8
9
10
# File 'lib/grafana/sql_datasource.rb', line 7

def self.handles?(model)
  tmp = new(model)
  tmp.category == 'sql'
end

Instance Method Details

#default_variable_formatObject



65
66
67
# File 'lib/grafana/sql_datasource.rb', line 65

def default_variable_format
    'glob'
end

#raw_query_from_panel_model(panel_query_target) ⇒ Object

Currently all composed SQL queries are saved in the dashboard as rawSql, so no conversion necessary here.



60
61
62
# File 'lib/grafana/sql_datasource.rb', line 60

def raw_query_from_panel_model(panel_query_target)
  panel_query_target['rawSql']
end

#request(query_description) ⇒ Object

:raw_query needs to contain a SQL query as String in the respective database dialect



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/grafana/sql_datasource.rb', line 14

def request(query_description)
  raise MissingSqlQueryError if query_description[:raw_query].nil?

  sql = replace_variables(query_description[:raw_query], query_description[:variables])
  webrequest = query_description[:prepared_request]
  request = {}

  ver = query_description[:grafana_version].split('.').map{|x| x.to_i}
  if ver[0] >= 8
    webrequest.relative_url = '/api/ds/query'
    request = {
      body: {
        from: query_description[:from],
        to: query_description[:to],
        queries: [{
          datasource: { type: type, uid: uid },
          datasourceId: id,
          rawSql: sql,
          format: 'table',
          # intervalMs: '',
          # maxDataPoints: 999,
          refId: 'A'
        }]
      }.to_json,
      request: Net::HTTP::Post
    }
  else
    webrequest.relative_url = '/api/tsdb/query'
    request = {
      body: {
        from: query_description[:from],
        to: query_description[:to],
        queries: [rawSql: sql, datasourceId: id, format: 'table']
      }.to_json,
      request: Net::HTTP::Post
    }
  end
  webrequest.options.merge!(request)

  result = webrequest.execute(query_description[:timeout])
  preformat_response(result.body)
end