forked from mtusi2026/mtusi2026lab2
52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
|
)
|
|
|
|
type Storage struct {
|
|
pool *pgxpool.Pool
|
|
timeout time.Duration
|
|
}
|
|
|
|
var _ chatusecase.Repository = (*Storage)(nil)
|
|
|
|
func New(pool *pgxpool.Pool, timeout time.Duration) *Storage {
|
|
return &Storage{pool: pool, timeout: timeout}
|
|
}
|
|
|
|
func (s *Storage) Ready(ctx context.Context) error {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
return dbError(s.pool.Ping(ctx))
|
|
}
|
|
|
|
func dbError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
switch pgErr.Code {
|
|
case "23505":
|
|
return chatusecase.ErrUsernameTaken
|
|
case "23503":
|
|
return chatusecase.ErrUserNotFound
|
|
}
|
|
log.Printf("postgres operation failed: sqlstate=%s", pgErr.Code)
|
|
} else if !errors.Is(err, pgx.ErrNoRows) {
|
|
log.Print("postgres operation failed")
|
|
}
|
|
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище недоступно")
|
|
}
|