2019-06-28 09:37:37 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"dorisbot/pkg/config"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2019-06-30 15:05:54 +00:00
|
|
|
"log"
|
2019-06-28 09:37:37 +00:00
|
|
|
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Errors
|
|
|
|
var (
|
|
|
|
ErrDBNotInit = errors.New("database not init")
|
|
|
|
)
|
|
|
|
|
|
|
|
var x *sqlx.DB
|
|
|
|
|
|
|
|
// NewDB -
|
|
|
|
func NewDB(conf *config.Database) (*sqlx.DB, error) {
|
|
|
|
var err error
|
2019-07-02 10:05:26 +00:00
|
|
|
connStr := fmt.Sprintf("dbname=%s user=%s password=%s host=%s port=%d sslmode=disable",
|
2019-06-28 09:37:37 +00:00
|
|
|
conf.DBName,
|
|
|
|
conf.User,
|
|
|
|
conf.Pass,
|
|
|
|
conf.Host,
|
|
|
|
conf.Port,
|
|
|
|
)
|
2019-06-30 15:05:54 +00:00
|
|
|
log.Println("DB Connstr :: ", connStr)
|
2019-06-28 09:37:37 +00:00
|
|
|
|
|
|
|
x, err = sqlx.Connect("postgres", connStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return x, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ping database connection
|
|
|
|
func Ping() error {
|
|
|
|
if x == nil {
|
|
|
|
return ErrDBNotInit
|
|
|
|
}
|
|
|
|
return x.Ping()
|
|
|
|
}
|
2019-06-28 15:11:58 +00:00
|
|
|
|
|
|
|
// GetConn database connection
|
2019-07-13 09:44:31 +00:00
|
|
|
func GetConn() *sqlx.DB {
|
|
|
|
if x == nil {
|
|
|
|
panic(errors.New("database object not init"))
|
|
|
|
}
|
|
|
|
return x
|
|
|
|
}
|