diff --git a/repository/connector.go b/repository/connector.go index 8e4ab15..92dca49 100644 --- a/repository/connector.go +++ b/repository/connector.go @@ -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 }