forked from mtusi2026/mtusi2026lab3
перенос лабы 2
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab3/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Open(
|
||||
ctx context.Context,
|
||||
cfg config.Config,
|
||||
) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = cfg.DatabaseMaxConns
|
||||
poolConfig.MinConns = cfg.DatabaseMinConns
|
||||
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
// NewWithConfig создаёт структуру пула, но не гарантирует,
|
||||
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user