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?
By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application. You can also supply several connection string modifiers to control connection pooling behavior.
If your specific use-case still requires to use the Close() method, GORM provides the method DB that returns a db generic_interface where you can use it.
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.
Yes, also note that the connection pool can be configured as such, in both GORM v1 and v2:
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
db.DB().SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
db.DB().SetMaxOpenConns(100)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
db.DB().SetConnMaxLifetime(time.Hour)
Calling the DB()
function on the *gorm.DB
instance returns the underlying *sql.DB
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With