From b72ddd127c7a7547ad1e5f0d0195e338f32524f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Thu, 1 Oct 2026 22:39:18 +0300 Subject: [PATCH] feat(storage/postgres): lab2 add SessionRepo --- backend/internal/storage/postgres/session.go | 59 ++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 backend/internal/storage/postgres/session.go diff --git a/backend/internal/storage/postgres/session.go b/backend/internal/storage/postgres/session.go new file mode 100644 index 0000000..fa983aa --- /dev/null +++ b/backend/internal/storage/postgres/session.go @@ -0,0 +1,59 @@ +package postgres + +import ( + "context" + + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type SessionRepo struct { + pool *pgxpool.Pool +} + +func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo { + return &SessionRepo{pool: pool} +} + +func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error { + const q = ` + INSERT INTO sessions (token_hash, user_id, expires_at, created_at) + VALUES ($1, $2::uuid, $3, $4) + ` + _, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt) + if err != nil { + if uniqueViolation(err) { + return &domain.AlreadyExistsError{ + Entity: "session", + Field: "token_hash", + Value: "", + } + } + return err + } + return nil +} + +func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) { + const q = ` + SELECT token_hash, user_id, expires_at, created_at + FROM sessions + WHERE token_hash = $1 + ` + s := &domain.Session{} + err := r.pool.QueryRow(ctx, q, tokenHash). + Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt) + if err != nil { + return nil, notFound(err, "session", "") + } + return s, nil +} + +func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error { + const q = `DELETE FROM sessions WHERE token_hash = $1` + _, err := r.pool.Exec(ctx, q, tokenHash) + return err +} + +var _ domain.SessionRepository = (*SessionRepo)(nil)