31 lines
695 B
Go
31 lines
695 B
Go
package postgres
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
|
|
"git.tek.govt.hu/dowerx/chat/server/config"
|
|
"git.tek.govt.hu/dowerx/chat/server/util"
|
|
"github.com/jmoiron/sqlx"
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
var db *sqlx.DB
|
|
var mu sync.Mutex
|
|
|
|
func getDatabase() (*sqlx.DB, *util.ChatError) {
|
|
mu.Lock()
|
|
if db == nil {
|
|
cfg := config.GetConfig()
|
|
newDB, err := sqlx.Connect("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.DBname))
|
|
if err != nil {
|
|
mu.Unlock()
|
|
return nil, util.MakeError(err, util.DATABASE_CONNECTION_FAULT)
|
|
}
|
|
db = newDB
|
|
}
|
|
|
|
mu.Unlock()
|
|
return db, nil
|
|
}
|