66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
package meteo
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
b "github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type Repository interface {
|
|
InsertAcceptedMeteoData(ctx context.Context, data []MeteoData) (int, error)
|
|
InsertRejectedMeteoData(ctx context.Context, data []RejectedMeteoData) (int, error)
|
|
}
|
|
|
|
type pgxRepo struct {
|
|
*pgxpool.Pool
|
|
}
|
|
|
|
func NewPGXRepo(pool *pgxpool.Pool) Repository {
|
|
return &pgxRepo{
|
|
pool,
|
|
}
|
|
}
|
|
|
|
const insertAcceptedMeteoData = `insert into public.meteo_data (location_id, max_temp, min_temp, rainfall, cloudiness, created_at) values ($1, $2, $3, $4, $5, $6) returning id`
|
|
|
|
func (pgx *pgxRepo) InsertAcceptedMeteoData(ctx context.Context, data []MeteoData) (int, error) {
|
|
// TODO pass context
|
|
// TODO improve transaction
|
|
tx, err := pgx.Begin(ctx)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("error starting transaction: %w", err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
batch := &b.Batch{}
|
|
|
|
for _, d := range data {
|
|
// TODO get city id before insert!
|
|
batch.Queue(insertAcceptedMeteoData, 1, d.MaxTemp, d.MinTemp, d.Rainfall, d.Cloudiness, d.Timestamp)
|
|
}
|
|
|
|
results := tx.SendBatch(ctx, batch)
|
|
|
|
for i := range data {
|
|
_, err := results.Exec()
|
|
if err != nil {
|
|
results.Close()
|
|
return 0, fmt.Errorf("error executing batch command %d: %w", i, err)
|
|
}
|
|
}
|
|
|
|
results.Close()
|
|
|
|
if err = tx.Commit(ctx); err != nil {
|
|
return 0, fmt.Errorf("error committing transaction: %w", err)
|
|
}
|
|
|
|
return 0, nil
|
|
}
|
|
|
|
func (pgx *pgxRepo) InsertRejectedMeteoData(ctx context.Context, data []RejectedMeteoData) (int, error) {
|
|
return 0, nil
|
|
}
|