diff --git a/pkg/common/dbconn/gorm.go b/pkg/common/dbconn/gorm.go index 2601e47bc..e99c9ffc9 100644 --- a/pkg/common/dbconn/gorm.go +++ b/pkg/common/dbconn/gorm.go @@ -29,19 +29,25 @@ import ( ) func NewMysqlGormDB() (*gorm.DB, error) { + // Construct the DSN (Data Source Name) dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local", *config.Config.Mysql.Username, *config.Config.Mysql.Password, (*config.Config.Mysql.Address)[0], "mysql") + + // First attempt to open a new database connection db, err := gorm.Open(mysql.Open(dsn), nil) if err != nil { time.Sleep(time.Duration(30) * time.Second) db, err = gorm.Open(mysql.Open(dsn), nil) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to open initial database connection with DSN %s: %w", dsn, err) } + } + sqlDB, err := db.DB() if err != nil { - return nil, err + // Include specific function name and the DSN used + return nil, fmt.Errorf("failed to get underlying sql.DB from GORM with DSN %s: %w", dsn, err) } defer sqlDB.Close() sql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8mb4 COLLATE utf8mb4_unicode_ci;", *config.Config.Mysql.Database) @@ -49,22 +55,33 @@ func NewMysqlGormDB() (*gorm.DB, error) { if err != nil { return nil, fmt.Errorf("init db %w", err) } + // Reconnect with the specific database dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local", *config.Config.Mysql.Username, *config.Config.Mysql.Password, (*config.Config.Mysql.Address)[0], *config.Config.Mysql.Database) + + // Custom logger sqlLogger := log.NewSqlLogger(logger.LogLevel(*config.Config.Mysql.LogLevel), true, time.Duration(*config.Config.Mysql.SlowThreshold)*time.Millisecond) + + // Second attempt to open a new database connection db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: sqlLogger, }) if err != nil { - return nil, err + // Include specific function name and the DSN used + return nil, fmt.Errorf("failed to open database connection with specific database using DSN %s: %w", dsn, err) } + sqlDB, err = db.DB() if err != nil { - return nil, err + // Include specific function name and the DSN used + return nil, fmt.Errorf("failed to get underlying sql.DB from GORM with specific database using DSN %s: %w", dsn, err) } + + // Database connection configuration sqlDB.SetConnMaxLifetime(time.Second * time.Duration(*config.Config.Mysql.MaxLifeTime)) sqlDB.SetMaxOpenConns(*config.Config.Mysql.MaxOpenConn) sqlDB.SetMaxIdleConns(*config.Config.Mysql.MaxIdleConn) + return db, nil }