Improve multi-value variable handling
Sometimes, we had to SQL-CAST variables into Strings (VARCHAR
) as we thought it would be obligatory for Grafana.
Example
Like that.
Metric query
SELECT osm_country_code, state_and_city, name_and_id, sensor_type_name
FROM irceline_network
WHERE
station_id IN ($irceline_station_id) AND
CAST (sensor_type_id AS VARCHAR) IN ($irceline_station_sensortype)
ORDER BY osm_country_code, state_and_city, name_and_id, sensor_type_name;
which would yield
Rendered example
SELECT osm_country_code, state_and_city, name_and_id, sensor_type_name
FROM irceline_network
WHERE
station_id IN ('1234','1118') AND
CAST (sensor_type_id AS VARCHAR) IN ('482','20','391','71','10','4013','431','464','8','38','7','5','6002','6001','62106','1','62101','21','61102','61110')
ORDER BY osm_country_code, state_and_city, name_and_id, sensor_type_name;
Improvement
However, we just found through Using Variables to dynamically select Columns in MySQL - Support - Grafana Community that multi-value variables can be rendered/formatted without quoting each single value, see also Variables | Grafana Documentation.
This works like a charm, we tried it by using ${irceline_station_id:csv}
and ${irceline_station_sensortype:csv}
in the following query.
Metric query
SELECT osm_country_code, state_and_city, name_and_id, sensor_type_name
FROM irceline_network
WHERE
station_id IN (${irceline_station_id:csv}) AND
sensor_type_id IN (${irceline_station_sensortype:csv})
ORDER BY osm_country_code, state_and_city, name_and_id, sensor_type_name;
Rendered example
SELECT osm_country_code, state_and_city, name_and_id, sensor_type_name
FROM irceline_network
WHERE
station_id IN (1234,1118) AND
sensor_type_id IN (482,20,391,71,10,4013,431,464,8,38,7,5,6002,6001,62106,1,62101,21,61102,61110)
ORDER BY osm_country_code, state_and_city, name_and_id, sensor_type_name;