gmgo

package module
v0.0.0-...-df99eb4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2018 License: MIT Imports: 9 Imported by: 2

README

gmgo

Convenient wrapper around Go's MongoDB driver Mgo

Usage:

package main

import (
	"fmt"
	"github.com/narup/gmgo"
	"log"
)

var userDB gmgo.Db

####################
type User struct {
    Name string `json:"name" bson:"name"`
    Email string `json:"email" bson:"email"`
}

// Each of your data model that needs to be persisted should implment gmgo.Document interface
func (user User) CollectionName() string {
    return "user"
}

####################

func saveNewUser() {
   session := userDB.Session()
   defer session.Close()
   
   user := &User{Name:'Puran', Email:'puran@xyz.com'}
   user.Id = bson.NewObjectId()
   userId, err := session.Save(user)
   if err != nil {
	log.Fatalf("Error saving user : %s.\n", err)
   }

   fmt.Printf("User id %s", userId)
}

func findUser(userId string) *User {
    session := userDB.Session()
    defer session.Close()
   
    user := new(User)
    if err := session.FindByID(userId, user); err != nil {
        return nil
    }
    return user
}

//Find all users
func findAllUsers() {
    session := userDB.Session()
    defer session.Close()

    users, err := session.FindAll(gmgo.Q{}, new(User)) //Note user pointer is passed to identify the collection type etc.
    if err != nil {
    	fmt.Printf("Error fetching users %s", err)
    } else {
	    for _, user := range users {
	        fmt.Println(user.Name)
        }
    }
}

func findUsingIterator() ([]*user, error) {
	session := testDBSession()
	defer session.Close()

    users := make([]*user, 0)

	itr := session.DocumentIterator(Q{"state": "CA"}, "user")
	itr.Load(IteratorConfig{Limit: 20, SortBy: []string{"-_id"}})

	result, err := itr.All(new(user))
	if err != nil {
		println(err)
		return
	}
	users := result.([]*user)
	for _, usr := range users {
		println(usr.ID.Hex() + " -- " + usr.CreatedDate.String())
	}
	
    return users, nil 
}

func setupUserDB() {
    if userDbErr := gmgo.Setup(gmgo.DbConfig{"localhost:27017", "userdb", "", ""}); userDbErr != nil {
    		log.Fatalf("Database connection error : %s.\n", userDbErr)
    		return
    }

    newDb, userDbErr := gmgo.New("userdb")
    if userDbErr != nil {
        log.Fatalf("Db connection error : %s.\n", err)
    }
    userDB = newDb
}

