Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting *sql.DB without using Open #25

Closed
yulrizka opened this issue Dec 4, 2013 · 1 comment
Closed

Setting *sql.DB without using Open #25

yulrizka opened this issue Dec 4, 2013 · 1 comment

Comments

@yulrizka
Copy link

yulrizka commented Dec 4, 2013

I've design my function to accept *sql.DB as the parameter. This way it's general enough if in the feature we want to use basic driver or switch between ORM.

The way I do this right now is something like this.

func Users(source *sql.DB) (users []User) {
    db := initGorm(source)
    db.Table("user").Find(&users)
}

func initGorm(source *sql.DB) *gorm.DB {
    result := gorm.SetDB("mysql", db)
    return &result
}

// on gorm/main.go
func SetDB(driver string, dbSource *sql.DB) (db DB) {
   db.db = dbSource
   db.dialect = dialect.New(driver)
   db.tagIdentifier = "sql"
   db.parent = &db
   return
}

Is this the right way to do this ? or gorm already have functionality that support this ?

@jinzhu
Copy link
Member

jinzhu commented Dec 5, 2013

For me, I think this is not the best way to do it, I am doing it like this:

// xxx/db.go
var DB gorm.DB
func init() {
  DB = gorm.Open("mysql", "xxxxxx")
}

// xxx/user.go
import . "xxx/db.go"

func Users() (users []User) {
  DB.Table("user").Find(users)
}

Then if you want to change to any other ORM, you just need to change the db package if the syntax is same.

@jinzhu jinzhu closed this as completed Dec 5, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants