From 3e623d4fea9ee957f8821e3dfb2a0ddd9619743f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Thu, 1 Oct 2026 20:42:11 +0300 Subject: [PATCH] feat(storage/postgres): lab2 add pg error helpers and keyset cursor --- backend/internal/storage/postgres/cursor.go | 41 ++++++++++++++++++++ backend/internal/storage/postgres/errors.go | 42 +++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 backend/internal/storage/postgres/cursor.go create mode 100644 backend/internal/storage/postgres/errors.go diff --git a/backend/internal/storage/postgres/cursor.go b/backend/internal/storage/postgres/cursor.go new file mode 100644 index 0000000..4349c07 --- /dev/null +++ b/backend/internal/storage/postgres/cursor.go @@ -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: "некорректный формат", + } +} diff --git a/backend/internal/storage/postgres/errors.go b/backend/internal/storage/postgres/errors.go new file mode 100644 index 0000000..905d0bf --- /dev/null +++ b/backend/internal/storage/postgres/errors.go @@ -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 +}