49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
|
|
"git.keircn.com/keiran/termcloud/internal/config"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func NewPool(ctx context.Context, cfg *config.Config) (*pgxpool.Pool, error) {
|
|
if cfg.DatabaseURL == "" {
|
|
return nil, fmt.Errorf("DATABASE_URL environment variable is not set")
|
|
}
|
|
|
|
config, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to parse DATABASE_URL: %w", err)
|
|
}
|
|
|
|
config.MaxConns = cfg.MaxConnections
|
|
config.MinConns = cfg.MinConnections
|
|
config.MaxConnLifetime = cfg.ConnLifetime
|
|
config.MaxConnIdleTime = cfg.ConnIdleTime
|
|
config.HealthCheckPeriod = cfg.HealthCheckPeriod
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to create connection pool: %w", err)
|
|
}
|
|
|
|
err = pool.Ping(ctx)
|
|
if err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("unable to ping database: %w", err)
|
|
}
|
|
|
|
log.Println("Database connection pool successfully initialized.")
|
|
return pool, nil
|
|
}
|
|
|
|
func ClosePool(pool *pgxpool.Pool) {
|
|
if pool != nil {
|
|
pool.Close()
|
|
log.Println("Database connection pool closed.")
|
|
}
|
|
}
|