I am working with GORM in my Go application and I need to set a default query timeout for all queries. Currently, I have individual queries where I set the timeout explicitly, But I want to avoid repetitive code and set a default timeout that applies to all queries executed through GORM. Such as:
ctx, cancel := context.WithTimeout(context.Background(),
config.DB_TIMEOUT)
defer cancel()
res := tx.WithContext(ctx).Model(&Stock{}).Update(myMap)
Is there a way to configure a default query timeout for GORM queries globally, so that I don’t have to specify it for each query individually?
1
Add timeout to dsn, e.g.
dsn := "user:password@tcp(127.0.0.1:3306)/dbname? loc=Local&timeout=10s"
gorm also supports other settings
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.maxIdleConn)
sqlDB.SetMaxOpenConns(m.maxOpenConn)
sqlDB.SetConnMaxLifetime(time.Hour)
Sorye Tong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2