Search code examples
goaws-lambdago-gorm

Does Gorm automatically close the connection?


I have been using GORM for my application based on AWS lambda. I used gorm.Open() for every Handler function,

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
    })

so can someone help me confirm that does gorm.Open(...) automatically close the connection or not? Or I must use generic database interface bellow?

// Get generic database object sql.DB to use its functions
sqlDB, err := db.DB()

// Ping
sqlDB.Ping()

// Close
sqlDB.Close()

// Returns database statistics
sqlDB.Stats()

Solution

  • A gorm.DB object is intended to be reused, like a sql.DB handle. You rarely have to explicitly close these objects. Just create it once and reuse it.

    gorm.DB contains a sql.DB which uses a connection pool to manage the connections. If it is closed, it will stop accepting new queries, wait for running queries to finish and close all connections.