genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
hs_monolith/lib/database/main.go

67 lines
1.4 KiB
Go
Raw Normal View History

2017-03-30 16:09:44 +02:00
package database
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
2017-03-30 17:02:20 +02:00
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/genofire/hs_master-kss-monolith/lib/log"
2017-03-30 16:09:44 +02:00
)
var (
2017-03-30 17:02:20 +02:00
Write *gorm.DB
Read *gorm.DB
2017-03-30 16:09:44 +02:00
config *Config
runtime []interface{}
2017-03-30 16:09:44 +02:00
)
type Config struct {
2017-03-30 17:02:20 +02:00
Type string
Connection string
2017-03-30 16:09:44 +02:00
ReadConnection string
Logging bool
2017-03-30 16:09:44 +02:00
}
2017-03-30 16:16:19 +02:00
func Open(c Config) (err error) {
writeLog := log.Log.WithField("db", "write")
2017-03-30 16:09:44 +02:00
config = &c
Write, err = gorm.Open(config.Type, config.Connection)
if err != nil {
return
}
2017-03-30 18:44:09 +02:00
Write.SingularTable(true)
2017-03-31 10:57:01 +02:00
Write.LogMode(c.Logging)
Write.SetLogger(writeLog)
2017-03-30 18:44:09 +02:00
Write.Callback().Create().Remove("gorm:update_time_stamp")
Write.Callback().Update().Remove("gorm:update_time_stamp")
2017-03-30 16:09:44 +02:00
if len(config.ReadConnection) > 0 {
readLog := log.Log.WithField("db", "read")
2017-03-30 16:09:44 +02:00
Read, err = gorm.Open(config.Type, config.ReadConnection)
if err != nil {
return
}
2017-03-30 18:44:09 +02:00
Read.SingularTable(true)
2017-03-31 10:57:01 +02:00
Read.LogMode(c.Logging)
Read.SetLogger(readLog)
2017-03-30 18:44:09 +02:00
Read.Callback().Create().Remove("gorm:update_time_stamp")
Read.Callback().Update().Remove("gorm:update_time_stamp")
2017-03-30 16:09:44 +02:00
} else {
Read = Write
}
Write.AutoMigrate(runtime...)
2017-03-30 16:09:44 +02:00
return
}
func Close() {
Write.Close()
2017-03-30 18:44:09 +02:00
Write = nil
2017-03-30 16:09:44 +02:00
if len(config.ReadConnection) > 0 {
Read.Close()
}
2017-03-30 18:44:09 +02:00
Read = nil
2017-03-30 16:09:44 +02:00
}
func AddModel(m interface{}) {
runtime = append(runtime, m)
2017-03-30 16:09:44 +02:00
}