ms-tester/internal/contests/repository/pg_repository.go
Vyacheslav1557 d62ae666d5 refactor:
2024-10-09 23:55:16 +05:00

98 lines
2.2 KiB
Go

package repository
import (
"context"
"errors"
"git.sch9.ru/new_gate/models"
"git.sch9.ru/new_gate/ms-tester/pkg/utils"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
)
type ContestRepository struct {
db *sqlx.DB
logger *zap.Logger
}
func NewContestRepository(db *sqlx.DB, logger *zap.Logger) *ContestRepository {
return &ContestRepository{
db: db,
logger: logger,
}
}
func (r *ContestRepository) CreateContest(ctx context.Context, contest *models.Contest) (int32, error) {
query := r.db.Rebind(`
INSERT INTO contests
(name)
VALUES (?)
RETURNING id
`)
rows, err := r.db.QueryxContext(
ctx,
query,
contest.Name,
)
if err != nil {
return 0, handlePgErr(err)
}
defer rows.Close()
var id int32
err = rows.StructScan(&id)
if err != nil {
return 0, handlePgErr(err)
}
return id, nil
}
func (r *ContestRepository) ReadContestById(ctx context.Context, id int32) (*models.Contest, error) {
var contest models.Contest
query := r.db.Rebind("SELECT * from contests WHERE id=? LIMIT 1")
err := r.db.GetContext(ctx, &contest, query, id)
if err != nil {
return nil, handlePgErr(err)
}
return &contest, nil
}
func (r *ContestRepository) UpdateContest(ctx context.Context, contest *models.Contest) error {
query := r.db.Rebind("UPDATE contests SET name=? WHERE id=?")
_, err := r.db.ExecContext(ctx, query, contest.Name, contest.Id)
if err != nil {
return handlePgErr(err)
}
return nil
}
func (r *ContestRepository) DeleteContest(ctx context.Context, id int32) error {
query := r.db.Rebind("DELETE FROM contests WHERE id=?")
_, err := r.db.ExecContext(ctx, query, id)
if err != nil {
return handlePgErr(err)
}
return nil
}
func handlePgErr(err error) error {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return utils.StorageError(err, utils.ErrUnknown, "unexpected error from postgres")
}
if pgerrcode.IsIntegrityConstraintViolation(pgErr.Code) {
// TODO: probably should specify which constraint
return utils.StorageError(err, utils.ErrConflict, pgErr.Message)
}
if pgerrcode.IsNoData(pgErr.Code) {
return utils.StorageError(err, utils.ErrNotFound, pgErr.Message)
}
return utils.StorageError(err, utils.ErrUnimplemented, "unimplemented error")
}