Files
mtusi2026lab7/internal/adapter/postgres/users.go
T
d1frend cc41f601e3
Skeleton contracts / contracts (pull_request) Canceled after 0s
на оценку 4
2026-11-22 23:33:11 +03:00

166 lines
2.8 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func (s *PostgreSQLStore) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
}
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO users (
id,
username,
display_name,
password_hash
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
user.ID,
user.Username,
user.DisplayName,
passwordHash,
).Scan(&user.CreatedAt)
if err == nil {
return user, nil
}
var postgresError *pgconn.PgError
if errors.As(err, &postgresError) &&
postgresError.Code == "23505" &&
postgresError.ConstraintName == "users_username_unique" {
return domain.User{}, ErrConflict
}
return domain.User{}, fmt.Errorf("insert user: %w", err)
}
func (s *PostgreSQLStore) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at
FROM users
WHERE id = $1
`,
userID,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf("select user by id: %w", err)
}
return user, nil
}
func (s *PostgreSQLStore) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
user domain.User
passwordHash string
)
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at,
password_hash
FROM users
WHERE username = $1
`,
username,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
&passwordHash,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, "", ErrNotFound
}
if err != nil {
return domain.User{}, "", fmt.Errorf(
"select user by username: %w",
err,
)
}
return user, passwordHash, nil
}
func (s *PostgreSQLStore) UpdatePasswordHash(
ctx context.Context,
userID string,
previousHash string,
newHash string,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3`,
newHash,
userID,
previousHash,
)
if err != nil {
return fmt.Errorf("update password hash: %w", err)
}
return nil
}