Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-gorm

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?

like image 543
ykel Avatar asked May 17 '19 17:05

ykel


1 Answers

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.

like image 172
Praveen Rewar Avatar answered Sep 28 '22 04:09

Praveen Rewar