mgo

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2019 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DialMaxRetries defines the maximum amount of retries to attempt when dialing to a
	// connection to a mongodb instance
	DialMaxRetries = 3

	// DialRetrySleep defines the sleep time between retries when dialing for a connection to a mongodb instance.
	DialRetrySleep = 10 * time.Second

	// DialTimeout indicates the max time to wait before aborting a dialing attempt.
	DialTimeout = 10 * time.Second
)
View Source
var (
	// ErrNotFound is the error returned when no results are found in a mongo operation.
	ErrNotFound = mgo.ErrNotFound

	// ErrCursor is the error returned when the cursor used in a mongo operation is not valid.
	ErrCursor = mgo.ErrCursor
)

Functions

func AddTlsHandler added in v1.0.5

func AddTlsHandler(dialInfo *mgo.DialInfo, cert []byte, insecureSkipVerify bool)

AddTlsHandler adds the TLS handling logic to a provided `*mgo.DialInfo`

{dialInfo}            - The DialInfo to use
{cert}                - The PEM bytes of the CA cert to use for TLS
{insecureSkipVerify}  - Controls whether a client verifies the server's certificate chain and
                        host name. If 'true', TLS accepts any certificate presented by the
                        server and any host name in that certificate. In this mode, TLS is
                        susceptible to man-in-the-middle attacks.  This should be used only
                        for testing.

func IsDup

func IsDup(err error) bool

IsDup returns whether err informs of a duplicate key error because a primary key index or a secondary unique index already has an entry with the given value.

func ParseURL added in v1.0.5

func ParseURL(url string) (*mgo.DialInfo, error)

ParseURL parses a MongoDB URL as accepted by the Dial function and returns a value suitable for providing into DialWithInfo.

See Dial for more details on the format of url.

func SetLogger added in v1.0.3

func SetLogger(logger log.ILogger)

Types

type BulkResult

type BulkResult struct {
	Matched  int
	Modified int
}

BulkResult See the BulkResult documentation in `gopkg.in/mgo.v2` for more information.

type Change

type Change struct {
	Update    interface{} // The update document
	Upsert    bool        // Whether to insert in case the document isn't found
	Remove    bool        // Whether to remove the document found rather than updating
	ReturnNew bool        // Should the modified document be returned rather than the old one
}

Change See the Change documentation in `gopkg.in/mgo.v2` for more information.

type ChangeInfo

type ChangeInfo struct {
	Updated    int
	Removed    int         // Number of documents removed
	Matched    int         // Number of documents matched but not necessarily changed
	UpsertedId interface{} // Upserted _id field, when not explicitly provided
}

ChangeInfo See the ChangeInfo documentation in `gopkg.in/mgo.v2` for more information.

type CollectionInfo

type CollectionInfo struct {
	DisableIdIndex   bool
	ForceIdIndex     bool
	Capped           bool
	MaxBytes         int
	MaxDocs          int
	Validator        interface{}
	ValidationLevel  string
	ValidationAction string
	StorageEngine    interface{}
}

CollectionInfo See the CollectionInfo documentation in `gopkg.in/mgo.v2` for more information.

type CollectionMock

type CollectionMock struct {
	ICollection
	// contains filtered or unexported fields
}

CollectionMock: Is the mock struct use for ICollection mocking.

func MockCollection

func MockCollection(col ...ICollection) *CollectionMock

MockCollection returns a new instance of ICollection for mocking purposes

{t}:    The instance of *testing.T used in the test
{col}:  An optional instance of ICollection to handle real calls if wanted.

func (*CollectionMock) Clear

func (m *CollectionMock) Clear(funcName string)

func (*CollectionMock) Find

func (m *CollectionMock) Find(query interface{}) IQuery

func (*CollectionMock) Insert

func (m *CollectionMock) Insert(docs ...interface{}) error

func (*CollectionMock) Times

func (m *CollectionMock) Times(funcName string) int

func (*CollectionMock) WhenFind

func (m *CollectionMock) WhenFind(query interface{}, output IQuery)

func (*CollectionMock) WhenInsert

func (m *CollectionMock) WhenInsert(docs interface{}, output error)

type DatabaseMock

type DatabaseMock struct {
	IDatabase
	// contains filtered or unexported fields
}

DatabaseMock is a mock of IDatabase

func MockDb

func MockDb(db ...IDatabase) *DatabaseMock

MockDb returns a new instance of IDatabase for mocking purposes

{db}:   An optional instance of IDatabase to handle real calls if wanted.

func (*DatabaseMock) C

