// Package database owns the PostgreSQL connection pool and schema migrations. package database import ( "context" "fmt" "time" "github.com/jackc/pgx/v5/pgxpool" ) func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) { cfg, err := pgxpool.ParseConfig(url) if err != nil { return nil, fmt.Errorf("parse DATABASE_URL: %w", err) } cfg.MaxConns = maxConns cfg.MinConns = 1 cfg.MaxConnLifetime = 30 * time.Minute cfg.MaxConnIdleTime = 5 * time.Minute cfg.HealthCheckPeriod = 30 * time.Second cfg.ConnConfig.ConnectTimeout = 3 * time.Second pool, err := pgxpool.NewWithConfig(ctx, cfg) if err != nil { return nil, fmt.Errorf("create pool: %w", err) } deadline := time.Now().Add(wait) for { pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second) err = pool.Ping(pingCtx) cancel() if err == nil { return pool, nil } if time.Now().After(deadline) || ctx.Err() != nil { pool.Close() return nil, fmt.Errorf("postgres is not reachable: %w", err) } time.Sleep(500 * time.Millisecond) } }