Does gorm.Open() create a new connection pool every time it's called?

Viewed 13310

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?

2 Answers

TLDR: yes, try to reuse the returned DB object.

gorm.Open does the following: (more or less):

  1. lookup the driver for the given dialect
  2. call sql.Open to return a DB object
  3. call DB.Ping() to force it to talk to the database

This 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.

Related