From 862d22c2283126ce8a196987650cc2080f47b23d Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 21:41:39 +0300 Subject: [PATCH] feat(postgres): add pool and error code helpers --- internal/postgres/errors.go | 25 +++++++++++++++++++++++++ internal/postgres/pool.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 internal/postgres/errors.go create mode 100644 internal/postgres/pool.go diff --git a/internal/postgres/errors.go b/internal/postgres/errors.go new file mode 100644 index 00000000..961f069e --- /dev/null +++ b/internal/postgres/errors.go @@ -0,0 +1,25 @@ +package postgres + +import ( + "errors" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +const ( + CodeUniqueViolation = "23505" + CodeForeignKeyViolation = "23503" + CodeCheckViolation = "23514" +) + +func ErrCode(err error) string { + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return pgErr.Code + } + return "" +} + +func IsNotFound(err error) bool { + return errors.Is(err, pgx.ErrNoRows) +} diff --git a/internal/postgres/pool.go b/internal/postgres/pool.go new file mode 100644 index 00000000..4a1361aa --- /dev/null +++ b/internal/postgres/pool.go @@ -0,0 +1,34 @@ +package postgres + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func New(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" + + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("create pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping database: %w", err) + } + + return pool, nil +}