-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathconfig.go
129 lines (104 loc) · 2.42 KB
/
config.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package gobatis
import (
"database/sql"
"os"
"strings"
"time"
)
type config struct {
dbConf *DBConfig
mapperConf *mapperConfig
}
var conf *config
var db map[string]*GoBatisDB
func Init(option IOption) {
configInit(option.ToDBConf())
}
func configInit(dbConf *DBConfig) {
if nil == dbConf {
panic("Build db config err: dbConf == nil")
}
if len(dbConf.DB) <= 0 && dbConf.db == nil {
panic("No datasource config")
}
mapperConf := &mapperConfig{
mappedStmts: make(map[string]*node),
mappedSql: make(map[string]*node),
}
for _, item := range dbConf.Mappers {
f, err := os.Open(item)
if nil != err {
panic("Open mapper config: " + item + " err:" + err.Error())
}
LOG.Info("mapper config:%s %s", item, "init...")
mc := buildMapperConfig(f)
for k, ms := range mc.mappedStmts {
mapperConf.put(k, ms)
}
// sql tag cache
for k, ms := range mc.mappedSql {
mapperConf.putSql(k, ms)
}
}
conf = &config{
dbConf: dbConf,
mapperConf: mapperConf,
}
// init db
dbInit(dbConf)
}
func dbInit(dbConf *DBConfig) {
db = make(map[string]*GoBatisDB)
if len(dbConf.DB) <= 0 && dbConf.db == nil {
panic("No config for datasource")
}
for _, item := range dbConf.DB {
if item.DataSource == "" {
panic("DB config err: datasource must not be nil")
}
item.DataSource = strings.TrimSpace(item.DataSource)
_, ok := db[item.DataSource]
if ok {
panic("DB config datasource name repeat:" + item.DataSource)
}
if item.DriverName == "" {
panic("DB config err: driverName must not be nil")
}
if item.DataSourceName == "" {
panic("DB config err: dataSourceName must not be nil")
}
dbConn, err := sql.Open(item.DriverName, item.DataSourceName)
if nil != err {
panic(err)
}
if err := dbConn.Ping(); err != nil {
panic(err)
}
if item.MaxLifeTime == 0 {
dbConn.SetConnMaxLifetime(120 * time.Second)
} else {
dbConn.SetConnMaxLifetime(time.Duration(item.MaxLifeTime) * time.Second)
}
if item.MaxOpenConns == 0 {
dbConn.SetMaxOpenConns(10)
} else {
dbConn.SetMaxOpenConns(item.MaxOpenConns)
}
if item.MaxOpenConns == 0 {
dbConn.SetMaxIdleConns(5)
} else {
dbConn.SetMaxIdleConns(item.MaxIdleConns)
}
d := NewGoBatisDB(DBType(item.DriverName), dbConn)
db[item.DataSource] = d
}
if dbConf.db != nil {
for k, v := range dbConf.db {
_, ok := db[k]
if ok {
panic("DB config datasource name repeat:" + k)
}
db[k] = v
}
}
}