add context propagation
This commit is contained in:
@@ -9,8 +9,8 @@ import (
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
InsertAcceptedMeteoData(data []MeteoData) (int, error)
|
||||
InsertRejectedMeteoData(data []RejectedMeteoData) (int, error)
|
||||
InsertAcceptedMeteoData(ctx context.Context, data []MeteoData) (int, error)
|
||||
InsertRejectedMeteoData(ctx context.Context, data []RejectedMeteoData) (int, error)
|
||||
}
|
||||
|
||||
type pgxRepo struct {
|
||||
@@ -25,22 +25,23 @@ func NewPGXRepo(pool *pgxpool.Pool) Repository {
|
||||
|
||||
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
|
||||
func (pgx *pgxRepo) InsertAcceptedMeteoData(ctx context.Context, data []MeteoData) (int, error) {
|
||||
// TODO pass context
|
||||
// TODO improve transaction
|
||||
tx, err := pgx.Begin(context.Background())
|
||||
tx, err := pgx.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("error starting transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
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(context.Background(), batch)
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
|
||||
for i := range data {
|
||||
_, err := results.Exec()
|
||||
@@ -52,13 +53,13 @@ func (pgx *pgxRepo) InsertAcceptedMeteoData(data []MeteoData) (int, error) {
|
||||
|
||||
results.Close()
|
||||
|
||||
if err = tx.Commit(context.Background()); err != nil {
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return 0, fmt.Errorf("error committing transaction: %w", err)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (pgx *pgxRepo) InsertRejectedMeteoData(data []RejectedMeteoData) (int, error) {
|
||||
func (pgx *pgxRepo) InsertRejectedMeteoData(ctx context.Context, data []RejectedMeteoData) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user