func (m *DatabaseMock) C(collectionName string) ICollection

func (*DatabaseMock) Clear

func (m *DatabaseMock) Clear(funcName string)

func (*DatabaseMock) Run

func (m *DatabaseMock) Run(cmd interface{}, result interface{}) error

func (*DatabaseMock) Times

func (m *DatabaseMock) Times(funcName string) int

func (*DatabaseMock) WhenC

func (m *DatabaseMock) WhenC(colName string, output ICollection)

func (*DatabaseMock) WhenRun

func (m *DatabaseMock) WhenRun(cmd interface{}, output error)

type IBulk

type IBulk interface {
	// Unordered puts the bulk operation in unordered mode.
	//
	// In unordered mode the individual operations may be sent
	// out of order, which means latter operations may proceed
	// even if prior ones have failed.
	Unordered() IBulk

	// Insert queues up the provided documents for insertion.
	Insert(docs ...interface{}) IBulk

	// Remove queues up the provided selectors for removing matching documents.
	// Each selector will remove only a single matching document.
	Remove(selectors ...interface{}) IBulk

	// RemoveAll queues up the provided selectors for removing all matching documents.
	// Each selector will remove all matching documents.
	RemoveAll(selectors ...interface{}) IBulk

	// Update queues up the provided pairs of updating instructions.
	// The first element of each pair selects which documents must be
	// updated, and the second element defines how to update it.
	// Each pair matches exactly one document for updating at most.
	Update(pairs ...interface{}) IBulk

	// UpdateAll queues up the provided pairs of updating instructions.
	// The first element of each pair selects which documents must be
	// updated, and the second element defines how to update it.
	// Each pair updates all documents matching the selector.
	UpdateAll(pairs ...interface{}) IBulk

	// Upsert queues up the provided pairs of upserting instructions.
	// The first element of each pair selects which documents must be
	// updated, and the second element defines how to update it.
	// Each pair matches exactly one document for updating at most.
	Upsert(pairs ...interface{}) IBulk

	// Run runs all the operations queued up.
	//
	// If an error is reported on an unordered bulk operation, the error value may
	// be an aggregation of all issues observed. As an exception to that, Insert
	// operations running on MongoDB versions prior to 2.6 will report the last
	// error only due to a limitation in the wire protocol.
	Run() (*BulkResult, error)
}

IBulk is an interface which matches the contract for the `Bulk` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.Bulk` in the `gopkg.in/mgo.v2` package.

func NewBulk

func NewBulk(col ...ICollection) IBulk

NewBulk creates an instance of IBulk with the given ICollection if passed as an arg. Note: The IBulk instance returned will not work without a valid ICollection.

type ICollection

type ICollection interface {
	// Set of extension functions that are not present in the original `mgo` package are defined in the following interface(s):
	ICollectionExtensions

	// With returns a copy of c that uses Session s.
	With(s ISession) ICollection

	// EnsureIndexKey ensures an index with the given key exists, creating it
	EnsureIndexKey(key ...string) error

	// EnsureIndex ensures an index with the given key exists, creating it with
	EnsureIndex(index Index) error

	// DropIndex drops the index with the provided key from the c collection.
	DropIndex(key ...string) error

	// DropIndexName removes the index with the provided index name.
	DropIndexName(name string) error

	// Indexes returns a list of all indexes for the collection.
	Indexes() (indexes []Index, err error)

	// Find prepares a query using the provided document. The document may be a map or a struct value capable of being marshalled with bson. The map may be a generic one using
	// interface{} for its key and/or values, such as bson.M, or it may be a properly typed map.  roviding nil as the document is equivalent to providing an empty document such
	// as bson.M{}.
	Find(query interface{}) IQuery

	// Repair returns an iterator that goes over all recovered documents in the collection, in a best-effort manner. This is most useful when there are damaged data files. Multiple
	// copies of the same document may be returned by the iterator.
	Repair() IIter

	// FindId is a convenience helper equivalent to:
	FindId(id interface{}) IQuery

	// pipe prepares a pipeline to aggregate. The pipeline document must be a slice built in terms of the aggregation framework language.
	Pipe(pipeline interface{}) IPipe

	// NewIter returns a newly created iterator with the provided parameters. Using this method is not recommended unless the desired functionality is not yet exposed via a more
	// convenient interface (Find, pipe, etc).
	NewIter(session ISession, firstBatch []bson.Raw, cursorId int64, err error) IIter

	// Insert inserts one or more documents in the respective collection.  In case the Session is in safe mode (see the SetSafe method) and an error happens while inserting the
	// provided documents, the returned error will be of type *LastError.
	Insert(docs ...interface{}) error

	// Update finds a single document matching the provided selector document and modifies it according to the update document.
	Update(selector interface{}, update interface{}) error

	// UpdateId is a convenience helper equivalent to:
	UpdateId(id interface{}, update interface{}) error

	// UpdateAll finds all documents matching the provided selector document and modifies them according to the update document.
	UpdateAll(selector interface{}, update interface{}) (info *ChangeInfo, err error)

	// Upsert finds a single document matching the provided selector document and modifies it according to the update document.  If no document matching the selector is found, the
	// update document is applied to the selector document and the result is inserted in the collection.
	Upsert(selector interface{}, update interface{}) (info *ChangeInfo, err error)

	// UpsertId is a convenience helper equivalent to:
	UpsertId(id interface{}, update interface{}) (info *ChangeInfo, err error)

	// Remove finds a single document matching the provided selector document and removes it from the Database.
	Remove(selector interface{}) error

	// RemoveId is a convenience helper equivalent to:
	RemoveId(id interface{}) error

	// RemoveAll finds all documents matching the provided selector document and removes them from the Database.
	RemoveAll(selector interface{}) (info *ChangeInfo, err error)

	// DropCollection removes the entire collection including all of its documents.
	DropCollection() error

	// Create explicitly creates the c collection with details of info. MongoDB creates collections automatically on use, so this method is only necessary when creating collection
	// with non-default characteristics, such as capped collections.
	Create(info *CollectionInfo) error

	// Count returns the total number of documents in the collection.
	Count() (n int, err error)

	// Database returns the database the collection belongs to
	Database() IDatabase

	// Name returns the name of the collection ("collection")
	Name() string

	// FullName returns the full name of the collection ("db.collection")
	FullName() string

	// Bulk returns a value to prepare the execution of a bulk operation.
	Bulk() IBulk

	// C returns the internal mgo.collection used by this implementation.
	C() *mgo.Collection
}

ICollection is an interface which matches the contract for the `collection` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.collection` in the `gopkg.in/mgo.v2` package.

