// Package store holds the repository implementations of the users module. 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" ) const userColumns = `id, username, display_name, password_hash, created_at` 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 (`+userColumns+`) 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", err) } return nil } func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) { return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1`, id) } func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) { return r.one(ctx, `SELECT `+userColumns+` 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", err) } found, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID]) if err != nil { return nil, fmt.Errorf("read user ids: %w", 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", err) } u.CreatedAt = u.CreatedAt.UTC() return u, nil }