//database.go
package database
import (
"net/url"
"fmt"
"db"
"os"
"strconv"
)
//Manages a database connection along with the required information
type Database struct {
Host string
Port int
Database string
Handle *db.Client
}
//Constructor that returns a reference to a new database
func NewDatabase(db string) Database {
port, err := strconv.Atoi(os.Getenv("DB_PORT"))
if err != nil {
port = 8086
}
return Database{
os.Getenv("DB_HOST"),
port,
db,
nil,
}
}
//Gets the database being used
func (d Database) GetDatabase() string {
return d.Database
}
//Sets the database to be used
func (d *Database) SetDatabase(db string) {
d.Database = db
}
//Connects to the database and stores the handle
func (d *Database) Connect() error {
u, err := url.Parse(fmt.Sprintf("http://%s:%d", d.Host, d.Port))
if err != nil {
return err
}
conf := db.Config{
URL: *u,
}
con, err := db.NewClient(conf)
if err != nil {
return err
}
d.Handle = con
return nil
}
//Tests the connection to the database
func (d Database) Ping() error {
d.Connect()
_, _, err := d.Handle.Ping()
if err != nil {
return err
}
return nil
}
//Queries the database and returns the results
func (d Database) Query(q string) (string, error) {
query := db.Query{
Command: q,
Database: d.Database,
}
var results string
if response, err := d.Handle.Query(query); err == nil {
if response.Error() != nil {
return results, response.Error()
}
json, err := response.MarshalJSON()
if err != nil {
return results, err
}
results = string(json)
} else {
return results, err
}
return results, nil
}