feat(storage/postgres): lab2 add pg error helpers and keyset cursor

This commit is contained in:
Голиков Maximillian Антон
2026-10-01 20:42:11 +03:00
parent a8b787eccb
commit 3e623d4fea
2 changed files with 83 additions and 0 deletions
@@ -0,0 +1,41 @@
package postgres
import (
"encoding/base64"
"strings"
"time"
"high-loud-apps-labs/internal/domain"
)
// Взял за основу что в inmemery делал
func encodeCursor(scope string, createdAt time.Time, id string) string {
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return time.Time{}, "", badCursor()
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return time.Time{}, "", badCursor()
}
if parts[0] != expectedScope {
return time.Time{}, "", badCursor()
}
t, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return time.Time{}, "", badCursor()
}
return t, parts[2], nil
}
func badCursor() error {
return &domain.ValidationError{
Field: "cursor",
Message: "некорректный формат",
}
}
@@ -0,0 +1,42 @@
package postgres
import (
"errors"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"high-loud-apps-labs/internal/domain"
)
func notFound(err error, entity, id string) error {
if errors.Is(err, pgx.ErrNoRows) {
return &domain.NotFoundError{Entity: entity, ID: id}
}
return 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
}