48 lines
1.3 KiB
Go
48 lines
1.3 KiB
Go
package initialization
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
"wm-backend/internal/models"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func ConnectPostgreSQL(config *models.Config) (*pgxpool.Pool, error) {
|
|
connStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable",
|
|
config.Database.Username, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.Name)
|
|
|
|
var pool *pgxpool.Pool
|
|
var err error
|
|
|
|
maxRetries := 5
|
|
for i := range maxRetries {
|
|
poolConfig, parseErr := pgxpool.ParseConfig(connStr)
|
|
if parseErr != nil {
|
|
log.Error().Err(parseErr).Msgf("Failed to parse DB config (attempt %d/%d)", i+1, maxRetries)
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
pool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
|
if err != nil {
|
|
log.Error().Err(err).Msgf("Failed to connect to PostgreSQL (attempt %d/%d)", i+1, maxRetries)
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
err = pool.Ping(context.Background())
|
|
if err != nil {
|
|
log.Error().Err(err).Msgf("Failed to ping PostgreSQL (attempt %d/%d)", i+1, maxRetries)
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
log.Info().Msg("Successfully connected to PostgreSQL")
|
|
return pool, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to connect to PostgreSQL after %d attempts: %v", maxRetries, err)
|
|
}
|