45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
func isUniqueViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
|
}
|
|
|
|
// dbError separates a drained dependency (503) from a real bug (500). SQL
|
|
// details never reach the client; callers only emit the AppError message.
|
|
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 common.Conflict("resource already exists")
|
|
case "23503", "23514", "22P02":
|
|
return common.BadRequest("request conflicts with stored data")
|
|
}
|
|
}
|
|
|
|
var netErr net.Error
|
|
if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) ||
|
|
errors.Is(err, context.Canceled) ||
|
|
pgconn.SafeToRetry(err) ||
|
|
errors.Is(err, pgx.ErrTxClosed) {
|
|
return common.Unavailable("database unavailable")
|
|
}
|
|
|
|
return common.Internal()
|
|
}
|