forked from andeya/faygo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
78 lines (66 loc) · 1.8 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package gorm
import (
"os"
"path/filepath"
"strings"
"github.com/jinzhu/gorm"
// _ "github.com/jinzhu/gorm/dialects/mssql" //github.com/denisenkom/go-mssqldb
_ "github.com/jinzhu/gorm/dialects/mysql" //github.com/go-sql-driver/mysql
_ "github.com/jinzhu/gorm/dialects/postgres" //github.com/lib/pq
// _ "github.com/jinzhu/gorm/dialects/sqlite" //github.com/mattn/go-sqlite3
"github.com/henrylee2cn/faygo"
)
// DBService is a database engine object.
type DBService struct {
Default *gorm.DB // the default database engine
List map[string]*gorm.DB // database engine list
}
var dbService = func() (serv *DBService) {
serv = &DBService{
List: map[string]*gorm.DB{},
}
var errs []string
defer func() {
if len(errs) > 0 {
panic("[gorm] " + strings.Join(errs, "\n"))
}
if serv.Default == nil {
faygo.Panicf("[gorm] the `default` database engine must be configured and enabled")
}
}()
err := loadDBConfig()
if err != nil {
faygo.Panicf("[gorm]", err.Error())
return
}
for _, conf := range dbConfigs {
if !conf.Enable {
continue
}
engine, err := gorm.Open(conf.Driver, conf.Connstring)
if err != nil {
faygo.Critical("[gorm]", err.Error())
errs = append(errs, err.Error())
continue
}
engine.SetLogger(faygo.NewLog())
engine.LogMode(conf.ShowSql)
engine.DB().SetMaxOpenConns(conf.MaxOpenConns)
engine.DB().SetMaxIdleConns(conf.MaxIdleConns)
if conf.Driver == "sqlite3" && !faygo.FileExists(conf.Connstring) {
os.MkdirAll(filepath.Dir(conf.Connstring), 0777)
f, err := os.Create(conf.Connstring)
if err != nil {
faygo.Critical("[gorm]", err.Error())
errs = append(errs, err.Error())
} else {
f.Close()
}
}
serv.List[conf.Name] = engine
if DEFAULTDB_NAME == conf.Name {
serv.Default = engine
}
}
return
}()