Neo
Neo

Reputation: 857

Should database connections be opened and closed in every CRUD method?

I am using GORM ORM for Postgres access in a Go application. I have got 4 functions, Create, Update, Delete, and Read in a database repository.

In each of these functions, I open a database connection, perform a CRUD operation and then close the connection just after the operation is performed as you will see here and here and in the code snippet below, using GORM

func (e *Example) Create(m *model.Example) (*model.Example, error) {
    // open a database session
    dbSession, err := e.OpenDB() //gorm.Open("postgres", connStr)
    if err != nil {
        log.Log(err)
        return nil, err
    }

    // close database connection after operation is completed
    defer dbSession.Close()

    // create item
    db := dbSession.Create(m)

    if db.Error != nil {
        return nil, db.Error
    }

    return m, nil
}

Is that the correct practice or should one database connection be shared in the whole application and let the ORM handle managing connections? as stated here?

Upvotes: 5

Views: 2572

Answers (1)

Praveen Rewar
Praveen Rewar

Reputation: 961

You should reuse a DB connection as much as you can. Also gorm has a built-in connection pool, so, you don't need to manage the db handle. Simply share it amongst all goroutines and they can share the handle safely, allocating new connections as needed.

Upvotes: 8

Related Questions