func NewCollection

func NewCollection(col ...*mgo.Collection) ICollection

NewCollection creates an instance of ICollection with the given *mgo.Collection if passed as an arg. Note: The ICollection instance returned will not work without a valid *mgo.Collection.

type ICollectionExtensions

type ICollectionExtensions interface {
	// MustEnsureIndex ensures an index with the given key exists, creating it with
	// the provided parameters if necessary.  If the index fails then this call
	// exists as a Fatal
	//
	//   {index} - the index in Bson form
	//
	MustEnsureIndex(index Index)

	// BulkUpsert allows multiple Upsert operations. Queues up the provided pairs of upserting instructions.
	// The first element of each pair selects which documents must be updated, and the second element defines how to update it.
	// Each pair matches exactly one document for updating at most.
	//
	// Enhanced to use bulk operations in the length of documents is more than the allowed 1000.
	BulkUpsert(pairs ...interface{}) (*BulkResult, error)
}

ICollectionExtensions encapsulates the new extended functions to the original ICollection

type IDatabase

type IDatabase interface {
	IDatabaseExtensions

	// C returns a value representing the named collection.
	C(name string) ICollection

	// With returns a copy of db that uses Session s.
	With(s ISession) IDatabase

	// GridFS returns a GridFS value representing collections in db that follow the standard GridFS specification.
	GridFS(prefix string) *mgo.GridFS

	// Run issues the provided command on the db Database and unmarshals its result in the respective argument. The cmd argument may be either a string with the command name itself,
	// in which case an empty document of the form bson.M{cmd: 1} will be used, or it may be a full command document.
	Run(cmd interface{}, result interface{}) error

	// Login authenticates with MongoDB using the provided credential. The authentication is valid for the whole Session and will stay valid until Logout is explicitly called for
	// the same Database, or the Session is closed.
	Login(user, pass string) error

	// Logout removes any established authentication credentials for the Database.
	Logout()

	// UpsertUser updates the authentication credentials and the roles for a MongoDB user within the db Database. If the named user doesn't exist it will be created.
	// This method should only be used from MongoDB 2.4 and on. For older MongoDB releases, use the obsolete AddUser method instead.
	UpsertUser(user *mgo.User) error

	// AddUser creates or updates the authentication credentials of user within the db Database.
	// WARNING: This method is obsolete and should only be used with MongoDB 2.2 or earlier. For MongoDB 2.4 and on, use UpsertUser instead.
	AddUser(username, password string, readOnly bool) error

	// RemoveUser removes the authentication credentials of user from the Database.
	RemoveUser(user string) error

	// DropDatabase removes the entire Database including all of its collections.
	DropDatabase() error

	// FindRef returns a query that looks for the document in the provided reference. If the reference includes the DB field, the document will be retrieved from the respective Database.
	FindRef(ref *mgo.DBRef) IQuery

	// CollectionNames returns the collection names present in the db Database.
	CollectionNames() (names []string, err error)

	// Name returns the name of the database
	Name() string

	// Session returns the session used by the database
	Session() ISession

	// Returns the internal mgo.Database used by this implementation.
	DB() *mgo.Database
}

