Initial MVP commit
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful

This commit is contained in:
2026-03-17 08:35:16 -05:00
parent 8c092c2247
commit 27817f9e43
29 changed files with 1890 additions and 1 deletions

View File

@@ -0,0 +1,65 @@
package postgres
import (
"context"
"database/sql"
"fmt"
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
"github.com/jackc/pgx/v5/pgxpool"
)
type AlertRepository struct {
pool *pgxpool.Pool
}
func NewAlertRepository(pool *pgxpool.Pool) *AlertRepository {
return &AlertRepository{pool: pool}
}
func (r *AlertRepository) ListCurrentAlerts(ctx context.Context) ([]ports.AlertRecord, error) {
rows, err := r.pool.Query(ctx, queryCurrentAlerts)
if err != nil {
return nil, fmt.Errorf("query current alerts: %w", err)
}
defer rows.Close()
out := make([]ports.AlertRecord, 0)
for rows.Next() {
var effective sql.NullTime
var expires sql.NullTime
var severity sql.NullString
var event sql.NullString
var headline sql.NullString
var instruction sql.NullString
var description sql.NullString
if err := rows.Scan(
&effective,
&expires,
&severity,
&event,
&headline,
&instruction,
&description,
); err != nil {
return nil, fmt.Errorf("scan current alert row: %w", err)
}
out = append(out, ports.AlertRecord{
Effective: ptrTime(effective),
Expires: ptrTime(expires),
Severity: ptrString(severity),
Event: ptrString(event),
Headline: ptrString(headline),
Instruction: ptrString(instruction),
Description: ptrString(description),
})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate current alert rows: %w", err)
}
return out, nil
}

View File

@@ -0,0 +1,119 @@
package postgres
import (
"context"
"database/sql"
"fmt"
"time"
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
"github.com/jackc/pgx/v5/pgxpool"
)
type ForecastRepository struct {
pool *pgxpool.Pool
}
func NewForecastRepository(pool *pgxpool.Pool) *ForecastRepository {
return &ForecastRepository{pool: pool}
}
func (r *ForecastRepository) ListForecastPeriodsAt(ctx context.Context, ts time.Time, limit int) ([]ports.ForecastPeriodMetric, error) {
rows, err := r.pool.Query(ctx, queryForecastPeriodsAt, ts, limit)
if err != nil {
return nil, fmt.Errorf("query forecast periods at timestamp: %w", err)
}
defer rows.Close()
out := make([]ports.ForecastPeriodMetric, 0)
for rows.Next() {
var row ports.ForecastPeriodMetric
var name sql.NullString
var isDay sql.NullBool
var conditionText sql.NullString
var providerRawDescription sql.NullString
var textDescription sql.NullString
var detailedText sql.NullString
var iconURL sql.NullString
var temperature sql.NullFloat64
var temperatureMin sql.NullFloat64
var temperatureMax sql.NullFloat64
var dewpoint sql.NullFloat64
var humidity sql.NullFloat64
var windDirection sql.NullFloat64
var windSpeed sql.NullFloat64
var windGust sql.NullFloat64
var pressure sql.NullFloat64
var visibility sql.NullFloat64
var apparent sql.NullFloat64
var cloudCover sql.NullFloat64
var precipProbability sql.NullFloat64
var precipAmount sql.NullFloat64
var snowfallDepth sql.NullFloat64
var uvIndex sql.NullFloat64
if err := rows.Scan(
&row.PeriodIndex,
&row.StartTime,
&row.EndTime,
&name,
&isDay,
&row.ConditionCode,
&conditionText,
&providerRawDescription,
&textDescription,
&detailedText,
&iconURL,
&temperature,
&temperatureMin,
&temperatureMax,
&dewpoint,
&humidity,
&windDirection,
&windSpeed,
&windGust,
&pressure,
&visibility,
&apparent,
&cloudCover,
&precipProbability,
&precipAmount,
&snowfallDepth,
&uvIndex,
); err != nil {
return nil, fmt.Errorf("scan forecast period row: %w", err)
}
row.Name = ptrString(name)
row.IsDay = ptrBool(isDay)
row.ConditionText = ptrString(conditionText)
row.ProviderRawDescription = ptrString(providerRawDescription)
row.TextDescription = ptrString(textDescription)
row.DetailedText = ptrString(detailedText)
row.IconURL = ptrString(iconURL)
row.TemperatureC = ptrFloat64(temperature)
row.TemperatureCMin = ptrFloat64(temperatureMin)
row.TemperatureCMax = ptrFloat64(temperatureMax)
row.DewpointC = ptrFloat64(dewpoint)
row.RelativeHumidityPercent = ptrFloat64(humidity)
row.WindDirectionDegrees = ptrFloat64(windDirection)
row.WindSpeedKmh = ptrFloat64(windSpeed)
row.WindGustKmh = ptrFloat64(windGust)
row.BarometricPressurePa = ptrFloat64(pressure)
row.VisibilityMeters = ptrFloat64(visibility)
row.ApparentTemperatureC = ptrFloat64(apparent)
row.CloudCoverPercent = ptrFloat64(cloudCover)
row.ProbabilityOfPrecipitationPercent = ptrFloat64(precipProbability)
row.PrecipitationAmountMm = ptrFloat64(precipAmount)
row.SnowfallDepthMm = ptrFloat64(snowfallDepth)
row.UVIndex = ptrFloat64(uvIndex)
out = append(out, row)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate forecast period rows: %w", err)
}
return out, nil
}

