package mongo import ( "github.com/dalu/gopiwik/piwik" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func NewSiteStorage(ms *mgo.Session, db, col string) SiteStorage { return SiteStorage{ ms: ms.Clone(), db: db, col: col, } } type SiteStorage struct { ms *mgo.Session db, col string } func (s SiteStorage) Add(site *piwik.Site) error { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) site.ID = bson.NewObjectId().Hex() return c.Insert(site) } func (s SiteStorage) Remove(site *piwik.Site) error { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) return c.RemoveId(site.ID) } func (s SiteStorage) Update(site *piwik.Site) error { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) return c.UpdateId(site.ID, site) } func (s SiteStorage) List() ([]*piwik.Site, error) { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) sites := []*piwik.Site{} if e := c.Find(nil).All(&sites); e != nil { return sites, e } return sites, nil } func (s SiteStorage) FindId(id string) (*piwik.Site, error) { ms := s.ms.Copy() defer ms.Close() site := new(piwik.Site) c := ms.DB(s.db).C(s.col) if e := c.FindId(id).One(site); e != nil { return nil, e } return site, nil } func (s SiteStorage) Find(query map[string]interface{}) (*piwik.Site, error) { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) site := new(piwik.Site) if e := c.Find(query).One(site); e != nil { return nil, e } return site, nil } func (s SiteStorage) FindAll(query map[string]interface{}) ([]*piwik.Site, error) { ms := s.ms.Copy() defer ms.Close() c := ms.DB(s.db).C(s.col) sites := []*piwik.Site{} if e := c.Find(query).All(&sites); e != nil { return sites, e } return sites, nil }