IDatabase is an interface which matches the contract for the `Database` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.collection` in the `gopkg.in/mgo.v2` package.

func NewDatabase

func NewDatabase(db *mgo.Database) IDatabase

NewDatabase creates an instance of IDatabase with the given *mgo.Database if passed as an arg. Note: The IDatabase instance returned will not work without a valid *mgo.Database.

type IDatabaseExtensions

type IDatabaseExtensions interface {
	// MustEnsureIndex ensures an index with the given key exists, creating it with
	// the provided parameters if necessary.  If the index fails then this call
	// exists as a Fatal
	//
	// {index}      - the index in Bson form
	// {collection} - the name of the collection to apply the index to
	MustEnsureIndex(index Index, collection string)
}

IDatabaseExtensions encapsulates the new extended functions to the original IDatabase

type IIter

type IIter interface {
	// Err returns nil if no errors happened during iteration, or the actual
	// error otherwise.
	//     - See the Err documentation in `gopkg.in/mgo.v2` for more information.
	Err() error

	// Close kills the server cursor used by the iterator, if any, and returns
	// nil if no errors happened during iteration, or the actual error otherwise.
	//     - See the Close documentation in `gopkg.in/mgo.v2` for more information.
	Close() error

	// Done returns true only if a follow up Next call is guaranteed
	// to return false.
	//     - See the Done documentation in `gopkg.in/mgo.v2` for more information.
	Done() bool

	// Timeout returns true if Next returned false due to a timeout of
	// a tailable cursor. In those cases, Next may be called again to continue
	// the iteration at the previous cursor position.
	Timeout() bool

	// Next retrieves the next document from the result set, blocking if necessary.
	// This method will also automatically retrieve another batch of documents from
	// the server when the current one is exhausted, or before that in background
	// if pre-fetching is enabled (see the query.Prefetch and Session.SetPrefetch
	// methods).
	//     - See the Next documentation in `gopkg.in/mgo.v2` for more information.
	Next(result interface{}) bool

	// All retrieves all documents from the result set into the provided slice
	// and closes the iterator.
	//     - See the All documentation in `gopkg.in/mgo.v2` for more information.
	All(result interface{}) error

	// The For method is obsolete and will be removed in a future release.
	// See Iter as an elegant replacement.
	For(result interface{}, f func() error) (err error)
}

type IPipe

type IPipe interface {
	// Iter executes the pipeline and returns an iterator capable of going over all the generated results.
	Iter() IIter
	// All works like Iter.All.
	All(result interface{}) error
	// One executes the pipeline and unmarshals the first item from the result set into the result parameter.
	// It returns ErrNotFound if no items are generated by the pipeline.
	One(result interface{}) error
	// Explain returns a number of details about how the MongoDB server would execute the requested pipeline, such as the
	// number of objects examined, the number of times the read lock was yielded to allow writes to go in, and so on.
	//     - See the Tail documentation in `gopkg.in/mgo.v2` for more information.
	Explain(result interface{}) error
	// AllowDiskUse enables writing to the "<dbpath>/_tmp" server directory so
	// that aggregation pipelines exec not have to be held entirely in memory.
	AllowDiskUse() IPipe
	// Batch sets the batch size used when fetching documents from the database. It's possible to change this setting on a
	// per-session basis as well, using the Batch method of Session.
	//     - See the Tail documentation in `gopkg.in/mgo.v2` for more information.
	Batch(n int) IPipe
	// P returns the internal mgo.pipe used by this implementation.
	P() *mgo.Pipe
}

IPipe is an interface which matches the contract for the `Pipe` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.collection` in the `gopkg.in/mgo.v2` package.

func NewPipe

func NewPipe(p ...*mgo.Pipe) IPipe

NewPipe creates an instance of IPipe with the given *mgo.Pipe if passed as an arg. Note: The IPipe instance returned will not work without a valid *mgo.Pipe.