func main() {
    //setup Mongo database connection. You can setup multiple db connections
    setupUserDB()
    user := findUser("56596608e4b07ceddcfad96e")
    if user != nil {
    	fmt.Printf("User name:%s\n", user.Name)
    } else {
	fmt.Printf("Couldn't find user")
    }
	
    findAllUsers()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Setup

func Setup(dbConfig DbConfig) error

Setup the MongoDB connection based on passed in config. It can be called multiple times to setup connection to multiple MongoDB instances.

Types

type Db

type Db struct {
	Config DbConfig
	// contains filtered or unexported fields
}

Db represents database connection which holds reference to global session and configuration for that database.

func Get

func Get(dbName string) (Db, error)

Get creates new database connection

func (Db) Session

func (db Db) Session() *DbSession

Session creates the copy of the gmgo session

type DbConfig

type DbConfig struct {
	HostURL, DBName, UserName, Password string
	Hosts                               []string
	Mode                                int
}

DbConfig represents the configuration params needed for MongoDB connection

type DbSession

type DbSession struct {
	Session *mgo.Session
	// contains filtered or unexported fields
}

DbSession mgo session wrapper

func (*DbSession) Clone

func (s *DbSession) Clone() *DbSession

Clone returns the clone of current DB session. Cloned session uses the same socket connection

func (*DbSession) Close

func (s *DbSession) Close()

Close closes the underlying mgo session

func (*DbSession) Collection

func (s *DbSession) Collection(d Document) *mgo.Collection

Collection returns a mgo.Collection representation for given document

func (*DbSession) DocumentIterator

func (s *DbSession) DocumentIterator(query Q, collection string) *DocumentIterator

DocumentIterator returns the document iterator which could be used to fetch documents as batch with batch size and other config params

func (*DbSession) Exists

func (s *DbSession) Exists(query Q, document Document) (bool, error)

Exists check if the document exists for given query

func (*DbSession) Find

func (s *DbSession) Find(query Q, document Document) error

Find the data based on given query

func (*DbSession) FindAll

func (s *DbSession) FindAll(query Q, document Document) (interface{}, error)

FindAll returns all the documents based on given query

func (*DbSession) FindAllWithFields

func (s *DbSession) FindAllWithFields(query Q, fields []string, document Document) (interface{}, error)

FindAllWithFields returns all the documents with given fields based on a given query

func (*DbSession) FindByID

func (s *DbSession) FindByID(id string, result Document) error

FindByID find the object by id. Returns error if it's not able to find the document. If document is found it's copied to the passed in result object.

func (*DbSession) FindByRef

func (s *DbSession) FindByRef(ref *mgo.DBRef, document Document) error

FindByRef finds the document based on given db reference.

func (*DbSession) FindWithLimit

func (s *DbSession) FindWithLimit(limit int, query Q, document Document) (interface{}, error)

FindWithLimit find the doucments for given query with limit

func (*DbSession) Pipe

func (s *DbSession) Pipe(pipeline interface{}, document Document) *mgo.Pipe

Pipe returns the pipe for a given query and document

func (*DbSession) ReadFile

func (s *DbSession) ReadFile(id, prefix string, file *File) error

ReadFile read file based on given id

func (*DbSession) Remove

func (s *DbSession) Remove(query Q, document Document) error

Remove removes the given document type based on the query

func (*DbSession) RemoveAll

func (s *DbSession) RemoveAll(query Q, document Document) error

RemoveAll removes all the document matching given selector query

func (*DbSession) Save

func (s *DbSession) Save(document Document) error

Save inserts the given document that represents the collection to the database.

func (*DbSession) SaveFile

func (s *DbSession) SaveFile(file File, prefix string) (string, error)

SaveFile saves the given file in a gridfs

func (*DbSession) Update

func (s *DbSession) Update(selector Q, document Document) error

Update updates the given document based on given selector

func (*DbSession) UpdateFieldValue

func (s *DbSession) UpdateFieldValue(query Q, collectionName, field string, value interface{}) error

UpdateFieldValue updates the single field with a given value for a collection name based query

type Document

type Document interface {
	CollectionName() string
}

Document interface implemented by structs that needs to be persisted. It should provide collection name, as in the database. Also, a way to create new object id before saving.

type DocumentIterator

type DocumentIterator struct {
	// contains filtered or unexported fields
}

DocumentIterator is used to iterate over results and also provides a way to configure query using IteractorConfig For example:

	session := db.Session()
	defer session.Close()

	pd := session.DocumentIterator(gmgo.Q{"state":"CA"}, "user")
	pd.Load(gmgo.IteratorConfig{PageSize: 200, Snapshot: true})
	for pd.HasMore() {
     usr := new(user)
		result, err := pd.Next(&usr)
		if err != nil {
			println(err.Error())
			return
		}
 	u := result.(*user)
	}

func (*DocumentIterator) All

func (pd *DocumentIterator) All(document Document) (interface{}, error)

All returns all the documents in the iterator.

func (*DocumentIterator) Close

func (pd *DocumentIterator) Close() error

Close closes the document iterator

func (*DocumentIterator) Error

func (pd *DocumentIterator) Error() error

Error returns iteration error

func (*DocumentIterator) FetchNext

func (pd *DocumentIterator) FetchNext(d interface{}) bool

FetchNext retrieves the next document from the result set. For more details see mgo.Iter.Next() return false if there are no more records to fetch

Usage:

	aitr := session.DocumentIterator(gmgo.Q{}, data.User{}.CollectionName())
	aitr.Load(gmgo.IteratorConfig{PageSize: 1000, SortBy: []string{"-_id"}})
	var usr *data.User
	for aitr.FetchNext(&usr) {
    fmt.Printf("ID: %s", usr.Id)
	}

 //check if error happend
 err := aitr.Error()
	if err != nil {
		fmt.Printf("handle error: %s", err)
	}

 //check if timeout happened
 if aitr.IsTimeOut() {
	   -- handle timeout
 }

func (*DocumentIterator) HasMore

func (pd *DocumentIterator) HasMore() bool

HasMore returns true if paged document has still more documents to fetch. DEPRECATED Use FetchNext in favor of this

func (*DocumentIterator) IsTimeout

func (pd *DocumentIterator) IsTimeout() bool

IsTimeout returns true if the iterator timed out

func (*DocumentIterator) Load

func (pd *DocumentIterator) Load(cfg IteratorConfig)

Load loads the document iterator using IteratorConfig For example: Limit and sort by user full name

itr := session.DocumentIterator(Q{"state": "CA"}, new(user))
itr.Load(IteratorConfig{Limit: 20, SortBy: []string{"fullName"}})

fetch with page size

pd.Load(IteratorConfig{PageSize: 200})

func (*DocumentIterator) Next

func (pd *DocumentIterator) Next(d Document) error

Next returns the next result object in the paged document. If there's no element it will check for error and return the error if there's error. DEPRECATED - Use FetchNext in favor of this

type File

type File struct {
	ID          string
	Name        string
	ContentType string
	ByteLength  int
	Data        []byte
}

File file representation

type IteratorConfig

type IteratorConfig struct {
	//PageSize is used as a batch size. See mgo.Iter.Batch() for more details.
	//Default value used by MongoDB is 100. So, any value less than 100 is ignored
	PageSize int
	//Limit used limit the number of documents
	Limit int
	//Snashopt ($snapshot) operator prevents the cursor from returning a document more than
	//once because an intervening write operation results in a move of the document.
	Snapshot bool
	//SortBy list of field names to sort the result
	SortBy []string
}

IteratorConfig defines different iterator config to load the document interator

type MongoTail

type MongoTail struct {
	EventHandler TailEventHandler
	ReImport     bool
}

MongoTail handles MongoDB tailing event coordination and also update destination dbs

func (MongoTail) Start

func (mt MongoTail) Start(dbSession *DbSession)

Start - starts tailing mongodb oplog.

type Q

type Q map[string]interface{}

Q query representation to hide bson.M type to single file

type TailEvent

type TailEvent struct {
	ID         interface{}
	Collection string
	Data       map[string]interface{}
}

TailEvent defines oplog tail event

type TailEventHandler

type TailEventHandler interface {
	HandleInsertEvent(event TailEvent)
	HandleUpdateEvent(event TailEvent)
	HandleDeleteEvent(event TailEvent)
	HandleDropEvent(event TailEvent)
	HandleError(err error)
}

TailEventHandler interface for handling tail event

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL