title: Why are database connections automatically closed?
body: <p>I'm having an issue with Gorm / Psql where my database connection get automatically closed. </p>
  
  <p>I never call defer <code>dbInstance.Close()</code> in main.go  (not anymore for now, I've removed it, since that's the only place in my code where I felt the connection could be wrongfully closed) nor was it ever anywhere else.</p>
  
  <p>The way I'm initializing my db is with a "db" package that looks like this:</p>
  
  <pre><code>package db
  
  import (
      "fmt"
      "github.com/jinzhu/gorm"
      _ "github.com/jinzhu/gorm/dialects/postgres"
  )
  
  var DbInstance *gorm.DB
  
  func Init() *gorm.DB {
      if DbInstance != nil {
          return DbInstance
      }
      fmt.Println("Opening Db")
      db, err := gorm.Open("postgres", "host=localhost port=5432 user=admin dbname=dbname sslmode=disable password=")
      if err != nil {
          fmt.Println(err)
          panic("failed to connect database")
      }
      return db
  }
  </code></pre>
  
  <p>then I call <code>db.Init()</code> in my main.go and then only call the db from "db.dbInstance" from the rest of my program.</p>
  
  <p>As I've previously mentioned I used to call <code>defer db.DbInstance.Close()</code> from main.go but have tried removing it to see if it fixed the issue but it didn't. </p>
  
  <p>What's strange is that the db connection will work for hours and hours in many different calls/function but always end up closing at some point.</p>
  
  <p>From what i understand <a href="https://github.com/jinzhu/gorm/issues/1427" rel="nofollow noreferrer">it should work</a> : </p>
  
  <blockquote>
    <p>gorm.Open() uses <a href="https://golang.org/pkg/database/sql/" rel="nofollow noreferrer">https://golang.org/pkg/database/sql/</a>, which is
    threadsafe and handles connection pooling for you. Don't call
    gorm.Open() every request. Call it once when setting up your
    application, and make sure you use defer db.Close() so connections are
    cleanly ended when your program exits. </p>
  </blockquote>
  
  <p>Lastly I need to add that it seems (i'm not 100% sure) that it's closing after I do batch inserts but again the <code>.Close()</code> <strong>function is never called, anywhere in my program</strong>.</p>
  
  <p>I'm a bit lost as to what could be happening? Garbage collector (doesn't make sense the var is global)? psql driver closing in the background? Configuration issue?</p>
  
  <p>I'm adding the batch function for reference just in case:</p>
  
  <pre><code>func InsertWithPostGresLimitSizeV2(DB *gorm.DB, array []interface{}) {
      if len(array) == 0 {
          return
      }
      numberOfParams := len(DB.NewScope(array[0]).Fields())
      // postgres is limited to 65535 params.
      maxStructPerBulk := int(65535 / numberOfParams)
      currentIndex := 0
      if len(array) &gt; maxStructPerBulk {
          for len(array) &gt; currentIndex {
              if (maxStructPerBulk + currentIndex) &lt; len(array) {
                  slice := array[currentIndex:(currentIndex + maxStructPerBulk)]
                  currentIndex += maxStructPerBulk
                  _, err := DB.BatchInsert(slice)
                  log.Println(err)
              } else {
  
                  slice := array[currentIndex:len(array)]
                  currentIndex = len(array)
                  _, err := DB.BatchInsert(slice)
                  log.Println(err)
              }
          }
      } else {
          _, err := DB.BatchInsert(array)
          log.Println(err)
      }
  }
  
  func BatchInsert(db *gorm.DB,objArr []interface{}) (int64, error) {
      if len(objArr) == 0 {
          return 0, errors.New("insert a slice length of 0")
      }
  
      mainObj := objArr[0]
      mainScope := db.NewScope(mainObj)
      mainFields := mainScope.Fields()
      quoted := make([]string, 0, len(mainFields))
      for i := range mainFields {
          if (mainFields[i].IsPrimaryKey &amp;&amp; mainFields[i].IsBlank) || (mainFields[i].IsIgnored) {
              continue
          }
          quoted = append(quoted, mainScope.Quote(mainFields[i].DBName))
      }
  
      placeholdersArr := make([]string, 0, len(objArr))
  
      for _, obj := range objArr {
          scope := db.NewScope(obj)
          fields := scope.Fields()
          placeholders := make([]string, 0, len(fields))
          for i := range fields {
              if (fields[i].IsPrimaryKey &amp;&amp; fields[i].IsBlank) || (fields[i].IsIgnored) {
                  continue
              }
              var vars interface{}
              if (fields[i].Name == "CreatedAt" || fields[i].Name == "UpdatedAt") &amp;&amp; fields[i].IsBlank {
                  vars = gorm.NowFunc()
              } else {
                  vars = fields[i].Field.Interface()
              }
              placeholders = append(placeholders, mainScope.AddToVars(vars))
          }
          placeholdersStr := "(" + strings.Join(placeholders, ", ") + ")"
          placeholdersArr = append(placeholdersArr, placeholdersStr)
  
          mainScope.SQLVars = append(mainScope.SQLVars, scope.SQLVars...)
      }
      mainScope.Raw(fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
          mainScope.QuotedTableName(),
          strings.Join(quoted, ", "),
          strings.Join(placeholdersArr, ", "),
      ))
      if err := mainScope.Exec().DB().Error; err != nil {
          return 0, err
      }
      return mainScope.DB().RowsAffected, nil
  }
  </code></pre>
  
  <p>On last thing is that I was thinking of " fixing " the issue by calling my db through but the ping would slow each of my calls:</p>
  
  <pre><code>func getDb() *gorm.DB {
      err := DbInstance.DB().Ping()
      if err != nil {
          fmt.Println("Connection to db closed opening a new one")
          return Init()
      }
      return DbInstance
  }
  </code></pre>