This commit is contained in:
yash 2026-02-26 16:30:56 +03:00
parent 8a76cca5fb
commit 7eb4977b99
6 changed files with 537 additions and 5 deletions

View file

@ -33,7 +33,7 @@ type Bybit struct {
type Postgresql struct {
Address string `yaml:"address" env-required:"true"`
User string `yaml:"user" env-required:"true"`
Password string `yaml:"password" env-required:"true"`
Password string `yaml:"password" env-default:""` // empty for peer auth over Unix socket
DBName string `yaml:"db_name" env-required:"true"`
}

View file

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"log/slog"
"strings"
"gitea.computernetthings.ru/yash/crypto_alert_bot/internal/config"
"gitea.computernetthings.ru/yash/crypto_alert_bot/internal/repository/postgresql/migrations"
@ -22,8 +23,18 @@ type Postgresql struct {
db *pgxpool.Pool
}
// dsn builds a connection string that supports both TCP (host:port) and Unix
// socket (path starting with "/") addresses. Unix socket mode skips the
// password and uses OS peer authentication instead.
func dsn(cfg *config.Postgresql) string {
if strings.HasPrefix(cfg.Address, "/") {
return fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable", cfg.Address, cfg.User, cfg.DBName)
}
return fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", cfg.User, cfg.Password, cfg.Address, cfg.DBName)
}
func New(ctx context.Context, log *slog.Logger, cfg *config.Postgresql) (*Postgresql, error) {
pool, err := pgxpool.New(ctx, fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", cfg.User, cfg.Password, cfg.Address, cfg.DBName))
pool, err := pgxpool.New(ctx, dsn(cfg))
if err != nil {
return nil, fmt.Errorf("failed to connect to postgres: %w", err)
}
@ -41,9 +52,7 @@ func New(ctx context.Context, log *slog.Logger, cfg *config.Postgresql) (*Postgr
}
func applyMigrations(cfg *config.Postgresql, log *slog.Logger) error {
dsn := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", cfg.User, cfg.Password, cfg.Address, cfg.DBName)
sqlDB, err := sql.Open("pgx", dsn)
sqlDB, err := sql.Open("pgx", dsn(cfg))
if err != nil {
return fmt.Errorf("failed to open sql db for migrations: %w", err)
}