Files
mtusi2026lab5/backend/internal/storage/postgres/user.go
T

77 lines
1.8 KiB
Go

package postgres
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
type UserRepo struct {
pool *pgxpool.Pool
}
func NewUserRepo(pool *pgxpool.Pool) *UserRepo {
return &UserRepo{pool: pool}
}
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
const q = `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
`
_, err := r.pool.Exec(ctx, q,
user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt,
)
if err != nil {
if uniqueViolation(err) {
return &domain.AlreadyExistsError{
Entity: "user",
Field: "username",
Value: user.Username,
}
}
if checkViolation(err) {
return &domain.ValidationError{
Field: "user",
Message: "нарушено ограничение целостности",
}
}
return mapError(err)
}
return nil
}
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE id = $1::uuid
`
u := &domain.User{}
err := r.pool.QueryRow(ctx, q, id).
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if err != nil {
return nil, notFound(err, "user", id)
}
return u, nil
}
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = $1
`
u := &domain.User{}
err := r.pool.QueryRow(ctx, q, username).
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if err != nil {
return nil, notFound(err, "user", username)
}
return u, nil
}
var _ domain.UserRepository = (*UserRepo)(nil)