dorisbot/models/models.go
2019-06-28 15:11:58 +00:00

51 lines
809 B
Go

package models
import (
"dorisbot/pkg/config"
"errors"
"fmt"
"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
connStr := fmt.Sprintf("dbname=%s user=%s password=%s host=%s port=%d sslmode=%s sslrootcert=%s sslcert=%s sslkey=%s",
conf.DBName,
conf.User,
conf.Pass,
conf.Host,
conf.Port,
conf.SSLMode,
conf.SSLCa,
conf.SSLCrt,
conf.SSLKey,
)
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()
}
// GetConn database connection
func GetConn() *sqlx.DB { return x }