Friday 25 March 2022

HomeAssistant Core 2022.3.+ and SQL integration

I'm using the sql integration for Home Assistant to query saved sensor data on a MS SQL Server container. The latest HomeAssistant Core release (2022.3 series) is based on Alpine linux and it looks like freetds is no longer included in the container's OS baseline, and this caused pyodbc to return errors saying it couldn't load the FreeTDS driver.

To work around this problem I've set up a HomeAssistant integration that runs on startup and calls a shell command to install freetds and put entries into /etc/odbcinit.ini, so my HomeAssistant is able to make SQL queries again :)

Instructions below are inspired by elRadix's posts in the following HA Community Thread: https://community.home-assistant.io/t/use-apt-get-commands/236873/4

Changes:

Create /config/scripts/startup.sh with the following contents:

#!/bin/sh
echo "Updating Image with freetds"
apk update
apk add freetds

cat >/etc/odbcinst.ini <<EOL
[FreeTDS]
Description             = FreeTDS unixODBC Driver
Driver          = /usr/lib/libtdsodbc.so.0
Setup           = /usr/lib/libtdsodbc.so.0
UsageCount              = 1
EOL

Run the following to give the script permission to execute:

chmod +x /config/scripts/startup.sh

At the end of configuration.yaml, add the following to create a new shell command:

shell_command:
  setup: "/config/scripts/startup.sh"

Add the following to automations.yaml:

- id: startup_1
  initial_state: true
  alias: System Startup Scripts
  trigger:
    platform: homeassistant
    event: start
  action:
    - service: shell_command.setup

Restart HA core and SQL Server queries should start working.