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.
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"
|
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
|
|
|
|
models []interface{}
|
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2017-03-30 16:16:19 +02:00
|
|
|
func Open(c Config) (err error) {
|
2017-03-30 16:09:44 +02:00
|
|
|
config = &c
|
|
|
|
Write, err = gorm.Open(config.Type, config.Connection)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if len(config.ReadConnection) > 0 {
|
|
|
|
Read, err = gorm.Open(config.Type, config.ReadConnection)
|
|
|
|
} else {
|
|
|
|
Read = Write
|
|
|
|
}
|
|
|
|
Write.AutoMigrate(models...)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func Close() {
|
|
|
|
Write.Close()
|
|
|
|
if len(config.ReadConnection) > 0 {
|
|
|
|
Read.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func AddModel(m interface{}) {
|
|
|
|
models = append(models, m)
|
|
|
|
}
|