Skip to content

Commit

Permalink
feat: add ping into the database connection creation
Browse files Browse the repository at this point in the history
  • Loading branch information
1995parham committed Dec 25, 2023
1 parent 52e7539 commit 4f9d263
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions internal/infra/db/db.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package db

import (
"context"
"database/sql"
"fmt"
"time"

"go.uber.org/zap"
"gorm.io/driver/postgres"
Expand All @@ -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{
Expand All @@ -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)
Expand Down

0 comments on commit 4f9d263

Please sign in to comment.