2024-08-18 14:54:08 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-08-25 16:52:00 +00:00
|
|
|
"git.sch9.ru/new_gate/ms-tester/pkg/models"
|
2024-08-18 14:54:08 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ContestStorage struct {
|
|
|
|
db *sqlx.DB
|
|
|
|
logger *zap.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewContestStorage(db *sqlx.DB, logger *zap.Logger) *ContestStorage {
|
|
|
|
return &ContestStorage{
|
|
|
|
db: db,
|
|
|
|
logger: logger,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (storage *ContestStorage) CreateContest(ctx context.Context, contest *models.Contest) (int32, error) {
|
|
|
|
query := storage.db.Rebind(`
|
|
|
|
INSERT INTO contests
|
|
|
|
(name)
|
|
|
|
VALUES (?)
|
|
|
|
RETURNING id
|
|
|
|
`)
|
|
|
|
|
|
|
|
rows, err := storage.db.QueryxContext(
|
|
|
|
ctx,
|
|
|
|
query,
|
2024-08-20 11:18:23 +00:00
|
|
|
contest.Name,
|
2024-08-18 14:54:08 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2024-08-20 11:18:23 +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 11:18:23 +00:00
|
|
|
return 0, handlePgErr(err)
|
2024-08-18 14:54:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return id, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (storage *ContestStorage) ReadContestById(ctx context.Context, id int32) (*models.Contest, error) {
|
|
|
|
var contest models.Contest
|
|
|
|
query := storage.db.Rebind("SELECT * from contests WHERE id=? LIMIT 1")
|
|
|
|
err := storage.db.GetContext(ctx, &contest, query, id)
|
|
|
|
if err != nil {
|
2024-08-20 11:18:23 +00:00
|
|
|
return nil, handlePgErr(err)
|
2024-08-18 14:54:08 +00:00
|
|
|
}
|
|
|
|
return &contest, nil
|
|
|
|
}
|
|
|
|
|
2024-08-20 22:54:46 +00:00
|
|
|
func (storage *ContestStorage) UpdateContest(ctx context.Context, contest *models.Contest) error {
|
|
|
|
query := storage.db.Rebind("UPDATE contests SET name=? WHERE id=?")
|
|
|
|
_, err := storage.db.ExecContext(ctx, query, contest.Name, contest.Id)
|
2024-08-18 14:54:08 +00:00
|
|
|
if err != nil {
|
2024-08-20 11:18:23 +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 *ContestStorage) DeleteContest(ctx context.Context, id int32) error {
|
|
|
|
query := storage.db.Rebind("DELETE FROM contests WHERE id=?")
|
|
|
|
_, err := storage.db.ExecContext(ctx, query, id)
|
|
|
|
if err != nil {
|
2024-08-20 11:18:23 +00:00
|
|
|
return handlePgErr(err)
|
2024-08-18 14:54:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|