diff --git a/backend/internal/storage/postgres/db.go b/backend/internal/storage/postgres/db.go new file mode 100644 index 0000000..d1f406e --- /dev/null +++ b/backend/internal/storage/postgres/db.go @@ -0,0 +1,75 @@ +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 + } + + 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) + defer db.Close() + + 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 +}