type IQuery

type IQuery interface {
	// Set of extension functions that are not present in the original `mgo` package are defined in the following interface(s):
	IQueryPageExtension

	// The default batch size is defined by the Database itself.  As of this writing, MongoDB will use an initial size of min(100 docs, 4MB) on the first batch, and 4MB on remaining ones.
	Batch(n int) IQuery

	// Prefetch sets the point at which the next batch of results will be requested. When there are p*batch_size remaining documents cached in an Iter, the next batch will be
	// requested in background. For instance, when using this:
	Prefetch(p float64) IQuery

	// Skip skips over the n initial documents from the query results. Note that this only makes sense with capped collections where documents are naturally ordered by insertion
	// time, or with sorted results.
	Skip(n int) IQuery

	// Limit restricts the maximum number of documents retrieved to n, and also changes the batch size to the same value.  Once n documents have been returned by Next, the following
	// call will return ErrNotFound.
	Limit(n int) IQuery

	// Select enables selecting which fields should be retrieved for the results found. For example, the following query would only retrieve the name field:
	Select(selector interface{}) IQuery

	// Sort asks the Database to order returned documents according to the provided field names. A field name may be prefixed by - (minus) for it to be sorted in reverse order.
	Sort(fields ...string) IQuery

	// Explain returns a number of details about how the MongoDB server would execute the requested query, such as the number of objects examined, the number of times the read lock
	// was yielded to allow writes to go in, and so on.
	Explain(result interface{}) error

	// Hint will include an explicit "hint" in the query to force the server to use a specified index, potentially improving performance in some situations. The provided parameters
	// are the fields that compose the key of the index to be used. For details on how the indexKey may be built, see the EnsureIndex method.
	Hint(indexKey ...string) IQuery

	// SetMaxScan constrains the query to stop after scanning the specified number of documents.
	SetMaxScan(n int) IQuery

	// SetMaxTime constrains the query to stop after running for the specified time. When the time limit is reached MongoDB automatically cancels the query.
	SetMaxTime(d time.Duration) IQuery

	// Snapshot will force the performed query to make use of an available index on the _id field to prevent the same document from being returned more than once in a single
	// iteration. This might happen without this setting in situations when the document changes in size and thus has to be moved while the iteration is running.
	Snapshot() IQuery

	// Comment adds a comment to the query to identify it in the Database profiler output.
	Comment(comment string) IQuery

	// LogReplay enables an option that optimizes queries that are typically made on the MongoDB oplog for replaying it. This is an internal implementation aspect and most likely
	// uninteresting for other uses. It has seen at least one use case, though, so it's exposed via the API.
	LogReplay() IQuery

	// One executes the query and unmarshals the first obtained document into the result argument. The result must be a struct or map value capable of being unmarshalled into by
	// gobson. This function blocks until either a result is available or an error happens.  For example:
	One(result interface{}) error

	// Iter executes the query and returns an iterator capable of going over all the results. Results will be returned in batches of configurable size (see the Batch method) and more
	// documents will be requested when a configurable number of documents is iterated over (see the Prefetch method).
	Iter() IIter

	// Tail returns a tailable iterator. Unlike a normal iterator, a tailable iterator may wait for new values to be inserted in the Collection once the end of the current result set
	// is reached, A tailable iterator may only be used with capped collections.
	//     - See the Tail documentation in `gopkg.in/mgo.v2` for more information.
	Tail(timeout time.Duration) IIter

	// All works like Iter.All.
	All(result interface{}) error

	// Count returns the total number of documents in the result set.
	Count() (n int, err error)

	// Distinct unmarshals into result the list of distinct values for the given key.
	Distinct(key string, result interface{}) error

	// MapReduce executes a map/reduce job for documents covered by the query. That kind of job is suitable for very flexible bulk aggregation of data performed at the server side
	// via Javascript functions.
	//     - See the MapReduce documentation in `gopkg.in/mgo.v2` for more information.
	MapReduce(job *MapReduce, result interface{}) (info *MapReduceInfo, err error)

	// Apply runs the findAndModify MongoDB command, which allows updating, upserting or removing a document matching a query and atomically returning either the old version (the
	// default) or the new version of the document (when ReturnNew is true). If no objects are found Apply returns ErrNotFound.
	//     - See the Apply documentation in `gopkg.in/mgo.v2` for more information.
	Apply(change Change, result interface{}) (info *ChangeInfo, err error)

	// Returns the internal mgo.query used by this implementation.
	Q() *mgo.Query
}

