forked from mtusi2026/mtusi2026lab6
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/pressly/goose/v3"
|
|
|
|
"high-loud-apps-labs/migrations"
|
|
)
|
|
|
|
type Config struct {
|
|
URL string
|
|
MaxConns int32
|
|
MinConns int32
|
|
MaxConnLifetime time.Duration
|
|
MaxConnIdleTime time.Duration
|
|
ConnectTimeout time.Duration
|
|
}
|
|
|
|
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
|
if cfg.URL == "" {
|
|
return nil, fmt.Errorf("DATABASE_URL пустой")
|
|
}
|
|
|
|
poolCfg, err := pgxpool.ParseConfig(cfg.URL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("разбор DATABASE_URL: %w", err)
|
|
}
|
|
if cfg.MaxConns > 0 {
|
|
poolCfg.MaxConns = cfg.MaxConns
|
|
}
|
|
if cfg.MinConns > 0 {
|
|
poolCfg.MinConns = cfg.MinConns
|
|
}
|
|
if cfg.MaxConnLifetime > 0 {
|
|
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
|
}
|
|
if cfg.MaxConnIdleTime > 0 {
|
|
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
|
}
|
|
if cfg.ConnectTimeout > 0 {
|
|
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
|
}
|
|
poolCfg.HealthCheckPeriod = 10 * time.Second
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("создание пула: %w", err)
|
|
}
|
|
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(pingCtx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping БД: %w", err)
|
|
}
|
|
return pool, nil
|
|
}
|
|
|
|
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
|
db := stdlib.OpenDBFromPool(pool)
|
|
|
|
goose.SetBaseFS(migrations.FS)
|
|
if err := goose.SetDialect("postgres"); err != nil {
|
|
return fmt.Errorf("goose dialect: %w", err)
|
|
}
|
|
if err := goose.UpContext(ctx, db, "."); err != nil {
|
|
return fmt.Errorf("применение миграций: %w", err)
|
|
}
|
|
return nil
|
|
}
|