4

Beego ORM is somehow incomplete for now (for example it doesn't support foreign key constraints). So I've decided to use gorm with Beego. What is proper way of doing that? I've seen the sample code from gorm:

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

func main() {
  db, err := gorm.Open("postgres", "host=myhost user=gorm dbname=gorm sslmode=disable password=mypassword")
  defer db.Close()
}

But do I have to connect to database each time in every controller function? Is there a way to use something like long polling connections?

matt.s
  • 1,698
  • 1
  • 20
  • 29
hamidfzm
  • 4,595
  • 8
  • 48
  • 80

2 Answers2

3

gorm uses sql.DB type embedded in gorm.DB under the hood which

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines. The sql package creates and frees connections automatically; it also maintains a free pool of idle connections.

So you can use obtained DB globally in your code, if you want level of isolation in request handling use transaction

tr:=db.Begin()
Uvelichitel
  • 8,220
  • 1
  • 19
  • 36
  • Could you provide more elaborate example? How exactly "obtained DB" (which is defined in `main.go`, if I understand correctly) would become accessible in other files/packages? – EugZol Oct 16 '16 at 23:58
1

So, as @Uvelichitel pointed out, your option is to define your db connection at the global level and to use it from a desired place (probably main function to open a connection and model layer to query for results).

So you could basically have a file containing your db connection logics:

// appname/conn.go

package db

import (
  "github.com/jinzhu/gorm"
  ...
)

var (
  // this one gonna contain an open connection
  // make sure to call Connect() before using it
  Conn *gorm.DB
)

func Connect(dbConnString string) (*gorm.DB, error) {
  db, err := gorm.Open("postgres", dbConnString)
  Conn = db
  return db, err
}

After you call db.Connect from your main.go you are free to use an opened connection db.Conn from anywhere of your application (just make sure you're importing this package to the places of use).

import "appname/db"

func main() {
  conn, _ := db.Connect("host=localhost user=postgres ...")
  // db.Conn is initialized and ready for usage anywhere else

The same result could be achieved within a single main.go file, moving global variable declaration and a connection logics straight there.

twonegatives
  • 3,400
  • 19
  • 30