forked from mtusi2026/mtusi2026lab2
47 lines
1.6 KiB
Go
47 lines
1.6 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
)
|
|
|
|
func (s *Storage) CreateUser(ctx context.Context, username, displayName, hash string) (domain.User, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var user domain.User
|
|
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
|
RETURNING id::text,username,display_name,created_at`, uuid.NewString(), username, displayName, hash).
|
|
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
|
return user, dbError(err)
|
|
}
|
|
|
|
func (s *Storage) User(ctx context.Context, id string) (domain.User, bool, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var user domain.User
|
|
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at FROM users WHERE id=$1`, id).
|
|
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return user, false, nil
|
|
}
|
|
return user, err == nil, dbError(err)
|
|
}
|
|
|
|
func (s *Storage) UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var user domain.User
|
|
var hash string
|
|
err := s.pool.QueryRow(ctx, `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, &hash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return user, "", false, nil
|
|
}
|
|
return user, hash, err == nil, dbError(err)
|
|
}
|