package store import ( "context" "errors" "fmt" "mtusi2026lab3/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 }