feat(postgres): add pool and error code helpers

This commit is contained in:
kk10
2026-10-04 21:41:39 +03:00
parent e1f2cb01e0
commit 862d22c228
2 changed files with 59 additions and 0 deletions
+25
View File
@@ -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)
}
+34
View File
@@ -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
}