I'm working on a piece of code that is making calls to the database from several different places. In this code I have been using the GORM library, and calling gorm.Open()
every time I need to interact with the database.
What I'm wondering is what is happening under the hood when I call this? Is a new connection pool created every time I call it or is each call to gorm.Open()
sharing the same connection pool?
TLDR: yes, try to reuse the returned DB object.
gorm.Open does the following: (more or less):
sql.Open
to return a DB
object DB.Ping()
to force it to talk to the databaseThis means that one sql.DB
object is created for every gorm.Open
. Per the doc, this means one connection pool for each DB object.
This means that the recommendations for sql.Open apply to gorm.Open
:
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.