|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/go-xorm/xorm" |
| 5 | + "os" |
| 6 | + "runtime" |
| 7 | + "path" |
| 8 | + "github.com/BurntSushi/toml" |
| 9 | + "errors" |
| 10 | + xcore "github.com/go-xorm/core" |
| 11 | +) |
| 12 | + |
| 13 | +type DB struct { |
| 14 | + Cfg Connection |
| 15 | + Engine *xorm.Engine |
| 16 | +} |
| 17 | + |
| 18 | +type Connection struct { |
| 19 | + Driver string |
| 20 | + Dsn string |
| 21 | + Log bool |
| 22 | + LogLevel int |
| 23 | + LogFile string |
| 24 | +} |
| 25 | + |
| 26 | +type Connections struct { |
| 27 | + Connections map[string]Connection |
| 28 | +} |
| 29 | + |
| 30 | +func GetDbConfigs() map[string]Connection { |
| 31 | + var conns Connections |
| 32 | + _, filename, _, _ := runtime.Caller(1) |
| 33 | + cfg := path.Join(path.Dir(filename), "/../config/db.toml") |
| 34 | + if _, err := toml.DecodeFile(cfg, &conns); err != nil { |
| 35 | + panic(errors.New("parse db.toml fail: " + err.Error())) |
| 36 | + } |
| 37 | + return conns.Connections |
| 38 | +} |
| 39 | + |
| 40 | +func GetDbConfig(id string) Connection { |
| 41 | + conns := GetDbConfigs() |
| 42 | + conn, err := conns[id] |
| 43 | + if !err { |
| 44 | + panic(errors.New("connection " + id + " is not available")) |
| 45 | + } |
| 46 | + return conn |
| 47 | +} |
| 48 | + |
| 49 | +func NewDB(conn string) *DB { |
| 50 | + cfg := GetDbConfig(conn) |
| 51 | + db := &DB{cfg, nil} |
| 52 | + |
| 53 | + var err error |
| 54 | + db.Engine, err = xorm.NewEngine(cfg.Driver, cfg.Dsn) |
| 55 | + if err != nil { |
| 56 | + panic(err) |
| 57 | + } |
| 58 | + |
| 59 | + if cfg.Log { |
| 60 | + //log into file |
| 61 | + if len(cfg.LogFile) > 0 { |
| 62 | + f, err := os.OpenFile(cfg.LogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) |
| 63 | + if err != nil { |
| 64 | + panic(err) |
| 65 | + } |
| 66 | + db.Engine.SetLogger(xorm.NewSimpleLogger(f)) |
| 67 | + } //else log into console |
| 68 | + |
| 69 | + db.Engine.ShowSQL(true) |
| 70 | + db.Engine.ShowExecTime(true) |
| 71 | + db.Engine.Logger().SetLevel(xcore.LogLevel(cfg.LogLevel)) |
| 72 | + } |
| 73 | + |
| 74 | + return db |
| 75 | +} |
0 commit comments