39 lines
967 B
Go
39 lines
967 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Connect opens a connection pool to Postgres.
|
|
// pgxpool manages multiple connections automatically — you rarely need to
|
|
// think about it; just pass the pool around and pgx picks an idle connection.
|
|
func Connect(databaseURL string) (*pgxpool.Pool, error) {
|
|
if databaseURL == "" {
|
|
return nil, fmt.Errorf("DATABASE_URL is not set")
|
|
}
|
|
|
|
config, err := pgxpool.ParseConfig(databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse database url: %w", err)
|
|
}
|
|
|
|
// Pool settings — tune these later based on your load
|
|
config.MaxConns = 25
|
|
config.MinConns = 2
|
|
|
|
pool, err := pgxpool.NewWithConfig(context.Background(), config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create pool: %w", err)
|
|
}
|
|
|
|
// Ping to verify the connection works at startup
|
|
if err := pool.Ping(context.Background()); err != nil {
|
|
return nil, fmt.Errorf("ping database: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|