72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/jackc/pgerrcode"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
)
|
|
|
|
type coded interface {
|
|
Code() domain.ErrorCode
|
|
}
|
|
|
|
// mapError переводит ошибки драйвера в доменные.
|
|
func mapError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var c coded
|
|
if errors.As(err, &c) {
|
|
return err
|
|
}
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return err
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) {
|
|
return &domain.UnavailableError{Reason: "превышено время ожидания БД"}
|
|
}
|
|
if errors.Is(err, context.Canceled) {
|
|
return &domain.UnavailableError{Reason: "запрос отменён"}
|
|
}
|
|
return &domain.UnavailableError{Reason: err.Error()}
|
|
}
|
|
|
|
func notFound(err error, entity, id string) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return &domain.NotFoundError{Entity: entity, ID: id}
|
|
}
|
|
return mapError(err)
|
|
}
|
|
|
|
func uniqueViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
return pgErr.Code == pgerrcode.UniqueViolation
|
|
}
|
|
return false
|
|
}
|
|
|
|
func foreignKeyViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
return pgErr.Code == pgerrcode.ForeignKeyViolation
|
|
}
|
|
return false
|
|
}
|
|
|
|
func checkViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) {
|
|
return pgErr.Code == pgerrcode.CheckViolation
|
|
}
|
|
return false
|
|
}
|