IQuery is an interface which matches the contract for the `query` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.Collection` in the `gopkg.in/mgo.v2` package.

func NewQuery

func NewQuery(q ...*mgo.Query) IQuery

NewQuery creates an instance of IQuery with the given *mgo.Query if passed as an arg. Note: The IQuery instance returned will not work without a valid *mgo.Query.

type IQueryPageExtension

type IQueryPageExtension interface {
	// Page adds to the query the information required to fetch the requested page of objects.
	Page(p ...*pages.Page) IQuery

	// WrapPage attempts to obtain the items in the requested page and wraps the result in *pages.Paginated
	WrapPage(result interface{}, p ...*pages.Page) (*pages.Paginated, error)
}

IQueryPageExtension encapsulates the new extended functions to the original IQuery

type ISession

type ISession interface {
	ISessionExtensions

	// LiveServers returns a list of server addresses which are currently known to be alive.
	LiveServers() (addrs []string)

	// DB returns a value representing the named Database. If name is empty, the Database name provided in the dialed URL is used instead. If that is also empty, "test" is used as a
	// fallback in a way equivalent to the mongo shell.
	DB(name string) IDatabase

	// Login authenticates with MongoDB using the provided credential. The authentication is valid for the whole Session and will stay valid until Logout is explicitly called for
	// the same Database, or the Session is closed.
	Login(cred *mgo.Credential) error

	// LogoutAll removes all established authentication credentials for the Session.
	LogoutAll()

	// ResetIndexCache() clears the cache of previously ensured indexes. Following requests to EnsureIndex will contact the server.
	ResetIndexCache()

	// New creates a new Session with the same parameters as the original Session, including consistency, batch size, prefetching, safety mode, etc. The returned Session will use
	// sockets from the pool, so there's a chance that writes just performed in another Session may not yet be visible.
	//
	// Login information from the original Session will not be copied over into the new Session unless it was provided through the initial URL for the Dial function.
	New() ISession

	// Copy works just like New, but preserves the exact authentication information from the original Session.
	Copy() ISession

	// Clone works just like Copy, but also reuses the same socket as the original Session, in case it had already reserved one due to its consistency guarantees. This behavior
	// ensures that writes performed in the old Session are necessarily observed when using the new Session, as long as it was a strong or monotonic Session. That said, it also
	// means that long operations may cause other goroutines using the original Session to wait.
	Clone() ISession

	// Close terminates the Session.  It's a runtime error to use a Session after it has been closed.
	Close()

	// Refresh puts back any reserved sockets in use and restarts the consistency guarantees according to the current consistency setting for the Session.
	Refresh()

	// SetMode changes the consistency mode for the Session. The default mode is Strong.
	//     - See the SetMode documentation in `gopkg.in/mgo.v2` for more information.
	SetMode(consistency mgo.Mode, refresh bool)

	// Mode returns the current consistency mode for the Session.
	Mode() mgo.Mode

	// SetSyncTimeout sets the amount of time an operation with this Session will wait before returning an error in case a connection to a usable server can't be established. Set it
	// to zero to wait forever. The default value is 7 seconds.
	SetSyncTimeout(d time.Duration)

	// SetSocketTimeout sets the amount of time to wait for a non-responding socket to the Database before it is forcefully closed. The default timeout is 1 minute.
	SetSocketTimeout(d time.Duration)

	// SetCursorTimeout changes the standard timeout period that the server enforces on created cursors. The only supported value right now is 0, which disables the timeout.
	// The standard server timeout is 10 minutes.
	SetCursorTimeout(d time.Duration)

	// SetPoolLimit sets the maximum number of sockets in use in a single server before this Session will block waiting for a socket to be available. The default limit is 4096.
	//     - See the SetPoolLimit documentation in `gopkg.in/mgo.v2` for more information.
	SetPoolLimit(limit int)

	// SetBypassValidation sets whether the server should bypass the registered validation expressions executed when documents are inserted or modified, in the interest of preserving
	// invariants in the collection being modified. The default is to not bypass, and thus to perform the validation expressions registered for modified collections.
	SetBypassValidation(bypass bool)

	// SetBatch sets the default batch size used when fetching documents from the Database. It's possible to change this setting on a per-query basis as well, using the query.Batch method.
	//     - See the SetBatch documentation in `gopkg.in/mgo.v2` for more information.
	SetBatch(n int)

	// SetPrefetch sets the default point at which the next batch of results will be requested. When there are p*batch_size remaining documents cached in an Iter, the next batch
	// will be requested in background. The default prefetch value is 0.25.
	SetPrefetch(p float64)

	// Safe returns the current safety mode for the Session.
	Safe() (safe *mgo.Safe)

	// SetSafe changes the Session safety mode.
	//     - See the SetSafe documentation in `gopkg.in/mgo.v2` for more information.
	SetSafe(safe *mgo.Safe)

	// EnsureSafe compares the provided safety parameters with the ones currently in use by the Session and picks the most conservative choice for each setting.
	//     - See the EnsureSafe documentation in `gopkg.in/mgo.v2` for more information.
	EnsureSafe(safe *mgo.Safe)

	// Run issues the provided command on the "admin" Database and and unmarshals its result in the respective argument. The cmd argument may be either a string with the command name
	// itself, in which case an empty document of the form bson.M{cmd: 1} will be used, or it may be a full command document.
	//     - See the Session.Run documentation in `gopkg.in/mgo.v2` for more information.
	Run(cmd interface{}, result interface{}) error

	// SelectServers restricts communication to servers configured with the given tags. For example, the following statement restricts servers used for reading operations to those
	// with both tag "disk" set to "ssd" and tag "rack" set to 1:
	//     - See the Session.SelectServers documentation in `gopkg.in/mgo.v2` for more information.
	SelectServers(tags ...bson.D)

	// Ping runs a trivial ping command just to get in touch with the server.
	Ping() error

	// Fsync flushes in-memory writes to disk on the server the Session is established with. If async is true, the call returns immediately, otherwise it returns after the flush has
	// been made.
	Fsync(async bool) error

	// FsyncLock locks all writes in the specific server the Session is established with and returns. Any writes attempted to the server after it is successfully locked will block
	// until FsyncUnlock is called for the same server.
	//     - See the Session.FsyncLock documentation in `gopkg.in/mgo.v2` for more information.
	FsyncLock() error

	// FsyncUnlock releases the server for writes. See FsyncLock for details.
	FsyncUnlock() error

	// FindRef returns a query that looks for the document in the provided reference. For a DBRef to be resolved correctly at the Session level it must necessarily have the optional
	// DB field defined.
	FindRef(ref *mgo.DBRef) IQuery

	// DatabaseNames returns the names of non-empty databases present in the cluster.
	DatabaseNames() (names []string, err error)

	// BuildInfo retrieves the version and other details about the running MongoDB server.
	BuildInfo() (info mgo.BuildInfo, err error)

	// Returns the internal mgo.Session used by this implementation.
	S() *mgo.Session
}

ISession is an interface which matches the contract for the `Session` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.collection` in the `gopkg.in/mgo.v2` package.

