Skip to content

Instantly share code, notes, and snippets.

@LYY
Created July 15, 2015 12:13
Show Gist options
  • Select an option

  • Save LYY/b7fd1c4402ca1ce25e5b to your computer and use it in GitHub Desktop.

Select an option

Save LYY/b7fd1c4402ca1ce25e5b to your computer and use it in GitHub Desktop.
gorm.go
package utils
import (
"database/sql"
"fmt"
"github.com/adjust/goenv"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/jrallison/go-workers"
"strings"
)
var Db gorm.DB
type GormDB struct {
*gorm.DB
}
func InitDB() {
config := getDatabaseConfig()
var connstring string
connstring = getConnectionString(config)
var err error
Db, err = gorm.Open("mysql", connstring)
if err != nil {
workers.Logger.Println("***FATAL*** ", err)
panic(err)
}
// Then you could invoke `*sql.DB`'s functions with it
Db.DB().SetMaxIdleConns(config.GetInt("pool", 5))
Db.DB().SetMaxOpenConns(config.GetInt("maxopen", 0))
Db.LogMode(IsDevEnv())
}
func getConnectionString(config *goenv.Goenv) string {
host := config.Get("host", "")
port := config.Get("port", "3306")
user := config.Get("username", "")
pass := config.Get("password", "")
dbname := config.Get("database", "")
protocol := config.Get("protocol", "tcp")
dbargs := config.Get("dbargs", " ")
if strings.Trim(dbargs, " ") != "" {
dbargs = "?" + dbargs
} else {
dbargs = ""
}
return fmt.Sprintf("%s:%s@%s([%s]:%s)/%s%s", user, pass, protocol, host, port, dbname, dbargs)
}
func DbBegin() *GormDB {
txn := Db.Begin()
if txn.Error != nil {
panic(txn.Error)
}
return &GormDB{txn}
}
func (c *GormDB) DbCommit() {
c.Commit()
if err := c.Error; err != nil && err != sql.ErrTxDone {
panic(err)
}
}
func (c *GormDB) DbRollback() {
c.Rollback()
if err := c.Error; err != nil && err != sql.ErrTxDone {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment