forked from golang/hotime
59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
|
package hotime
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
_ "github.com/go-sql-driver/mysql"
|
||
|
_ "github.com/mattn/go-sqlite3"
|
||
|
)
|
||
|
|
||
|
func SetDB(appIns *Application) {
|
||
|
db := appIns.Config.GetMap("db")
|
||
|
dbSqlite := db.GetMap("sqlite")
|
||
|
dbMysql := db.GetMap("mysql")
|
||
|
if db != nil && dbSqlite != nil {
|
||
|
SetSqliteDB(appIns, dbSqlite)
|
||
|
}
|
||
|
if db != nil && dbMysql != nil {
|
||
|
SetMysqlDB(appIns, dbMysql)
|
||
|
}
|
||
|
}
|
||
|
func SetMysqlDB(appIns *Application, config Map) {
|
||
|
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||
|
//master数据库配置
|
||
|
query := config.GetString("user") + ":" + config.GetString("password") +
|
||
|
"@tcp(" + config.GetString("host") + ":" + config.GetString("port") + ")/" + config.GetString("name") + "?charset=utf8"
|
||
|
DB, e := sql.Open("mysql", query)
|
||
|
if e != nil && len(err) != 0 {
|
||
|
err[0].SetError(e)
|
||
|
}
|
||
|
master = DB
|
||
|
//slave数据库配置
|
||
|
configSlave := config.GetMap("slave")
|
||
|
if configSlave != nil {
|
||
|
query := configSlave.GetString("user") + ":" + configSlave.GetString("password") +
|
||
|
"@tcp(" + config.GetString("host") + ":" + configSlave.GetString("port") + ")/" + configSlave.GetString("name") + "?charset=utf8"
|
||
|
DB1, e := sql.Open("mysql", query)
|
||
|
if e != nil && len(err) != 0 {
|
||
|
err[0].SetError(e)
|
||
|
}
|
||
|
slave = DB1
|
||
|
}
|
||
|
|
||
|
return master, slave
|
||
|
//return DB
|
||
|
})
|
||
|
appIns.Db.Type = "mysql"
|
||
|
}
|
||
|
func SetSqliteDB(appIns *Application, config Map) {
|
||
|
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||
|
db, e := sql.Open("sqlite3", config.GetString("path"))
|
||
|
if e != nil && len(err) != 0 {
|
||
|
err[0].SetError(e)
|
||
|
}
|
||
|
master = db
|
||
|
|
||
|
return master, slave
|
||
|
})
|
||
|
appIns.Db.Type = "sqlite"
|
||
|
}
|