Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

go

go-gorm

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?

like image 300
Abe Miessler Avatar asked May 15 '20 15:05

Abe Miessler


People also ask

Is connection pooling enabled by default?

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.

How do I close Gorm connection?

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.


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.

like image 89
Marc Avatar answered Oct 27 '22 02:10

Marc


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.

like image 11
robbieperry22 Avatar answered Oct 27 '22 00:10

robbieperry22