29 lines
668 B
Go
29 lines
668 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// OpenPostgres creates a pgx connection pool and validates connectivity.
|
|
func OpenPostgres(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse postgres DSN: %w", err)
|
|
}
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create postgres pool: %w", err)
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping postgres: %w", err)
|
|
}
|
|
slog.Info("postgres connected", "max_conns", cfg.MaxConns)
|
|
return pool, nil
|
|
}
|