View File

@@ -0,0 +1,106 @@
package postgres
import (
"context"
"database/sql"
"fmt"
"time"
"gitea.maximumdirect.net/ejr/weatherapi/internal/core/ports"
"github.com/jackc/pgx/v5/pgxpool"
)
type ObservationRepository struct {
pool *pgxpool.Pool
}
func NewObservationRepository(pool *pgxpool.Pool) *ObservationRepository {
return &ObservationRepository{pool: pool}
}
func (r *ObservationRepository) GetCurrentSummary(ctx context.Context, window time.Duration) (ports.ObservationSummaryMetric, error) {
var temperature sql.NullFloat64
var apparent sql.NullFloat64
if err := r.pool.QueryRow(ctx, queryObservationSummary, windowMinutes(window)).Scan(&temperature, &apparent); err != nil {
return ports.ObservationSummaryMetric{}, fmt.Errorf("query observation summary: %w", err)
}
return ports.ObservationSummaryMetric{
TemperatureC: ptrFloat64(temperature),
ApparentTemperatureC: ptrFloat64(apparent),
}, nil
}
func (r *ObservationRepository) ListCurrentConditions(ctx context.Context, window time.Duration) ([]ports.ObservationConditionMetric, error) {
rows, err := r.pool.Query(ctx, queryObservationConditions, windowMinutes(window))
if err != nil {
return nil, fmt.Errorf("query observation conditions: %w", err)
}
defer rows.Close()
out := make([]ports.ObservationConditionMetric, 0)
for rows.Next() {
var stationID sql.NullString
var observedAt time.Time
var temperature sql.NullFloat64
var textDescription sql.NullString
var providerRawDescription sql.NullString
var conditionText sql.NullString
if err := rows.Scan(
&stationID,
&observedAt,
&temperature,
&textDescription,
&providerRawDescription,
&conditionText,
); err != nil {
return nil, fmt.Errorf("scan observation condition row: %w", err)
}
out = append(out, ports.ObservationConditionMetric{
StationID: ptrString(stationID),
ObservedAt: observedAt,
TemperatureC: ptrFloat64(temperature),
TextDescription: ptrString(textDescription),
ProviderRawDescription: ptrString(providerRawDescription),
ConditionText: ptrString(conditionText),
})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate observation conditions rows: %w", err)
}
return out, nil
}
func (r *ObservationRepository) ListCurrentPrecipitationEvents(ctx context.Context, window time.Duration) ([]string, error) {
rows, err := r.pool.Query(ctx, queryObservationPrecipitation, windowMinutes(window))
if err != nil {
return nil, fmt.Errorf("query observation precipitation events: %w", err)
}
defer rows.Close()
out := make([]string, 0)
for rows.Next() {
var rawText sql.NullString
if err := rows.Scan(&rawText); err != nil {
return nil, fmt.Errorf("scan observation precipitation row: %w", err)
}
if rawText.Valid {
out = append(out, rawText.String)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate observation precipitation rows: %w", err)
}
return out, nil
}
func windowMinutes(window time.Duration) int {
return int(window / time.Minute)
}

View File

@@ -0,0 +1,81 @@
package postgres
const (
queryObservationSummary = `
SELECT
AVG(temperature_c) AS temperature_c,
AVG(apparent_temperature_c) AS apparent_temperature_c
FROM observations
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1);
`
queryObservationConditions = `
SELECT
station_id,
observed_at,
temperature_c,
text_description,
provider_raw_description,
condition_text
FROM observations
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1)
ORDER BY observed_at DESC;
`
queryObservationPrecipitation = `
SELECT
raw_text
FROM observation_present_weather
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1)
ORDER BY observed_at DESC;
`
queryForecastPeriodsAt = `
SELECT
period_index,
start_time,
end_time,
name,
is_day,
condition_code,
condition_text,
provider_raw_description,
text_description,
detailed_text,
icon_url,
temperature_c,
temperature_c_min,
temperature_c_max,
dewpoint_c,
relative_humidity_percent,
wind_direction_degrees,
wind_speed_kmh,
wind_gust_kmh,
barometric_pressure_pa,
visibility_meters,
apparent_temperature_c,
cloud_cover_percent,
probability_of_precipitation_percent,
precipitation_amount_mm,
snowfall_depth_mm,
uv_index
FROM forecast_periods
WHERE start_time < $1
AND end_time > $1
ORDER BY period_index ASC, start_time DESC
LIMIT $2;
`
queryCurrentAlerts = `
SELECT
effective,
expires,
severity,
event,
headline,
instruction,
description
FROM alerts
WHERE expires > CURRENT_TIMESTAMP;
`
)

View File

@@ -0,0 +1,38 @@
package postgres
import (
"strings"
"testing"
"gitea.maximumdirect.net/ejr/weatherapi/internal/platform/constants"
)
func TestQueriesUseParametersNotHardcodedValues(t *testing.T) {
if !strings.Contains(queryObservationSummary, "make_interval(mins => $1)") {
t.Fatalf("observation summary query must use $1 minutes parameter")
}
if strings.Contains(queryObservationSummary, "30 minutes") {
t.Fatalf("observation summary query should not hardcode 30 minutes")
}
if !strings.Contains(queryObservationConditions, "make_interval(mins => $1)") {
t.Fatalf("observation conditions query must use $1 minutes parameter")
}
if !strings.Contains(queryObservationPrecipitation, "make_interval(mins => $1)") {
t.Fatalf("observation precipitation query must use $1 minutes parameter")
}
if !strings.Contains(queryForecastPeriodsAt, "LIMIT $2") {
t.Fatalf("forecast query must use parameterized limit")
}
if strings.Contains(queryForecastPeriodsAt, "LIMIT 5") {
t.Fatalf("forecast query should not hardcode limit=5")
}
}
func TestWindowMinutesUsesObservationWindowConstant(t *testing.T) {
got := windowMinutes(constants.ObservationWindow)
if got != 30 {
t.Fatalf("expected 30 minutes from constants.ObservationWindow, got %d", got)
}
}

View File

@@ -0,0 +1,38 @@
package postgres
import (
"database/sql"
"time"
)
func ptrFloat64(v sql.NullFloat64) *float64 {
if !v.Valid {
return nil
}
f := v.Float64
return &f
}
func ptrString(v sql.NullString) *string {
if !v.Valid {
return nil
}
s := v.String
return &s
}
func ptrBool(v sql.NullBool) *bool {
if !v.Valid {
return nil
}
b := v.Bool
return &b
}
func ptrTime(v sql.NullTime) *time.Time {
if !v.Valid {
return nil
}
t := v.Time
return &t
}