2025-12-05 09:22:23 +08:00

111 lines
2.6 KiB
Go

package data
import (
"context"
"database/sql"
"fmt"
"strings"
)
// GetStationName returns stations.name by station_id; empty string if not found/null.
func GetStationName(ctx context.Context, stationID string) (string, error) {
const q = `SELECT COALESCE(name, '') FROM stations WHERE station_id = $1`
var name sql.NullString
err := DB().QueryRowContext(ctx, q, stationID).Scan(&name)
if err != nil {
if err == sql.ErrNoRows {
return "", nil
}
return "", err
}
if name.Valid {
return name.String, nil
}
return "", nil
}
// StationInfo contains minimal fields for alert checks.
type StationInfo struct {
ID string
Name string
Location string
Latitude float64
Longitude float64
Altitude float64
}
// ListEligibleStations returns WH65LP stations with required non-empty fields.
func ListEligibleStations(ctx context.Context) ([]StationInfo, error) {
const q = `
SELECT
station_id,
COALESCE(NULLIF(BTRIM(name), ''), station_id) AS name,
location,
latitude::float8,
longitude::float8,
altitude::float8
FROM stations
WHERE
device_type = 'WH65LP' AND
name IS NOT NULL AND BTRIM(name) <> '' AND
location IS NOT NULL AND BTRIM(location) <> '' AND
latitude IS NOT NULL AND latitude <> 0 AND
longitude IS NOT NULL AND longitude <> 0 AND
altitude IS NOT NULL AND altitude <> 0`
rows, err := DB().QueryContext(ctx, q)
if err != nil {
return nil, err
}
defer rows.Close()
var out []StationInfo
for rows.Next() {
var st StationInfo
if err := rows.Scan(&st.ID, &st.Name, &st.Location, &st.Latitude, &st.Longitude, &st.Altitude); err != nil {
continue
}
out = append(out, st)
}
return out, nil
}
// ListStationsByIDs returns stations by a given id list (ignores missing ones).
func ListStationsByIDs(ctx context.Context, ids []string) ([]StationInfo, error) {
if len(ids) == 0 {
return nil, nil
}
var placeholders []string
args := make([]interface{}, 0, len(ids))
for i, id := range ids {
placeholders = append(placeholders, fmt.Sprintf("$%d", i+1))
args = append(args, id)
}
q := fmt.Sprintf(`
SELECT
station_id,
COALESCE(NULLIF(BTRIM(name), ''), station_id) AS name,
location,
latitude::float8,
longitude::float8,
altitude::float8
FROM stations
WHERE station_id IN (%s)`, strings.Join(placeholders, ","))
rows, err := DB().QueryContext(ctx, q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []StationInfo
for rows.Next() {
var st StationInfo
if err := rows.Scan(&st.ID, &st.Name, &st.Location, &st.Latitude, &st.Longitude, &st.Altitude); err != nil {
continue
}
out = append(out, st)
}
return out, nil
}