448cf2a465
Co-authored-by: Cursor <cursoragent@cursor.com>
37 lines
727 B
Go
37 lines
727 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func Connect(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse database url: %w", err)
|
|
}
|
|
|
|
cfg.MaxConns = 10
|
|
cfg.MinConns = 2
|
|
cfg.MaxConnLifetime = time.Hour
|
|
cfg.HealthCheckPeriod = 30 * time.Second
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create pool: %w", err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping database: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|