Skip to content

Commit

Permalink
feat: handle query interpolation multi-valued variable (#32)
Browse files Browse the repository at this point in the history
This is a follow up after PR #31. This makes it possible to query
with both single- and multi-valued variables.

After this PR, the following query in Grafana:
```sql
SELECT * FROM backend WHERE application_name IN ($application) OR duration_ms IN ($duration) OR sub = '$sub'
```

In to:
```sql
SELECT * FROM backend WHERE application_name IN ('Elfskot.Api','Elfsquad.ConfiguratorApi','Elfsquad.OdataApi') OR duration_ms IN ('30', '8') OR sub = '1ff96bd8-53d8-4214-85b9-08da00dc987f'
```

The `WHERE IN (x, y, z)` with single quotes seems to work for both
numbers & strings. The logic in the formatter might need to be improved
for more complex data types.

---------

Signed-off-by: Stan van Rooy <[email protected]>
Signed-off-by: Stan van Rooy <[email protected]>
  • Loading branch information
stanvanrooy authored Aug 31, 2023
1 parent 56a7167 commit f5b2453
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
const end = range!.to;

const calls = options.targets.map(target => {
const query = getTemplateSrv().replace(target.queryText, options.scopedVars);
const query = getTemplateSrv().replace(target.queryText, options.scopedVars, this.formatter);

const request = {
"query": query,
Expand Down Expand Up @@ -90,6 +90,13 @@ export class DataSource extends DataSourceApi<MyQuery, MyDataSourceOptions> {
};
}

private formatter(value: string | string[], options: any): string {
if (options.multi) {
return (value as string[]).map(v => `'${v}'`).join(',');
}
return value as string;
}

async metricFindQuery(query: string, options?: any): Promise<MetricFindValue[]> {
const to = new Date();
const from = new Date();
Expand Down

0 comments on commit f5b2453

Please sign in to comment.