Files
evening_detective_server/internal/repos/tickets_repo/repo.go
T
2026-09-18 16:14:56 +07:00

68 lines
1.5 KiB
Go

package tickets_repo
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrTicketNotFound = errors.New("Билет не найден")
type Info struct {
ID int
Status string
GameName string
StartAt time.Time
Location *string
GameStatus string
UsedAt *time.Time
}
type Repo struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *Repo {
return &Repo{pool: pool}
}
func (r *Repo) CreateBatch(ctx context.Context, gameID int, tokenHashes [][]byte) ([]int, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
ids := make([]int, 0, len(tokenHashes))
for _, tokenHash := range tokenHashes {
var id int
if err := tx.QueryRow(ctx,
`INSERT INTO tickets (game_id, token_hash) VALUES ($1, $2) RETURNING id`,
gameID, tokenHash,
).Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return ids, nil
}
func (r *Repo) GetByHash(ctx context.Context, tokenHash []byte) (*Info, error) {
info := &Info{}
err := r.pool.QueryRow(ctx, `
SELECT t.id, t.status, g.name, g.start_at, g.location, g.status, t.used_at
FROM tickets t JOIN games g ON g.id = t.game_id
WHERE t.token_hash = $1`, tokenHash).Scan(
&info.ID, &info.Status, &info.GameName, &info.StartAt, &info.Location, &info.GameStatus, &info.UsedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrTicketNotFound
}
return info, err
}