1
0
mirror of synced 2024-11-22 12:26:02 +03:00
mg-transport-telegram/database.go
Alex Lushpai acb2a62da5
Initial release (#1)
Routes
Migrations
Settings form
Activation/deactivation through retailCRM/MG Transport API
2018-05-17 18:35:53 +03:00

52 lines
1.1 KiB
Go

package main
import (
"time"
"github.com/getsentry/raven-go"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
// Orm struct
type Orm struct {
DB *gorm.DB
}
// NewDb init new database connection
func NewDb(config *TransportConfig) *Orm {
db, err := gorm.Open("postgres", config.Database.Connection)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
panic(err)
}
db.DB().SetConnMaxLifetime(time.Duration(config.Database.ConnectionLifetime) * time.Second)
db.DB().SetMaxOpenConns(config.Database.MaxOpenConnections)
db.DB().SetMaxIdleConns(config.Database.MaxIdleConnections)
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return config.Database.TablePrefix + defaultTableName
}
db.SingularTable(true)
db.LogMode(config.Database.Logging)
setCreatedAt := func(scope *gorm.Scope) {
if scope.HasColumn("CreatedAt") {
scope.SetColumn("CreatedAt", time.Now())
}
}
db.Callback().Create().Replace("gorm:update_time_stamp", setCreatedAt)
return &Orm{
DB: db,
}
}
// Close connection
func (orm *Orm) Close() {
orm.DB.Close()
}