GORM stands out as a go-to choice for ORM in Go projects, and we often encounter the familiar gorm.Open()
. If you have ever wondered how this function works under the hood, this article aims to provide a short and concise answer for the same. So, let's dive in!
Connecting to a database using the gorm.Open()
function on a high level involves the following series of steps
1. Dialect Driver Lookup
GORM identifies the appropriate driver for the specified database dialect (e.g., MySQL, PostgreSQL). The chosen driver facilitates interactions with the targeted database.
2. DB Object Creation
Every invocation of gorm.Open()
results in the creation of a distinct sql.DB
object, as per the documentation. We'll talk about the implications of this later in the article.
3. Database Connection Validation
A subsequent call to ping ensures active communication with the database. This step guarantees the validity and accessibility of the established database connection.
You can set the value of DisableAutomaticPing
to true
in order to disable the automatic ping.
Implications of the sql.DB object
The database/sql
package simplifies database access by reducing the need for the user to manage connections. This package opens a database handle (sql.DB
) that represents a connection pool and executes data access operations with the handle. The returned sql.DB
object is safe for concurrent use by multiple goroutines.
Since gorm.Open()
uses this under the hood, it has the following implications
It is advisable to call
gorm.Open()
only once during the application's lifecycle, reusing the returned DB instance across the application.Closing the DB is seldom necessary, as Gorm effectively manages its connections and pool.
The DB instance returned by
gorm.Open()
is designed to be concurrency-safe, enabling seamless usage across multiple goroutines without concerns about concurrency issues.Gorm maintains its own connection pool, optimising performance by reusing existing connections and minimising the overhead of creating new ones.
sql.DB
object. (Refer to Connection Pools)