File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package sqlagent
2+
3+ import (
4+ "github.com/RivenZoo/dsncfg"
5+ "sync"
6+ "gopkg.in/yaml.v2"
7+ "path"
8+ "strings"
9+ "io/ioutil"
10+ "encoding/json"
11+ )
12+
13+ var (
14+ initOnce = & sync.Once {}
15+ )
16+
17+ // Init module SqlAgent with database config.
18+ func Init (cfg * dsncfg.Database ) error {
19+ return initSqlAgent (cfg )
20+ }
21+
22+ // Init module SqlAgent with database config.
23+ // cfgFile: config file path, support file type [.json | .yaml/.yml], default decoder is json.
24+ func InitFromConfig (cfgFile string ) error {
25+ cfg , err := readDBConfig (cfgFile )
26+ if err != nil {
27+ return err
28+ }
29+ return initSqlAgent (cfg )
30+ }
31+
32+ // cfgFile: config file path, support file type [.json | .yaml/.yml], default decoder is json.
33+ func readDBConfig (cfgFile string ) (* dsncfg.Database , error ) {
34+ c , err := ioutil .ReadFile (cfgFile )
35+ if err != nil {
36+ return nil , err
37+ }
38+
39+ ext := path .Ext (cfgFile )
40+ ext = strings .ToLower (ext )
41+
42+ dbCfg := & dsncfg.Database {}
43+ switch ext {
44+ case ".yaml" , ".yml" :
45+ err = yaml .Unmarshal (c , dbCfg )
46+ default :
47+ // default: .json
48+ err = json .Unmarshal (c , dbCfg )
49+ }
50+ if err != nil {
51+ return nil , err
52+ }
53+ return dbCfg , nil
54+ }
55+
56+ // initSqlAgent init module SqlAgent only once.
57+ func initSqlAgent (cfg * dsncfg.Database ) (err error ) {
58+ initOnce .Do (func () {
59+ defaultAgent , err = NewSqlAgent (cfg )
60+ })
61+ return
62+ }
You can’t perform that action at this time.
0 commit comments