diff --git a/docs/sources/features/datasources/mysql.md b/docs/sources/features/datasources/mysql.md index 2072e6a4f7b..9c208ad3d37 100644 --- a/docs/sources/features/datasources/mysql.md +++ b/docs/sources/features/datasources/mysql.md @@ -29,8 +29,7 @@ data from a MySQL compatible database. The database user you specify when you add the data source should only be granted SELECT permissions on the specified database & tables you want to query. Grafana does not validate that the query is safe. The query could include any SQL statement. For example, statements like `USE otherdb;` and `DROP TABLE user;` would be -executed. To protect against this we **Highly** recommmend you create a specific mysql user with -restricted permissions. +executed. To protect against this we **Highly** recommmend you create a specific mysql user with restricted permissions. Example: @@ -49,11 +48,9 @@ Macro example | Description ------------ | ------------- *$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > FROM_UNIXTIME(1494410783) AND dateColumn < FROM_UNIXTIME(1494497183)* -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. +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. -The query editor has a link named `Generated SQL` that show 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. +The query editor has a link named `Generated SQL` that show 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. ## Table queries @@ -109,8 +106,63 @@ This is something we plan to add. ## Templating -You can use variables in your queries but there are currently no support for defining `Query` variables -that target a MySQL data source. +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. + +Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. + +### Query Variable + +If you add a template variable of the type `Query`, you can write a MySQL query that can +return things like measurement names, key names or key values that are shown as a dropdown select box. + +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. + +```sql +SELECT hostname FROM my_host +``` + +A query can returns 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`. + +```sql +SELECT my_host.hostname, my_other_host.hostname2 FROM my_host JOIN my_other_host ON my_host.city = my_other_host.city +``` + +You can also create nested variables. For example if you had another variable named `region`. Then you could have +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): + +```sql +SELECT hostname FROM my_host WHERE region IN($region) +``` + +### Using Variables in Queries + +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. + +There are two syntaxes: + +`$` Example with a template variable named `hostname`: + +```sql +SELECT + UNIX_TIMESTAMP(atimestamp) as time_sec, + aint as value, + avarchar as metric +FROM my_table +WHERE $__timeFilter(atimestamp) and hostname in($hostname) +ORDER BY atimestamp ASC +``` + +`[[varname]]` Example with a template variable named `hostname`: + +```sql +SELECT + UNIX_TIMESTAMP(atimestamp) as time_sec, + aint as value, + avarchar as metric +FROM my_table +WHERE $__timeFilter(atimestamp) and hostname in([[hostname]]) +ORDER BY atimestamp ASC +``` ## Alerting diff --git a/public/app/features/templating/query_variable.ts b/public/app/features/templating/query_variable.ts index 04d642547b0..257f6b49dc6 100644 --- a/public/app/features/templating/query_variable.ts +++ b/public/app/features/templating/query_variable.ts @@ -128,7 +128,7 @@ export class QueryVariable implements Variable { } metricFindQuery(datasource, query) { - var options = {range: undefined}; + var options = {range: undefined, variable: this}; if (this.refresh === 2) { options.range = this.timeSrv.timeRange(); diff --git a/public/app/plugins/datasource/mysql/datasource.ts b/public/app/plugins/datasource/mysql/datasource.ts index d2603bf8514..54857789a3c 100644 --- a/public/app/plugins/datasource/mysql/datasource.ts +++ b/public/app/plugins/datasource/mysql/datasource.ts @@ -14,11 +14,11 @@ export class MysqlDatasource { interpolateVariable(value) { if (typeof value === 'string') { - return '\"' + value + '\"'; + return '\'' + value + '\''; } var quotedValues = _.map(value, function(val) { - return '\"' + val + '\"'; + return '\'' + val + '\''; }); return quotedValues.join(','); } @@ -114,6 +114,48 @@ export class MysqlDatasource { return list; } + metricFindQuery(query, optionalOptions) { + let refId = 'tempvar'; + if (optionalOptions && optionalOptions.variable && optionalOptions.variable.name) { + refId = optionalOptions.variable.name; + } + + const interpolatedQuery = { + refId: refId, + datasourceId: this.id, + rawSql: this.templateSrv.replace(query, {}, this.interpolateVariable), + format: 'table', + }; + + return this.backendSrv.datasourceRequest({ + url: '/api/tsdb/query', + method: 'POST', + data: { + queries: [interpolatedQuery], + } + }) + .then(this.transformFindQueryResponse.bind(this, refId)); + } + + transformFindQueryResponse(refId, results) { + if (!results || results.data.length === 0 || results.data.results[refId].meta.rowCount === 0) { return []; } + + const rows = results.data.results[refId].tables[0].rows; + const res = []; + for (let i = 0; i < rows.length; i++) { + for (let j = 0; j < rows[i].length; j++) { + const value = rows[i][j]; + if ( res.indexOf( value ) === -1 ) { + res.push(value); + } + } + } + + return _.map(res, value => { + return { text: value}; + }); + } + testDatasource() { return this.backendSrv.datasourceRequest({ url: '/api/tsdb/query', diff --git a/public/app/plugins/datasource/mysql/specs/datasource_specs.ts b/public/app/plugins/datasource/mysql/specs/datasource_specs.ts index 3a82293fb61..a229e387b70 100644 --- a/public/app/plugins/datasource/mysql/specs/datasource_specs.ts +++ b/public/app/plugins/datasource/mysql/specs/datasource_specs.ts @@ -76,4 +76,42 @@ describe('MySQLDatasource', function() { }); }); + describe('When performing metricFindQuery', function() { + let results; + const query = 'select * from atable'; + const response = { + results: { + tempvar: { + meta: { + rowCount: 3 + }, + refId: 'tempvar', + tables: [ + { + columns: [{text: 'time_sec'}, {text: 'title'}, {text: 'text'}], + rows: [ + ['aTitle', 'some text'], + ['aTitle2', 'some text2'], + ['aTitle3', 'some text3'] + ] + } + ] + } + } + }; + + beforeEach(function() { + ctx.backendSrv.datasourceRequest = function(options) { + return ctx.$q.when({data: response, status: 200}); + }; + ctx.ds.metricFindQuery(query).then(function(data) { results = data; }); + ctx.$rootScope.$apply(); + }); + + it('should return list of all column values', function() { + expect(results.length).to.be(6); + expect(results[0].text).to.be('aTitle'); + expect(results[5].text).to.be('some text3'); + }); + }); });