You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
894 B
Go
42 lines
894 B
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/denisovdennis/autohero/internal/config"
|
|
)
|
|
|
|
// NewPostgres creates a PostgreSQL connection pool.
|
|
func NewPostgres(ctx context.Context, cfg config.DBConfig, logger *slog.Logger) (*pgxpool.Pool, error) {
|
|
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse postgres config: %w", err)
|
|
}
|
|
|
|
// Sensible pool defaults for a game server.
|
|
poolCfg.MaxConns = 20
|
|
poolCfg.MinConns = 5
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create postgres pool: %w", err)
|
|
}
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping postgres: %w", err)
|
|
}
|
|
|
|
logger.Info("connected to PostgreSQL",
|
|
"host", cfg.Host,
|
|
"port", cfg.Port,
|
|
"database", cfg.Name,
|
|
)
|
|
|
|
return pool, nil
|
|
}
|