From 4f9d263a656768420ba98d9a90a35db3f27b122c Mon Sep 17 00:00:00 2001 From: Parham Alvani Date: Mon, 25 Dec 2023 04:05:28 +0000 Subject: [PATCH] feat: add ping into the database connection creation --- internal/infra/db/db.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/internal/infra/db/db.go b/internal/infra/db/db.go index 59f156f..e620f87 100644 --- a/internal/infra/db/db.go +++ b/internal/infra/db/db.go @@ -1,8 +1,10 @@ package db import ( + "context" "database/sql" "fmt" + "time" "go.uber.org/zap" "gorm.io/driver/postgres" @@ -14,6 +16,8 @@ type DB struct { SQL *sql.DB } +const PingTimeout = 10 * time.Second + func Provide(cfg Config, logger *zap.Logger) (*DB, error) { // nolint: exhaustruct db, err := gorm.Open(postgres.Open(cfg.DSN), &gorm.Config{ @@ -38,6 +42,13 @@ func Provide(cfg Config, logger *zap.Logger) (*DB, error) { return nil, fmt.Errorf("cannot get sql database from gorm %w", err) } + ctx, cancel := context.WithTimeout(context.Background(), PingTimeout) + defer cancel() + + if err := sqlDB.PingContext(ctx); err != nil { + return nil, fmt.Errorf("cannot ping the database %w", err) + } + logger.Info("get sql database from gorm successfully", zap.String("dsn", cfg.DSN)) sqlDB.SetMaxIdleConns(cfg.MaxIdelConns)