func Dial

func Dial(url string) (ISession, error)

Dial establishes a new session to the cluster identified by the given seed server(s). The session will enable communication with all of the servers in the cluster, so the seed servers are used only to find out about the cluster topology.

  • See mgo.Dial documentation in `gopkg.in/mgo.v2` for more information.

func DialWithInfo

func DialWithInfo(info *mgo.DialInfo) (ISession, error)

DialWithInfo establishes a new session to the cluster identified by info.

func DialWithTimeout

func DialWithTimeout(url string, timeout time.Duration) (ISession, error)

DialWithTimeout works like Dial, but uses timeout as the amount of time to wait for a server to respond when first connecting and also on follow up operations in the session. If timeout is zero, the call may block forever waiting for a connection to be made.

See SetSyncTimeout for customizing the timeout for the session.

func DialWithTls added in v1.0.4

func DialWithTls(url string, cert []byte, insecureSkipVerify ...bool) (ISession, error)

DialWithTls attempts to establish a MongoDB connection using TLS with the provided PEM encoded certificate.

{url}                 - The URL to dial to Mongo
{cert}                - The PEM bytes of the CA cert to use for TLS
{insecureSkipVerify}  - (optional) controls whether a client verifies the server's certificate
                        chain andhost name. If 'true', TLS accepts any certificate presented
                        by the server and any host name in that certificate. In this mode, TLS
                        is susceptible to man-in-the-middle attacks.  This should be used only
                        for testing.

func NewSession

func NewSession(s ...*mgo.Session) ISession

NewSession creates an instance of ISession with the given *mgo.Session if passed as an arg. Note: The ISession instance returned will not work without a valid *mgo.Session.

type ISessionExtensions

type ISessionExtensions interface {
	// SetDefaultSafe invokes SetSafe with the default safety instance.
	SetDefaultSafe()
}

ISessionExtensions encapsulates the new extended functions to the original ISession

