good morning!!!!

Skip to content
Snippets Groups Projects
Commit 75d1ac85 authored by José Carlos Nieto's avatar José Carlos Nieto
Browse files

This will allow to register drivers like database/sql.

parent 2c99deab
No related branches found
No related tags found
No related merge requests found
......@@ -186,6 +186,8 @@ type Database interface {
Use(string) error
Drop() error
Setup(DataSource) error
}
// Collection methods.
......@@ -323,3 +325,23 @@ func (item Item) GetBool(name string) bool {
return true
}
var wrappers = make(map[string]Database)
func Register(name string, driver Database) {
if name == "" {
panic("db: Wrapper name cannot be nil.")
}
if _, ok := wrappers[name]; ok != false {
panic("db: Wrapper was already registered.")
}
wrappers[name] = driver
}
func Open(name string, settings DataSource) Database {
if _, ok := wrappers[name]; ok == false {
panic(fmt.Sprintf("db: Unknown wrapper: %s.", name))
}
wrappers[name].Setup(settings)
return wrappers[name]
}
package main
import (
"fmt"
"github.com/gosexy/db"
_ "github.com/gosexy/db/mongo"
"github.com/gosexy/sugar"
)
func main() {
sess := db.Open("mongo", db.DataSource{Host: "127.0.0.1", Database: "gosexy-dev"})
if sess == nil {
panic("Could not open connection to MongoDB.")
}
defer sess.Close()
sess.Drop()
animals := sess.Collection("animals")
animals.Append(db.Item{
"animal": "Bird",
"young": "Chick",
"female": "Hen",
"male": "Cock",
"group": "flock",
})
animals.Append(db.Item{
"animal": "Bovidae",
"young": "Calf",
"female": "Cow",
"male": "Bull",
"group": "Herd",
})
animals.Append(db.Item{
"animal": "Canidae",
"young": sugar.List{"Puppy", "Pup"},
"female": "Bitch",
"male": "Dog",
"group": "Pack",
})
items := animals.FindAll()
for _, item := range items {
fmt.Printf("animal: %s, young: %s\n", item["animal"], item["young"])
}
}
......@@ -36,6 +36,10 @@ import (
"time"
)
func init() {
db.Register("mongo", &MongoDataSource{})
}
// Session
type MongoDataSource struct {
config db.DataSource
......@@ -506,6 +510,11 @@ func Session(config db.DataSource) db.Database {
return m
}
func (m *MongoDataSource) Setup(config db.DataSource) error {
m.config = config
return m.Open()
}
// Sets the active database.
func (m *MongoDataSource) Use(database string) error {
m.config.Database = database
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment