45 lines
1.5 KiB
Go

package database
import (
"context"
"time"
)
type Triad struct {
OpenMeteo float64
Caiyun float64
Imdroid float64
}
// GetWeightsCurrent returns the last saved triad and its issued_at for a station.
// If no row exists, returns ok=false.
func GetWeightsCurrent(ctx context.Context, stationID string) (triad Triad, lastIssued time.Time, ok bool, err error) {
db := GetDB()
row := db.QueryRowContext(ctx, `
SELECT w_open_meteo, w_caiyun, w_imdroid, last_issued_at
FROM forecast_weights_current
WHERE station_id=$1`, stationID)
var w1, w2, w3 float64
var li time.Time
if e := row.Scan(&w1, &w2, &w3, &li); e != nil {
return Triad{}, time.Time{}, false, nil
}
return Triad{OpenMeteo: w1, Caiyun: w2, Imdroid: w3}, li, true, nil
}
// UpsertWeightsCurrent saves the triad snapshot for the station.
func UpsertWeightsCurrent(ctx context.Context, stationID string, triad Triad, issued time.Time) error {
db := GetDB()
_, err := db.ExecContext(ctx, `
INSERT INTO forecast_weights_current (station_id, w_open_meteo, w_caiyun, w_imdroid, last_issued_at, updated_at)
VALUES ($1,$2,$3,$4,$5, NOW())
ON CONFLICT (station_id)
DO UPDATE SET w_open_meteo=EXCLUDED.w_open_meteo,
w_caiyun=EXCLUDED.w_caiyun,
w_imdroid=EXCLUDED.w_imdroid,
last_issued_at=EXCLUDED.last_issued_at,
updated_at=NOW()`,
stationID, triad.OpenMeteo, triad.Caiyun, triad.Imdroid, issued)
return err
}