ms-tester/internal/storage/participants.go

80 lines
1.8 KiB
Go
Raw Normal View History

2024-08-18 14:54:08 +00:00
package storage
import (
"context"
2024-08-20 22:54:46 +00:00
"git.sch9.ru/new_gate/ms-tester/internal/models"
2024-08-18 14:54:08 +00:00
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
)
type ParticipantStorage struct {
db *sqlx.DB
logger *zap.Logger
}
func NewParticipantStorage(db *sqlx.DB, logger *zap.Logger) *ParticipantStorage {
return &ParticipantStorage{
db: db,
logger: logger,
}
}
func (storage *ParticipantStorage) CreateParticipant(ctx context.Context, participant *models.Participant) (int32, error) {
query := storage.db.Rebind(`
INSERT INTO participants
(user_id,contest_id,name)
VALUES (?,?,?)
RETURNING id
`)
rows, err := storage.db.QueryxContext(
ctx,
query,
participant.UserId,
participant.ContestId,
2024-08-20 22:54:46 +00:00
participant.Name,
2024-08-18 14:54:08 +00:00
)
if err != nil {
2024-08-20 22:54:46 +00:00
return 0, handlePgErr(err)
2024-08-18 14:54:08 +00:00
}
defer rows.Close()
var id int32
err = rows.StructScan(&id)
if err != nil {
2024-08-20 22:54:46 +00:00
return 0, handlePgErr(err)
2024-08-18 14:54:08 +00:00
}
return id, nil
}
func (storage *ParticipantStorage) ReadParticipantById(ctx context.Context, id int32) (*models.Participant, error) {
var participant models.Participant
query := storage.db.Rebind("SELECT * from participants WHERE id=? LIMIT 1")
err := storage.db.GetContext(ctx, &participant, query, id)
if err != nil {
2024-08-20 22:54:46 +00:00
return nil, handlePgErr(err)
2024-08-18 14:54:08 +00:00
}
return &participant, nil
}
2024-08-20 22:54:46 +00:00
func (storage *ParticipantStorage) UpdateParticipant(ctx context.Context, id int32, participant models.Participant) error {
2024-08-18 14:54:08 +00:00
query := storage.db.Rebind("UPDATE participants SET name=?")
_, err := storage.db.ExecContext(ctx, query, participant.Name)
if err != nil {
2024-08-20 22:54:46 +00:00
return handlePgErr(err)
2024-08-18 14:54:08 +00:00
}
2024-08-20 22:54:46 +00:00
return nil
2024-08-18 14:54:08 +00:00
}
func (storage *ParticipantStorage) DeleteParticipant(ctx context.Context, id int32) error {
query := storage.db.Rebind("DELETE FROM participants WHERE id=?")
_, err := storage.db.ExecContext(ctx, query, id)
if err != nil {
2024-08-20 22:54:46 +00:00
return handlePgErr(err)
2024-08-18 14:54:08 +00:00
}
return nil
}