good morning!!!!

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

Drafting simple CRUD with mongo (Using Nieyemer's mgo http://labix.org/mgo).

parent 56aaab59
Branches
Tags
No related merge requests found
db/db.go 0 → 100644
/*
Copyright (c) 2012 José Carlos Nieto, http://xiam.menteslibres.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package db
type Database interface {
Connect() error
Use() error
Collection()
}
type Where map[string] interface{}
type And []interface{}
type Or []interface{}
type Sort map[string] interface{}
type Modify map[string] interface{}
type Limit uint
type Offset uint
type Set map[string] interface{}
type Upsert map[string] interface{}
type Query interface {
}
type Collection interface {
Append(...interface{}) bool
Find(...interface{}) []interface{}
Update(...interface{}) bool
Remove(...interface{}) bool
}
type DataSource struct {
Host string
Port int
Database string
User string
Password string
}
/*
Copyright (c) 2012 José Carlos Nieto, http://xiam.menteslibres.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package db
import (
. "github.com/xiam/gosexy"
"strings"
"launchpad.net/mgo"
)
type MongoDB struct {
config *DataSource
session *mgo.Session
database *mgo.Database
}
type MongoDBCollection struct {
parent *MongoDB
collection *mgo.Collection
}
type MongoDbQuery struct {
}
func (w Where) Marshal() map[string] interface{} {
conds := make(map[string] interface{})
for key, val := range(w) {
key = strings.Trim(key, " ")
chunks := strings.Split(key, " ")
if len(chunks) >= 2 {
conds[chunks[0]] = map[string] interface{} { chunks[1]: val }
} else {
conds[key] = val
}
}
return conds
}
func (c *MongoDBCollection) Append(items ...interface {}) bool {
// TODO: use reflection
length := len(items)
for i := 0; i < length; i++ {
err := c.collection.Insert(items[i])
if err != nil {
panic(err)
}
}
return true
}
func (c *MongoDBCollection) CompileConditions(term interface{}) interface{} {
switch term.(type) {
case []interface{}: {
values := []interface{} {}
itop := len(term.([]interface{}))
for i := 0; i < itop; i++ {
value := c.CompileConditions(term.([]interface{})[i])
if value != nil {
values = append(values, value)
}
}
if len(values) > 0 {
return values
}
}
case Or: {
values := []interface{} {}
itop := len(term.(Or))
for i := 0; i < itop; i++ {
values = append(values, c.CompileConditions(term.(Or)[i]))
}
condition := map[string]interface{} { "$or": values }
return condition
}
case And: {
values := []interface{} {}
itop := len(term.(And))
for i := 0; i < itop; i++ {
values = append(values, c.CompileConditions(term.(And)[i]))
}
condition := map[string]interface{} { "$and": values }
return condition
}
case Where: {
return term.(Where).Marshal()
}
}
return nil
}
func (c *MongoDBCollection) CompileQuery(terms []interface{}) interface{} {
var query interface {}
compiled := c.CompileConditions(terms)
if compiled != nil {
conditions := compiled.([]interface{})
if len(conditions) == 1 {
query = conditions[0]
} else {
query = map[string] interface{} { "$and": conditions }
}
} else {
query = map[string] interface {} {}
}
return query
}
func (c *MongoDBCollection) Remove(terms ...interface{}) bool {
query := c.CompileQuery(terms)
c.collection.RemoveAll(query)
return true
}
func (c *MongoDBCollection) Update(terms ...interface{}) bool {
var set interface{}
var upsert interface{}
var modify interface{}
set = nil
upsert = nil
modify = nil
query := c.CompileQuery(terms)
itop := len(terms)
for i := 0; i < itop; i++ {
term := terms[i]
switch term.(type) {
case Set: {
set = term.(Set)
}
case Upsert: {
upsert = term.(Upsert)
}
case Modify: {
modify = term.(Modify)
}
}
}
if set != nil {
c.collection.UpdateAll(query, Tuple { "$set": set })
return true
}
if upsert != nil {
c.collection.Upsert(query, upsert)
return true
}
if modify != nil {
c.collection.UpdateAll(query, modify)
return true
}
return false
}
func (c *MongoDBCollection) Find(terms ...interface{}) []interface{} {
var result []interface {}
var sort interface {}
limit := -1
offset := -1
sort = nil
// Conditions
query := c.CompileQuery(terms)
itop := len(terms)
for i := 0; i < itop; i++ {
term := terms[i]
switch term.(type) {
case Limit: {
limit = int(term.(Limit))
}
case Offset: {
offset = int(term.(Offset))
}
case Sort: {
sort = term.(Sort)
}
}
}
// Actually executing query, returning a pointer.
p := c.collection.Find(query)
// Applying limits and offsets.
if offset > -1 {
p = p.Skip(offset)
}
if limit > -1 {
p = p.Limit(limit)
}
// Sorting result
if sort != nil {
p = p.Sort(sort)
}
// Retrieving data
p.All(&result)
return result
}
func NewMongoDB(config *DataSource) *MongoDB {
m := &MongoDB{}
m.config = config
return m
}
func (m *MongoDB) Use(database string) bool {
m.config.Database = database
m.database = m.session.DB(m.config.Database)
return true
}
func (m *MongoDB) Collection(name string) Collection {
c := &MongoDBCollection{}
c.parent = m
c.collection = m.database.C(name)
return c
}
func (m *MongoDB) Connect() error {
var err error
m.session, err = mgo.Dial(m.config.Host)
if m.config.Database != "" {
m.Use(m.config.Database)
}
return err
}
package db
import (
. "github.com/xiam/gosexy"
"testing"
)
func TestAll(t *testing.T) {
db := NewMongoDB(&DataSource{ Host: "localhost", Database: "test" })
err := db.Connect()
if err != nil {
panic(err)
}
// Choose database
db.Use("test")
// Choose collection
col := db.Collection("people")
// Testing insert
col.Append(Tuple { "Name": "Tucket11", "LastName": "Nancy" })
col.Find()
col.Find(
Where { "Name": "Tucket" },
)
col.Find(
Where { "Name": "Tucket" },
Where { "LastName $ne": "Barr" },
Limit (2),
Offset (5),
Sort { "Name": -1 },
)
col.Update(Where {"Name": "Tucket" }, Set { "FooSet": "Bar", "Name": "Tucket3" })
col.Update(Where {"Name": "Tucket5" }, Upsert { "Heh": "Bar" })
col.Update(Where {"Name": "Tucket3" }, Modify { "$unset": "FooSet" })
col.Remove(Where { "Name": "Tucket" })
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment