65 lines
1.5 KiB
Go
65 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(data []MeteoData) (int, error)
|
|
InsertRejectedMeteoData(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(data []MeteoData) (int, error) {
|
|
// TODO: pass context
|
|
// TODO improve transaction
|
|
tx, err := pgx.Begin(context.Background())
|
|
if err != nil {
|
|
return 0, fmt.Errorf("error starting transaction: %w", err)
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
|
|
batch := &b.Batch{}
|
|
|
|
for _, d := range data {
|
|
batch.Queue(insertAcceptedMeteoData, 1, d.MaxTemp, d.MinTemp, d.Rainfall, d.Cloudiness, d.Timestamp)
|
|
}
|
|
|
|
results := tx.SendBatch(context.Background(), 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(context.Background()); err != nil {
|
|
return 0, fmt.Errorf("error committing transaction: %w", err)
|
|
}
|
|
|
|
return 0, nil
|
|
}
|
|
|
|
func (pgx *pgxRepo) InsertRejectedMeteoData(data []RejectedMeteoData) (int, error) {
|
|
return 0, nil
|
|
}
|