Hello there. *gorm.DB does not have DB as the struct field. It has DB()method which returns underlying connection and error. This way you can get access to the connection to close it.
But also pay attention, that sql package do it on it’s own:
The sql package creates and frees connections automatically;
In previous versions of Gorm they had a DB.Close function but it was removed in v1.20:
It’s likely you were looking at examples from older versions of Gorm. If you look at the implementation, they were just calling Close on the underlying sql/DB connection pool:
So you could change your code to the following if you really need to close the pool:
defer func() {
// Ignoring errors since there/s not much we can do at this point
sqlDB, _ := db.DB()
_ = sqlDB.Close()
}()
The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.
Refer to the specific library or framework you’re using for database interaction. The method to close the connection might be different than db.Close(). For instance, in Gorm v2 with Postgres, there’s no db.Close() method, but DB() to get the underlying connection.