Make repository reflect Config changes by adding a Connect method

master
Nick Krichevsky 2019-03-08 22:33:46 -05:00
parent 187b84f76f
commit 044d4fdd1b
1 changed files with 21 additions and 4 deletions

View File

@ -2,23 +2,40 @@ package repository
import (
"database/sql"
"errors"
_ "github.com/lib/pq"
)
const driver = "postgres"
// ErrNotConnected is returned when the database connection has never been attempted
var ErrNotConnected = errors.New("repository: Database connection was never established")
var connector *DatabaseConnector
// DatabaseConnector holds a connection to the database
type DatabaseConnector struct {
*sql.DB
}
// NewDatabaseConnector opens a new database connection with the given uri
func NewDatabaseConnector(uri string) (*DatabaseConnector, error) {
connection, err := sql.Open(driver, uri)
// GetConnector gets the stored database connection
func GetConnector() *DatabaseConnector {
if connector == nil {
panic(ErrNotConnected)
}
return connector
}
// Connect connects to the database
func Connect() (*DatabaseConnector, error) {
connectorCandidate, err := initDatabaseConnector()
if err != nil {
return nil, err
}
return &DatabaseConnector{connection}, connection.Ping()
connector = connectorCandidate
return connector, nil
}