Skip to content

Commit d1c9760

Browse files
authored
Postgres Data Source (grafana#9475)
* add postgresql datasource * add rest of files for postgres datasource * fix timeseries query, remove unused code * consistent naming, refactoring * s/mysql/postgres/ * s/mysql/postgres/ * couple more tests * tests for more datatypes * fix macros for postgres * add __timeSec macro * add frontend for postgres datasource * adjust documentation * fix formatting * add proper plugin description * merge editor changes from mysql * port changes from mysql datasource * set proper defaultQuery for postgres * add time_sec to timeseries query accept int for value for timeseries query * revert allowing time_sec and handle int or float values as unix timestamp for "time" column * fix tslint error * handle decimal values in timeseries query * allow setting sslmode for postgres datasource * use type switch for handling data types * fix value for timeseries query * refactor timeseries queries to make them more flexible * remove debug statement from inner loop in type conversion * use plain for loop in getTypedRowData * fix timeseries queries * adjust postgres datasource to tsdb refactoring * adjust postgres datasource to frontend changes * update lib/pq to latest version * move type conversion to getTypedRowData * handle address types cidr, inet and macaddr * adjust response parser and docs for annotations * convert unknown types to string * add documentation for postgres datasource * add another example query with metric column * set more helpful default query * update help text in query editor * handle NULL in value column of timeseries query * add __timeGroup macro * add test for __timeGroup macro * document __timeGroup and set proper default query for annotations * fix typos in docs * add postgres to list of datasources * add postgres to builtInPlugins * mysql: refactoring as prep for merging postgres Refactors out the initialization of the xorm engine and the query logic for an sql data source. * mysql: rename refactoring + test update * postgres:refactor to use SqlEngine(same as mysql) Refactored to use a common base class with the MySql data source. Other changes from the original PR: - Changed time column to be time_sec to allow other time units in the future and to be the same as MySQL - Changed integration test to test the main Query method rather than the private transformToTable method - Changed the __timeSec macro name to __timeEpoch - Renamed PostgresExecutor to PostgresQueryEndpoint Fixes grafana#9209 (the original PR) * postgres: encrypt password on config page With some other cosmetic changes to the config page: - placeholder texts - reset button for the password after it has been encrypted. - default value for the sslmode field. * postgres: change back col name to time from time_sec * postgres mysql: remove annotation title Title has been removed from annotations * postgres: fix images for docs page * postgres mysql: fix specs
1 parent 630e6f5 commit d1c9760

36 files changed

+2231
-478
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
+++
2+
title = "Using PostgreSQL in Grafana"
3+
description = "Guide for using PostgreSQL in Grafana"
4+
keywords = ["grafana", "postgresql", "guide"]
5+
type = "docs"
6+
[menu.docs]
7+
name = "PostgreSQL"
8+
parent = "datasources"
9+
weight = 7
10+
+++
11+
12+
# Using PostgreSQL in Grafana
13+
14+
Grafana ships with a built-in PostgreSQL data source plugin that allows you to query and visualize data from a PostgreSQL compatible database.
15+
16+
## Adding the data source
17+
18+
1. Open the side menu by clicking the Grafana icon in the top header.
19+
2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`.
20+
3. Click the `+ Add data source` button in the top header.
21+
4. Select *PostgreSQL* from the *Type* dropdown.
22+
23+
### Database User Permissions (Important!)
24+
25+
The database user you specify when you add the data source should only be granted SELECT permissions on
26+
the specified database & tables you want to query. Grafana does not validate that the query is safe. The query
27+
could include any SQL statement. For example, statements like `DELETE FROM user;` and `DROP TABLE user;` would be
28+
executed. To protect against this we **Highly** recommmend you create a specific postgresql user with restricted permissions.
29+
30+
Example:
31+
32+
```sql
33+
CREATE USER grafanareader WITH PASSWORD 'password';
34+
GRANT USAGE ON SCHEMA schema TO grafanareader;
35+
GRANT SELECT ON schema.table TO grafanareader;
36+
```
37+
38+
Make sure the user does not get any unwanted privileges from the public role.
39+
40+
## Macros
41+
42+
To simplify syntax and to allow for dynamic parts, like date range filters, the query can contain macros.
43+
44+
Macro example | Description
45+
------------ | -------------
46+
*$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time*
47+
*$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time*
48+
*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*
49+
*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*
50+
*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*
51+
*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int*
52+
*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*
53+
*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*
54+
*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*
55+
56+
We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo.
57+
58+
The query editor has a link named `Generated SQL` that shows up after a query as been executed, while in panel edit mode. Click on it and it will expand and show the raw interpolated SQL string that was executed.
59+
60+
## Table queries
61+
62+
If the `Format as` query option is set to `Table` then you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns & rows your query returns.
63+
64+
Query editor with example query:
65+
66+
![](/img/docs/v46/postgres_table_query.png)
67+
68+
69+
The query:
70+
71+
```sql
72+
SELECT
73+
title as "Title",
74+
"user".login as "Created By",
75+
dashboard.created as "Created On"
76+
FROM dashboard
77+
INNER JOIN "user" on "user".id = dashboard.created_by
78+
WHERE $__timeFilter(dashboard.created)
79+
```
80+
81+
You can control the name of the Table panel columns by using regular `as ` SQL column selection syntax.
82+
83+
The resulting table panel:
84+
85+
![](/img/docs/v46/postgres_table.png)
86+
87+
### Time series queries
88+
89+
If you set `Format as` to `Time series`, for use in Graph panel for example, then the query must return a column named `time` that returns either a sql datetime or any numeric datatype representing unix epoch in seconds.
90+
Any column except `time` and `metric` is treated as a value column.
91+
You may return a column named `metric` that is used as metric name for the value column.
92+
93+
Example with `metric` column
94+
95+
```sql
96+
SELECT
97+
min(time_date_time) as time,
98+
min(value_double),
99+
'min' as metric
100+
FROM test_data
101+
WHERE $__timeFilter(time_date_time)
102+
GROUP BY metric1, (extract(epoch from time_date_time)/extract(epoch from $__interval::interval))::int
103+
ORDER BY time asc
104+
```
105+
106+
Example with multiple columns:
107+
108+
```sql
109+
SELECT
110+
min(time_date_time) as time,
111+
min(value_double) as min_value,
112+
max(value_double) as max_value
113+
FROM test_data
114+
WHERE $__timeFilter(time_date_time)
115+
GROUP BY metric1, (extract(epoch from time_date_time)/extract(epoch from $__interval::interval))::int
116+
ORDER BY time asc
117+
```
118+
119+
## Templating
120+
121+
Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard.
122+
123+
Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables.
124+
125+
### Query Variable
126+
127+
If you add a template variable of the type `Query`, you can write a PostgreSQL query that can
128+
return things like measurement names, key names or key values that are shown as a dropdown select box.
129+
130+
For example, you can have a variable that contains all values for the `hostname` column in a table if you specify a query like this in the templating variable *Query* setting.
131+
132+
```sql
133+
SELECT hostname FROM host
134+
```
135+
136+
A query can return multiple columns and Grafana will automatically create a list from them. For example, the query below will return a list with values from `hostname` and `hostname2`.
137+
138+
```sql
139+
SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city
140+
```
141+
142+
Another option is a query that can create a key/value variable. The query should return two columns that are named `__text` and `__value`. The `__text` column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with `hostname` as the text and `id` as the value:
143+
144+
```sql
145+
SELECT hostname AS __text, id AS __value FROM host
146+
```
147+
148+
You can also create nested variables. For example if you had another variable named `region`. Then you could have
149+
the hosts variable only show hosts from the current selected region with a query like this (if `region` is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values):
150+
151+
```sql
152+
SELECT hostname FROM host WHERE region IN($region)
153+
```
154+
155+
### Using Variables in Queries
156+
157+
Template variables are quoted automatically so if it is a string value do not wrap them in quotes in where clauses. If the variable is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values.
158+
159+
There are two syntaxes:
160+
161+
`$<varname>` Example with a template variable named `hostname`:
162+
163+
```sql
164+
SELECT
165+
atimestamp as time,
166+
aint as value
167+
FROM table
168+
WHERE $__timeFilter(atimestamp) and hostname in($hostname)
169+
ORDER BY atimestamp ASC
170+
```
171+
172+
`[[varname]]` Example with a template variable named `hostname`:
173+
174+
```sql
175+
SELECT
176+
atimestamp as time,
177+
aint as value
178+
FROM table
179+
WHERE $__timeFilter(atimestamp) and hostname in([[hostname]])
180+
ORDER BY atimestamp ASC
181+
```
182+
183+
## Alerting
184+
185+
Time series queries should work in alerting conditions. Table formatted queries is not yet supported in alert rule
186+
conditions.

pkg/cmd/grafana-server/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import (
2626
_ "github.com/grafana/grafana/pkg/tsdb/influxdb"
2727
_ "github.com/grafana/grafana/pkg/tsdb/mysql"
2828
_ "github.com/grafana/grafana/pkg/tsdb/opentsdb"
29-
29+
_ "github.com/grafana/grafana/pkg/tsdb/postgres"
3030
_ "github.com/grafana/grafana/pkg/tsdb/prometheus"
3131
_ "github.com/grafana/grafana/pkg/tsdb/testdata"
3232
)

pkg/models/datasource.go

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const (
1717
DS_CLOUDWATCH = "cloudwatch"
1818
DS_KAIROSDB = "kairosdb"
1919
DS_PROMETHEUS = "prometheus"
20+
DS_POSTGRES = "postgres"
2021
DS_ACCESS_DIRECT = "direct"
2122
DS_ACCESS_PROXY = "proxy"
2223
)
@@ -62,6 +63,7 @@ var knownDatasourcePlugins map[string]bool = map[string]bool{
6263
DS_CLOUDWATCH: true,
6364
DS_PROMETHEUS: true,
6465
DS_OPENTSDB: true,
66+
DS_POSTGRES: true,
6567
"opennms": true,
6668
"druid": true,
6769
"dalmatinerdb": true,

pkg/tsdb/mysql/macros.go

+8-13
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,21 @@ import (
1111
const rsIdentifier = `([_a-zA-Z0-9]+)`
1212
const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
1313

14-
type SqlMacroEngine interface {
15-
Interpolate(sql string) (string, error)
16-
}
17-
1814
type MySqlMacroEngine struct {
1915
TimeRange *tsdb.TimeRange
2016
}
2117

22-
func NewMysqlMacroEngine(timeRange *tsdb.TimeRange) SqlMacroEngine {
23-
return &MySqlMacroEngine{
24-
TimeRange: timeRange,
25-
}
18+
func NewMysqlMacroEngine() tsdb.SqlMacroEngine {
19+
return &MySqlMacroEngine{}
2620
}
2721

28-
func (m *MySqlMacroEngine) Interpolate(sql string) (string, error) {
22+
func (m *MySqlMacroEngine) Interpolate(timeRange *tsdb.TimeRange, sql string) (string, error) {
23+
m.TimeRange = timeRange
2924
rExp, _ := regexp.Compile(sExpr)
3025
var macroError error
3126

32-
sql = ReplaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
33-
res, err := m.EvaluateMacro(groups[1], groups[2:])
27+
sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
28+
res, err := m.evaluateMacro(groups[1], groups[2:])
3429
if err != nil && macroError == nil {
3530
macroError = err
3631
return "macro_error()"
@@ -45,7 +40,7 @@ func (m *MySqlMacroEngine) Interpolate(sql string) (string, error) {
4540
return sql, nil
4641
}
4742

48-
func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
43+
func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
4944
result := ""
5045
lastIndex := 0
5146

@@ -62,7 +57,7 @@ func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]str
6257
return result + str[lastIndex:]
6358
}
6459

65-
func (m *MySqlMacroEngine) EvaluateMacro(name string, args []string) (string, error) {
60+
func (m *MySqlMacroEngine) evaluateMacro(name string, args []string) (string, error) {
6661
switch name {
6762
case "__time":
6863
if len(args) == 0 {

pkg/tsdb/mysql/macros_test.go

+10-36
Original file line numberDiff line numberDiff line change
@@ -9,86 +9,60 @@ import (
99

1010
func TestMacroEngine(t *testing.T) {
1111
Convey("MacroEngine", t, func() {
12+
engine := &MySqlMacroEngine{}
13+
timeRange := &tsdb.TimeRange{From: "5m", To: "now"}
1214

1315
Convey("interpolate __time function", func() {
14-
engine := &MySqlMacroEngine{}
15-
16-
sql, err := engine.Interpolate("select $__time(time_column)")
16+
sql, err := engine.Interpolate(nil, "select $__time(time_column)")
1717
So(err, ShouldBeNil)
1818

1919
So(sql, ShouldEqual, "select UNIX_TIMESTAMP(time_column) as time_sec")
2020
})
2121

2222
Convey("interpolate __time function wrapped in aggregation", func() {
23-
engine := &MySqlMacroEngine{}
24-
25-
sql, err := engine.Interpolate("select min($__time(time_column))")
23+
sql, err := engine.Interpolate(nil, "select min($__time(time_column))")
2624
So(err, ShouldBeNil)
2725

2826
So(sql, ShouldEqual, "select min(UNIX_TIMESTAMP(time_column) as time_sec)")
2927
})
3028

3129
Convey("interpolate __timeFilter function", func() {
32-
engine := &MySqlMacroEngine{
33-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
34-
}
35-
36-
sql, err := engine.Interpolate("WHERE $__timeFilter(time_column)")
30+
sql, err := engine.Interpolate(timeRange, "WHERE $__timeFilter(time_column)")
3731
So(err, ShouldBeNil)
3832

3933
So(sql, ShouldEqual, "WHERE time_column >= FROM_UNIXTIME(18446744066914186738) AND time_column <= FROM_UNIXTIME(18446744066914187038)")
4034
})
4135

4236
Convey("interpolate __timeFrom function", func() {
43-
engine := &MySqlMacroEngine{
44-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
45-
}
46-
47-
sql, err := engine.Interpolate("select $__timeFrom(time_column)")
37+
sql, err := engine.Interpolate(timeRange, "select $__timeFrom(time_column)")
4838
So(err, ShouldBeNil)
4939

5040
So(sql, ShouldEqual, "select FROM_UNIXTIME(18446744066914186738)")
5141
})
5242

5343
Convey("interpolate __timeTo function", func() {
54-
engine := &MySqlMacroEngine{
55-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
56-
}
57-
58-
sql, err := engine.Interpolate("select $__timeTo(time_column)")
44+
sql, err := engine.Interpolate(timeRange, "select $__timeTo(time_column)")
5945
So(err, ShouldBeNil)
6046

6147
So(sql, ShouldEqual, "select FROM_UNIXTIME(18446744066914187038)")
6248
})
6349

6450
Convey("interpolate __unixEpochFilter function", func() {
65-
engine := &MySqlMacroEngine{
66-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
67-
}
68-
69-
sql, err := engine.Interpolate("select $__unixEpochFilter(18446744066914186738)")
51+
sql, err := engine.Interpolate(timeRange, "select $__unixEpochFilter(18446744066914186738)")
7052
So(err, ShouldBeNil)
7153

7254
So(sql, ShouldEqual, "select 18446744066914186738 >= 18446744066914186738 AND 18446744066914186738 <= 18446744066914187038")
7355
})
7456

7557
Convey("interpolate __unixEpochFrom function", func() {
76-
engine := &MySqlMacroEngine{
77-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
78-
}
79-
80-
sql, err := engine.Interpolate("select $__unixEpochFrom()")
58+
sql, err := engine.Interpolate(timeRange, "select $__unixEpochFrom()")
8159
So(err, ShouldBeNil)
8260

8361
So(sql, ShouldEqual, "select 18446744066914186738")
8462
})
8563

8664
Convey("interpolate __unixEpochTo function", func() {
87-
engine := &MySqlMacroEngine{
88-
TimeRange: &tsdb.TimeRange{From: "5m", To: "now"},
89-
}
90-
91-
sql, err := engine.Interpolate("select $__unixEpochTo()")
65+
sql, err := engine.Interpolate(timeRange, "select $__unixEpochTo()")
9266
So(err, ShouldBeNil)
9367

9468
So(sql, ShouldEqual, "select 18446744066914187038")

0 commit comments

Comments
 (0)