77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
// conditions_read.go executes current-conditions queries.
|
|
// Layer: adapters/outbound/postgres conditions feature.
|
|
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gitea.maximumdirect.net/ejr/weatherapi/internal/app"
|
|
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
|
|
)
|
|
|
|
func (r *Repository) CurrentConditions(ctx context.Context, observationWindowMinutes int) (*app.CurrentConditions, error) {
|
|
if r == nil || r.db == nil {
|
|
return nil, fmt.Errorf("postgres repository is not configured")
|
|
}
|
|
|
|
var row currentConditionsRow
|
|
err := r.db.QueryRowContext(ctx, queryCurrentConditions, observationWindowMinutes).Scan(
|
|
&row.SampleCount,
|
|
&row.TemperatureC,
|
|
&row.ApparentTemperatureC,
|
|
&row.DewpointC,
|
|
&row.RelativeHumidityPercent,
|
|
&row.WindSpeedKmh,
|
|
&row.WindDirectionDegrees,
|
|
&row.IsDay,
|
|
)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query current conditions: %w", err)
|
|
}
|
|
|
|
if row.SampleCount == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
candidates, err := r.currentConditionsConditionCodeCandidates(ctx, observationWindowMinutes)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return mapCurrentConditionsRow(row, selectCurrentConditionsConditionCode(candidates)), nil
|
|
}
|
|
|
|
func (r *Repository) currentConditionsConditionCodeCandidates(ctx context.Context, observationWindowMinutes int) ([]currentConditionsConditionCodeCandidate, error) {
|
|
rows, err := r.db.QueryContext(ctx, queryCurrentConditionsConditionCodeCandidates, observationWindowMinutes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query current conditions condition code candidates: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var candidates []currentConditionsConditionCodeCandidate
|
|
for rows.Next() {
|
|
var (
|
|
eventSource string
|
|
conditionCode int64
|
|
)
|
|
if err := rows.Scan(&eventSource, &conditionCode); err != nil {
|
|
return nil, fmt.Errorf("scan current conditions condition code candidate: %w", err)
|
|
}
|
|
candidates = append(candidates, currentConditionsConditionCodeCandidate{
|
|
EventSource: eventSource,
|
|
ConditionCode: model.WMOCode(conditionCode),
|
|
})
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("iterate current conditions condition code candidates: %w", err)
|
|
}
|
|
|
|
return candidates, nil
|
|
}
|