2018-08-14 09:25:34 +00:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
|
2018-09-19 14:06:27 +00:00
|
|
|
"git.trj.tw/golang/mtfosbot/module/config"
|
2018-08-14 09:25:34 +00:00
|
|
|
"github.com/jmoiron/sqlx"
|
2018-08-22 09:20:12 +00:00
|
|
|
_ "github.com/lib/pq"
|
2018-08-14 09:25:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var x *sqlx.DB
|
|
|
|
|
|
|
|
// NewDB - connect to database
|
|
|
|
func NewDB() (*sqlx.DB, error) {
|
|
|
|
var err error
|
2018-09-19 14:06:27 +00:00
|
|
|
conf := config.GetConf()
|
2018-09-20 14:35:18 +00:00
|
|
|
userPassStr := conf.Database.User
|
|
|
|
if len(conf.Database.Pass) > 0 {
|
|
|
|
userPassStr += ":" + conf.Database.Pass
|
|
|
|
}
|
|
|
|
connStr := fmt.Sprintf("postgres://%s@%s/%s?sslmode=disable", userPassStr, conf.Database.Host, conf.Database.DB)
|
2018-08-28 03:55:38 +00:00
|
|
|
x, err = sqlx.Connect("postgres", connStr)
|
2018-08-14 09:25:34 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
x.SetMaxIdleConns(10)
|
|
|
|
x.SetMaxOpenConns(200)
|
|
|
|
err = x.Ping()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
return x, err
|
|
|
|
}
|
2018-09-19 14:06:27 +00:00
|
|
|
|
|
|
|
// GetDB -
|
|
|
|
func GetDB() *sqlx.DB {
|
|
|
|
return x
|
|
|
|
}
|