bit4sat/db/db.go
Chakib Benziane 57b7fd0889 wip postgres
2019-03-27 10:57:01 +01:00

86 lines
1.3 KiB
Go

package db
import (
"fmt"
"log"
"os"
_ "github.com/lib/pq"
//_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/mediocregopher/radix/v3"
)
const (
//DBName = "bit4sat.sqlite"
DBName = "bit4sat"
DBHostEnv = "DB_HOST"
DBUserEnv = "DB_USER"
DBPassEnv = "DB_PASS"
//DBPragma = ` PRAGMA foreign_keys = ON; `
)
var (
DB *Database
)
type Database struct {
Sql *sqlx.DB
Redis *radix.Pool
}
func (d *Database) Open() error {
var err error
// Get env vars
host, set := os.LookupEnv(DBHostEnv)
if !set {
log.Fatal("undefined DB_HOST env")
}
user, set := os.LookupEnv(DBUserEnv)
if !set {
log.Fatal("undefined DB_USER env")
}
pass, set := os.LookupEnv(DBPassEnv)
if !set {
log.Fatal("undefined DB_PASS env")
}
dsn := fmt.Sprintf("%s:%s@%s/%s", user, pass, host, DBName)
log.Printf("Opening SQL at %s\n", dsn)
d.Sql = sqlx.MustConnect("postgres", dsn)
// Execute Pragmas
//d.Sql.MustExec(DBPragma)
// Opend redis
d.Redis, err = radix.NewPool("tcp", "redis:6379", 10)
if err != nil {
log.Fatal(err)
}
return nil
}
func RollbackTx(tx *sqlx.Tx, callback func()) {
log.Println("Rolling back transactions !")
err := tx.Rollback()
if err != nil {
log.Fatal(err)
}
if callback != nil {
callback()
}
}
func init() {
DB = &Database{}
DB.Open()
}