Files
mtusi2026lab5/internal/user/store/postgres.go
T

75 lines
2.4 KiB
Go

// Package store holds the repository implementations of the users module.
// Errors pass through postgres.Classify, so an unreachable database surfaces
// as unavailability rather than as an internal error.
package store
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/platform/postgres"
"messenger/internal/user"
)
type Users struct {
pool *pgxpool.Pool
}
var _ user.Repository = (*Users)(nil)
func NewUsers(pool *pgxpool.Pool) *Users {
return &Users{pool: pool}
}
// Create relies on the unique constraint rather than a prior lookup, so two
// concurrent registrations of one username cannot both succeed.
func (r *Users) Create(ctx context.Context, u user.User) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Username, u.DisplayName, u.PasswordHash, u.CreatedAt)
if postgres.IsUniqueViolation(err, "users_username_key") {
return user.ErrUsernameTaken
}
if err != nil {
return fmt.Errorf("insert user: %w", postgres.Classify(err))
}
return nil
}
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id)
}
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username)
}
func (r *Users) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
rows, err := r.pool.Query(ctx, `SELECT id FROM users WHERE id = ANY($1)`, ids)
if err != nil {
return nil, fmt.Errorf("select user ids: %w", postgres.Classify(err))
}
found, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
if err != nil {
return nil, fmt.Errorf("read user ids: %w", postgres.Classify(err))
}
return found, nil
}
func (r *Users) one(ctx context.Context, query string, arg any) (user.User, error) {
var u user.User
err := r.pool.QueryRow(ctx, query, arg).Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return user.User{}, user.ErrNotFound
}
if err != nil {
return user.User{}, fmt.Errorf("select user: %w", postgres.Classify(err))
}
return u, nil
}