Implement PostgreSQL storage, sessions and persistence checks
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
type PostgresStore struct{ pool *pgxpool.Pool }
|
||||
|
||||
func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore {
|
||||
return &PostgresStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, errors.New("cannot generate user ID")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.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`,
|
||||
id, username, displayName, passwordHash,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key" {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user