From 6b496a39ee38f5593a09799b7b9aafbb9f42746d Mon Sep 17 00:00:00 2001 From: Pieter Hollander Date: Sat, 4 Oct 2025 01:56:08 +0200 Subject: [PATCH] small refactor --- main.go | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/main.go b/main.go index b6041cf..c0a24d6 100644 --- a/main.go +++ b/main.go @@ -178,6 +178,17 @@ type Config struct { var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil)) var config Config +const timescaleHypertableSQL = ` +-- CREATE EXTENSION IF NOT EXISTS timescaledb; +SELECT create_hypertable('opendtu_log', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_inverters', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_inverters_ac', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_inverters_dc', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_inverters_inv', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_events', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +SELECT create_hypertable('opendtu_hints', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); +` + // LoadConfig attempts to read the configuration from options.json // If it fails, it falls back to using environment variables func loadConfig() (Config, error) { @@ -399,26 +410,18 @@ func migrateDB(db *sql.DB) { if err != nil { log.Fatal("Error performing database migrations: ", err) } - timescaleEnabled := config.TimescaleDB - - enableTimescaleDB := ` - -- CREATE EXTENSION IF NOT EXISTS timescaledb; - SELECT create_hypertable('opendtu_log', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_inverters', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_inverters_ac', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_inverters_dc', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_inverters_inv', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_events', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - SELECT create_hypertable('opendtu_hints', 'timestamp', if_not_exists => TRUE, migrate_data => TRUE); - ` - if timescaleEnabled { - _, err := db.Exec(enableTimescaleDB) - if err != nil { + if config.TimescaleDB { + if err := enableTimescaleHypertables(db); err != nil { log.Fatal("Error enabling TimescaleDB: ", err) } } } +func enableTimescaleHypertables(db *sql.DB) error { + _, err := db.Exec(timescaleHypertableSQL) + return err +} + func insertLiveData(db *sql.DB, inverter Inverter, total Total, hints Hints) { timeZone := config.TZ loc, _ := time.LoadLocation(timeZone)