type Index

type Index struct {
	Key              []string // Index key fields; prefix name with dash (-) for descending order
	Unique           bool     // Prevent two documents from having the same index key
	DropDups         bool     // Drop documents with the same index key as a previously indexed one
	Background       bool     // Build index in background and return immediately
	Sparse           bool     // Only index documents containing the Key fields
	ExpireAfter      time.Duration
	Name             string
	Min, Max         int
	Minf, Maxf       float64
	BucketSize       float64
	Bits             int
	DefaultLanguage  string
	LanguageOverride string
	Weights          map[string]int
	Collation        *mgo.Collation
}

Index See the Index documentation in `gopkg.in/mgo.v2` for more information.

type MapReduce

type MapReduce struct {
	Map      string      // Map Javascript function code (required)
	Reduce   string      // Reduce Javascript function code (required)
	Finalize string      // Finalize Javascript function code (optional)
	Out      interface{} // Output collection name or document. If nil, results are inlined into the result parameter.
	Scope    interface{} // Optional global scope for Javascript functions
	Verbose  bool
}

MapReduce See the MapReduce documentation in `gopkg.in/mgo.v2` for more information.

type MapReduceInfo

type MapReduceInfo struct {
	InputCount  int                // Number of documents mapped
	EmitCount   int                // Number of times reduce called emit
	OutputCount int                // Number of documents in resulting collection
	Database    string             // Output database, if results are not inlined
	Collection  string             // Output collection, if results are not inlined
	Time        int64              // Time to run the job, in nanoseconds
	VerboseTime *mgo.MapReduceTime // Only defined if Verbose was true
}

MapReduceInfo See the MapReduceInfo documentation in `gopkg.in/mgo.v2` for more information.

type MapReduceTime

type MapReduceTime struct {
	Total    int64 // Total time, in nanoseconds
	Map      int64 // Time within map function, in nanoseconds
	EmitLoop int64 // Time within the emit/map loop, in nanoseconds
}

MapReduceTime See the MapReduceTime documentation in `gopkg.in/mgo.v2` for more information.

type MockBase

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

func (*MockBase) BulkTimes

func (m *MockBase) BulkTimes(names []string, expected []int) error

BulkTimes same as 'Times', but verifies multiple function calls in one call.

func (*MockBase) Times

func (m *MockBase) Times(funcName string) int

Times asserts that the amount of times a function was invoked matches the provided 'expected'.

func (*MockBase) When

func (m *MockBase) When(funcName string, f testutils.WhenHandler)

When indicates what the expected behavior should be when a function is invoked.

func (*MockBase) WhenReturn

func (m *MockBase) WhenReturn(funcName string, retArgs ...interface{})

WhenReturn allows to set the return args without the need of a WhenHandler.

type QueryMock

type QueryMock struct {
	IQuery
	*MockBase
}

QueryMock is a mock implementation of IQuery

func MockQuery

func MockQuery(q ...IQuery) *QueryMock

MockQuery returns a new instance of IQuery for mocking purposes

{q}:   An optional instance of IQuery to handle real calls if wanted.

func (*QueryMock) All

func (m *QueryMock) All(result interface{}) error

func (*QueryMock) Count

func (m *QueryMock) Count() (int, error)

func (*QueryMock) Limit

func (m *QueryMock) Limit(n int) IQuery

func (*QueryMock) Page

func (m *QueryMock) Page(page ...*pages.Page) IQuery

func (*QueryMock) Skip

func (m *QueryMock) Skip(n int) IQuery

func (*QueryMock) Sort

func (m *QueryMock) Sort(fields ...string) IQuery

func (*QueryMock) WrapPage

func (m *QueryMock) WrapPage(result interface{}, page ...*pages.Page) (*pages.Paginated, error)

type SessionMock

type SessionMock struct {
	ISession
	*MockBase
}

QueryMock is a mock implementation of IQuery

func MockSession

func MockSession(q ...ISession) *SessionMock

MockSession returns a new instance of IQuery for mocking purposes

{q}:   An optional instance of IQuery to handle real calls if wanted.

func (*SessionMock) Clone

func (s *SessionMock) Clone() ISession

func (*SessionMock) Copy

func (s *SessionMock) Copy() ISession

func (*SessionMock) DB

func (s *SessionMock) DB(name string) IDatabase

func (*SessionMock) FindRef

func (s *SessionMock) FindRef(ref *mgo.DBRef) IQuery

func (*SessionMock) New

func (s *SessionMock) New() ISession

Jump to

Keyboard shortcuts

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