The SQL Integration currently supports use of the value_template configuration variable to allow definition of a template to extract a value from the payload.
However, it does not currently support the use of a query_template configuration variable to allow for a dynamically defined SQL query.
The use case I have is to be able to lookup a friendly text for error codes. Normally, I would use a template sensor to achieve this, but there are two concerns with doing this:
We embed data in our configuration files. That isn’t too bad, but it does mean that a restart is required if a software update on your device has resulted in new or changed error codes and/or descriptions. It’s like a form of hard coding.
When the number of error codes is large, the resulting configuration will become large and somewhat unwieldy and difficult to maintain. In my use case there are 229 possible error codes.
Hence, I’m wondering if it would be possible to add template support to the query configuration variable in the SQL integration please. I think it would be very powerful and a valuable capability.
An example of the type of configuration that would then be allowed (no matter how many trip codes exist) is below:
- platform: sql
db_url: sqlite:////local_db/local.db
queries:
- name: Trip 0 Text
query: "SELECT * FROM lookup WHERE Code = {{states('sensor.dx_trip_0')}};"
column: 'Friendly Text'
To achieve the same outcome through using a template sensor would result in configuration like this:
Same situation here. I’m trying to look up a friendly base station name from a BSSID string, and I can’t find any examples of dynamically constructing the query based on other sensor values. Was this ever resolved?
FWIW, here’s what I’m currently using. It’s a little more concise than using a whole bunch of if statements. (Not sure my BSSID’s could be used maliciously, but I’ll mask parts of them with ** anyway.) It returns the friendly name if it’s on the list, or just the BSSID string if it isn’t.
My workaround is to use external program (or script), which retrives the data from HA’s database. This program exists within HA as a command line sensor, which accepts templates, so you can pass SQL parameters as command line args, e.g.:
- sensor:
name: "Jogging, distances and times, summary"
command: "/config/jogging_summary {{ states('input_datetime.start_date') }} {{ states('input_datetime.end_date') }}"
scan_interval: 315360000 # disable automatic updates of this sensor
“/config/jogging_summary” writes the results to std output. That goes to sensor’s state. If the result is too long, you can put it into an attribute.
The hardest part was to make the program/script. I had no luck with Python in HA, so I ended up putting my program into Proxmox host and calling it via ssh.