Files
mtusi2026lab2/internal/repository/postgres/user.go
T
Weinmaier_Andrew d8842a3de4
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2: postgres, sessions, redis, persistence, stale read
2026-10-09 21:30:36 +03:00

86 lines
2.3 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab2/internal/domain"
"github.com/charawein/mtusi2026lab2/internal/repository"
)
type UserRepository struct {
pool *pgxpool.Pool
}
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
return &UserRepository{pool: pool}
}
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
const q = `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)
`
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
return repository.ErrConflict
}
return fmt.Errorf("insert user: %w", err)
}
return nil
}
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, created_at
FROM users
WHERE id = $1
`
var u domain.User
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("select user by id: %w", err)
}
return &u, nil
}
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, created_at
FROM users
WHERE username = $1
`
var u domain.User
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("select user by username: %w", err)
}
return &u, nil
}
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
const q = `SELECT password_hash FROM users WHERE id = $1`
var hash string
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", repository.ErrNotFound
}
return "", fmt.Errorf("select password hash: %w", err)
}
return hash, nil
}