database

package
v5.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2021 License: Apache-2.0 Imports: 8 Imported by: 2

README

Database

A set of interface wrappers for Go's MongoDB driver

Usage

Usage is just like using the Mongo driver. The biggest difference is that instead of each object being a struct you will work with interfaces by the same name. This allow you to mock and test your code. Here is a small example usage.

package main

import (
	"github.com/app-nerds/kit/database"
	"github.com/globalsign/mgo/bson"
)

func main() {
	var err error
	var session database.Session
	var testData []string

	if session, err = database.Dial("localhost:27017"); err != nil {
		panic(err)
	}

	db := session.DB("mydatabase")
	defer session.Close()

	collection := db.C("collection")

	if err = collection.Find(bson.M{}).All(&testData); err != nil {
		panic(err)
	}
}

Testing

This package provides a full set of mock structs that allow you to mock your database interactions for unit testing. Below is an example.

package example_test

import (
	"reflect"
	"testing"

	"pkg/example"
	"github.com/app-nerds/kit/database"
)

func TestSomeFunc(t *testing.T) {
	allCalled := false
	findCalled := false

	expected := []string{
		"value 1",
		"value 2",
	}

	mock := &database.CollectionMock{
		FindFunc: func(query interface{}) database.Query {
			findCalled = true

			return &database.QueryMock{
				AllFunc: func(result interface{}) error {
					allCalled = true
					database.WriteToResultInterface([]string{"value 1", "value 2"})
					return nil
				},
			}
		},
	}

	component := example.Example{
		Collection: mock,
	}

	actual, err := component.SomeMethod()

	if err != nil {
		t.Errorf("Expected err to be nil")
	}

	if !allCalled {
		t.Errorf("Expected All() to be called")
	}

	if !findCalled {
		t.Errorf("Expected Find() to be called")
	}

	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expected %+v to be %+v", actual, expected)
	}
}

License

MIT License

Copyright (c) 2019 App Nerds LLC

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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WriteToResultInterface

func WriteToResultInterface(value, result interface{}) error

Types

type Collection

type Collection interface {
	Count() (int, error)
	DropAllIndexes() error
	DropCollection() error
	DropIndex(key ...string) error
	DropIndexName(name string) error
	EnsureIndex(index mgo.Index) error
	EnsureIndexKey(key ...string) error
	Find(query interface{}) Query
	FindWithPaging(query interface{}, skip, limit int) (Query, int, error)
	FindId(id interface{}) Query
	Indexes() ([]mgo.Index, error)
	Insert(docs ...interface{}) error
	Remove(selector interface{}) error
	RemoveAll(selector interface{}) (*mgo.ChangeInfo, error)
	RemoveId(id interface{}) error
	Update(selector interface{}, update interface{}) error
	UpdateAll(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)
	UpdateId(id interface{}, update interface{}) error
	Upsert(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)
	UpsertId(id interface{}, update interface{}) (*mgo.ChangeInfo, error)
}

Collection is an interface to access to the collection struct.

type CollectionMock

type CollectionMock struct {
	CountFunc          func() (int, error)
	DropAllIndexesFunc func() error
	DropCollectionFunc func() error
	DropIndexFunc      func(key ...string) error
	DropIndexNameFunc  func(name string) error
	EnsureIndexFunc    func(index mgo.Index) error
	EnsureIndexKeyFunc func(key ...string) error
	FindFunc           func(query interface{}) Query
	FindIdFunc         func(id interface{}) Query
	FindWithPagingFunc func(query interface{}, skip, limit int) (Query, int, error)
	IndexesFunc        func() ([]mgo.Index, error)
	InsertFunc         func(docs ...interface{}) error
	RemoveFunc         func(selector interface{}) error
	RemoveAllFunc      func(selector interface{}) (*mgo.ChangeInfo, error)
	RemoveIdFunc       func(id interface{}) error
	UpdateFunc         func(selector interface{}, update interface{}) error
	UpdateAllFunc      func(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)
	UpdateIdFunc       func(id interface{}, update interface{}) error
	UpsertFunc         func(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)
	UpsertIdFunc       func(id interface{}, update interface{}) (*mgo.ChangeInfo, error)
}

func (*CollectionMock) Count

func (c *CollectionMock) Count() (int, error)

func (*CollectionMock) DropAllIndexes

func (c *CollectionMock) DropAllIndexes() error

func (*CollectionMock) DropCollection

func (c *CollectionMock) DropCollection() error

func (*CollectionMock) DropIndex

func (c *CollectionMock) DropIndex(key ...string) error

func (*CollectionMock) DropIndexName

func (c *CollectionMock) DropIndexName(name string) error

func (*CollectionMock) EnsureIndex

func (c *CollectionMock) EnsureIndex(index mgo.Index) error

func (*CollectionMock) EnsureIndexKey

func (c *CollectionMock) EnsureIndexKey(key ...string) error

func (*CollectionMock) Find

func (c *CollectionMock) Find(query interface{}) Query

func (*CollectionMock) FindId

func (c *CollectionMock) FindId(id interface{}) Query

func (*CollectionMock) FindWithPaging

func (c *CollectionMock) FindWithPaging(query interface{}, skip, limit int) (Query, int, error)

func (*CollectionMock) Indexes

func (c *CollectionMock) Indexes() ([]mgo.Index, error)

func (*CollectionMock) Insert

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

func (*CollectionMock) Remove

func (c *CollectionMock) Remove(selector interface{}) error

func (*CollectionMock) RemoveAll

func (c *CollectionMock) RemoveAll(selector interface{}) (*mgo.ChangeInfo, error)

func (*CollectionMock) RemoveId

func (c *CollectionMock) RemoveId(id interface{}) error

func (*CollectionMock) Update

func (c *CollectionMock) Update(selector interface{}, update interface{}) error

func (*CollectionMock) UpdateAll

func (c *CollectionMock) UpdateAll(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)

func (*CollectionMock) UpdateId

func (c *CollectionMock) UpdateId(id interface{}, update interface{}) error

func (*CollectionMock) Upsert

func (c *CollectionMock) Upsert(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)

func (*CollectionMock) UpsertId

func (c *CollectionMock) UpsertId(id interface{}, update interface{}) (*mgo.ChangeInfo, error)

type Database

type Database interface {
	C(name string) Collection
	GridFS(prefix string) GridFS
}

DataLayer is an interface to access to the database struct.

type DatabaseMock

type DatabaseMock struct {
	CFunc      func(name string) Collection
	GridFSFunc func(prefix string) GridFS
}

func (*DatabaseMock) C

func (d *DatabaseMock) C(name string) Collection

func (*DatabaseMock) GridFS

func (d *DatabaseMock) GridFS(prefix string) GridFS

type DatabaseUploadResponse

type DatabaseUploadResponse struct {
	BytesWritten int           `json:"bytesWritten"`
	FileID       bson.ObjectId `json:"fileID"`
	FileName     string        `json:"fileName"`
	Height       int           `json:"height"`
	Width        int           `json:"width"`
}

A DatabaseUploadResponse is used to alert a caller information about their uploaded file.

type DatabaseUploader

type DatabaseUploader interface {
	Upload(reader io.Reader, name, path string) (*DatabaseUploadResponse, error)
}

A DatabaseUploader defines an interface for uploading files to a database

type GridFS

type GridFS interface {
	Create(name string) (GridFile, error)
	Find(query interface{}) Query
	Open(name string) (GridFile, error)
	OpenId(id interface{}) (GridFile, error)
	Remove(name string) (err error)
	RemoveId(id interface{}) error
}

GridFS stores files in a MongoDB database

type GridFSMock

type GridFSMock struct {
	CreateFunc   func(name string) (GridFile, error)
	FindFunc     func(query interface{}) Query
	OpenFunc     func(name string) (GridFile, error)
	OpenIdFunc   func(id interface{}) (GridFile, error)
	RemoveFunc   func(name string) (err error)
	RemoveIdFunc func(id interface{}) error
}

func (*GridFSMock) Create

func (g *GridFSMock) Create(name string) (GridFile, error)

func (*GridFSMock) Find

func (g *GridFSMock) Find(query interface{}) Query

func (*GridFSMock) Open

func (g *GridFSMock) Open(name string) (GridFile, error)

func (*GridFSMock) OpenId

func (g *GridFSMock) OpenId(id interface{}) (GridFile, error)

func (*GridFSMock) Remove

func (g *GridFSMock) Remove(name string) (err error)

func (*GridFSMock) RemoveId

func (g *GridFSMock) RemoveId(id interface{}) error

type GridFile

type GridFile interface {
	Abort()
	Close() error
	ContentType() string
	GetMeta(result interface{}) error
	Id() interface{}
	MD5() string
	Name() string
	Read(b []byte) (int, error)
	Seek(offset int64, whence int) (int64, error)
	SetChunkSize(bytes int)
	SetContentType(ctype string)
	SetId(id interface{})
	SetMeta(metadata interface{})
	SetName(name string)
	SetUploadDate(t time.Time)
	Size() int64
	Write(data []byte) (int, error)
}

GridFile represents a single file in GridFS

type GridFileMock

type GridFileMock struct {
	AbortFunc          func()
	CloseFunc          func() error
	ContentTypeFunc    func() string
	GetMetaFunc        func(result interface{}) error
	IdFunc             func() interface{}
	MD5Func            func() string
	NameFunc           func() string
	ReadFunc           func(b []byte) (int, error)
	SeekFunc           func(offset int64, whence int) (int64, error)
	SetChunkSizeFunc   func(bytes int)
	SetContentTypeFunc func(ctype string)
	SetIdFunc          func(id interface{})
	SetMetaFunc        func(metadata interface{})
	SetNameFunc        func(name string)
	SetUploadDateFunc  func(t time.Time)
	SizeFunc           func() int64
	WriteFunc          func(data []byte) (int, error)
}

func (*GridFileMock) Abort

func (g *GridFileMock) Abort()

func (*GridFileMock) Close

func (g *GridFileMock) Close() error

func (*GridFileMock) ContentType

func (g *GridFileMock) ContentType() string

func (*GridFileMock) GetMeta

func (g *GridFileMock) GetMeta(result interface{}) error

func (*GridFileMock) Id

func (g *GridFileMock) Id() interface{}

func (*GridFileMock) MD5

func (g *GridFileMock) MD5() string

func (*GridFileMock) Name

func (g *GridFileMock) Name() string

func (*GridFileMock) Read

func (g *GridFileMock) Read(b []byte) (int, error)

func (*GridFileMock) Seek

func (g *GridFileMock) Seek(offset int64, whence int) (int64, error)

func (*GridFileMock) SetChunkSize

func (g *GridFileMock) SetChunkSize(bytes int)

func (*GridFileMock) SetContentType

func (g *GridFileMock) SetContentType(ctype string)

func (*GridFileMock) SetId

func (g *GridFileMock) SetId(id interface{})

func (*GridFileMock) SetMeta

func (g *GridFileMock) SetMeta(metadata interface{})

func (*GridFileMock) SetName

func (g *GridFileMock) SetName(name string)

func (*GridFileMock) SetUploadDate

func (g *GridFileMock) SetUploadDate(t time.Time)

func (*GridFileMock) Size

func (g *GridFileMock) Size() int64

func (*GridFileMock) Write

func (g *GridFileMock) Write(data []byte) (int, error)

type Iter

type Iter interface {
	All(result interface{}) error
	Close() error
	Done() bool
	Err() error
	For(result interface{}, f func() error) error
	Next(result interface{}) bool
	State() (int64, []bson.Raw)
	Timeout() bool
}

type IterMock

type IterMock struct {
	AllFunc     func(result interface{}) error
	CloseFunc   func() error
	DoneFunc    func() bool
	ErrFunc     func() error
	ForFunc     func(result interface{}, f func() error) error
	NextFunc    func(result interface{}) bool
	StateFunc   func() (int64, []bson.Raw)
	TimeoutFunc func() bool
}

func (*IterMock) All

func (i *IterMock) All(result interface{}) error

func (*IterMock) Close

func (i *IterMock) Close() error

func (*IterMock) Done

func (i *IterMock) Done() bool

func (*IterMock) Err

func (i *IterMock) Err() error

func (*IterMock) For

func (i *IterMock) For(result interface{}, f func() error) error

func (*IterMock) Next

func (i *IterMock) Next(result interface{}) bool

func (*IterMock) State

func (i *IterMock) State() (int64, []bson.Raw)

func (*IterMock) Timeout

func (i *IterMock) Timeout() bool

type MongoCollection

type MongoCollection struct {
	*mgo.Collection
}

MongoCollection wraps a mgo.Collection to embed methods in models.

func (*MongoCollection) Count

func (c *MongoCollection) Count() (int, error)

func (*MongoCollection) DropAllIndexes

func (c *MongoCollection) DropAllIndexes() error

func (*MongoCollection) DropCollection

func (c *MongoCollection) DropCollection() error

func (*MongoCollection) DropIndex

func (c *MongoCollection) DropIndex(key ...string) error

func (*MongoCollection) DropIndexName

func (c *MongoCollection) DropIndexName(name string) error

func (*MongoCollection) EnsureIndex

func (c *MongoCollection) EnsureIndex(index mgo.Index) error

func (*MongoCollection) EnsureIndexKey

func (c *MongoCollection) EnsureIndexKey(key ...string) error

func (*MongoCollection) Find

func (c *MongoCollection) Find(query interface{}) Query

Find shadows *mgo.Collection to returns a Query interface instead of *mgo.Query.

func (*MongoCollection) FindId

func (c *MongoCollection) FindId(id interface{}) Query

func (*MongoCollection) FindWithPaging

func (c *MongoCollection) FindWithPaging(query interface{}, skip, limit int) (Query, int, error)

func (*MongoCollection) Indexes

func (c *MongoCollection) Indexes() ([]mgo.Index, error)

func (*MongoCollection) Insert

func (c *MongoCollection) Insert(docs ...interface{}) error

func (*MongoCollection) Remove

func (c *MongoCollection) Remove(selector interface{}) error

func (*MongoCollection) RemoveAll

func (c *MongoCollection) RemoveAll(selector interface{}) (*mgo.ChangeInfo, error)

func (*MongoCollection) RemoveId

func (c *MongoCollection) RemoveId(id interface{}) error

func (*MongoCollection) Update

func (c *MongoCollection) Update(selector interface{}, update interface{}) error

func (*MongoCollection) UpdateAll

func (c *MongoCollection) UpdateAll(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)

func (*MongoCollection) UpdateId

func (c *MongoCollection) UpdateId(id interface{}, update interface{}) error

func (*MongoCollection) Upsert

func (c *MongoCollection) Upsert(selector interface{}, update interface{}) (*mgo.ChangeInfo, error)

func (*MongoCollection) UpsertId

func (c *MongoCollection) UpsertId(id interface{}, update interface{}) (*mgo.ChangeInfo, error)

type MongoDatabase

type MongoDatabase struct {
	*mgo.Database
}

MongoDatabase wraps a mgo.Database to embed methods in models.

func (MongoDatabase) C

func (d MongoDatabase) C(name string) Collection

C shadows *mgo.DB to returns a DataLayer interface instead of *mgo.Database.

func (MongoDatabase) GridFS

func (d MongoDatabase) GridFS(prefix string) GridFS

type MongoGridFS

type MongoGridFS struct {
	*mgo.GridFS
}

MongoGridFS is the wrapper around GridFS

func (*MongoGridFS) Create

func (gfs *MongoGridFS) Create(name string) (GridFile, error)

Create makes a new GridFS storage

func (*MongoGridFS) Find

func (gfs *MongoGridFS) Find(query interface{}) Query

Find queries GridFS

func (*MongoGridFS) Open

func (gfs *MongoGridFS) Open(name string) (GridFile, error)

Open opens a grid file

func (*MongoGridFS) OpenId

func (gfs *MongoGridFS) OpenId(id interface{}) (GridFile, error)

func (*MongoGridFS) Remove

func (gfs *MongoGridFS) Remove(name string) error

func (*MongoGridFS) RemoveId

func (gfs *MongoGridFS) RemoveId(id interface{}) error

type MongoGridFile

type MongoGridFile struct {
	*mgo.GridFile
}

func (*MongoGridFile) Abort

func (mgf *MongoGridFile) Abort()

func (*MongoGridFile) Close

func (mgf *MongoGridFile) Close() error

func (*MongoGridFile) ContentType

func (mgf *MongoGridFile) ContentType() string

func (*MongoGridFile) GetMeta

func (mgf *MongoGridFile) GetMeta(result interface{}) error

func (*MongoGridFile) Id

func (mgf *MongoGridFile) Id() interface{}

func (*MongoGridFile) MD5

func (mgf *MongoGridFile) MD5() string

func (*MongoGridFile) Name

func (mgf *MongoGridFile) Name() string

func (*MongoGridFile) Read

func (mgf *MongoGridFile) Read(b []byte) (int, error)

func (*MongoGridFile) Seek

func (mgf *MongoGridFile) Seek(offset int64, whence int) (int64, error)

func (*MongoGridFile) SetChunkSize

func (mgf *MongoGridFile) SetChunkSize(bytes int)

func (*MongoGridFile) SetContentType

func (mgf *MongoGridFile) SetContentType(ctype string)

func (*MongoGridFile) SetId

func (mgf *MongoGridFile) SetId(id interface{})

func (*MongoGridFile) SetMeta

func (mgf *MongoGridFile) SetMeta(metadata interface{})

func (*MongoGridFile) SetName

func (mgf *MongoGridFile) SetName(name string)

func (*MongoGridFile) SetUploadDate

func (mgf *MongoGridFile) SetUploadDate(t time.Time)

func (*MongoGridFile) Size

func (mgf *MongoGridFile) Size() int64

func (*MongoGridFile) Write

func (mgf *MongoGridFile) Write(data []byte) (int, error)

type MongoIter

type MongoIter struct {
	*mgo.Iter
}

func (*MongoIter) All

func (iter *MongoIter) All(result interface{}) error

func (*MongoIter) Close

func (iter *MongoIter) Close() error

func (*MongoIter) Done

func (iter *MongoIter) Done() bool

func (*MongoIter) Err

func (iter *MongoIter) Err() error

func (*MongoIter) For

func (iter *MongoIter) For(result interface{}, f func() error) error

func (*MongoIter) Next

func (iter *MongoIter) Next(result interface{}) bool

func (*MongoIter) State

func (iter *MongoIter) State() (int64, []bson.Raw)

func (*MongoIter) Timeout

func (iter *MongoIter) Timeout() bool

type MongoQuery

type MongoQuery struct {
	*mgo.Query
}

MongoQuery wraps a mgo.Query to embed methods in models.

func (*MongoQuery) All

func (q *MongoQuery) All(result interface{}) error

func (*MongoQuery) Count

func (q *MongoQuery) Count() (int, error)

func (*MongoQuery) Distinct

func (q *MongoQuery) Distinct(key string, result interface{}) error

func (*MongoQuery) Limit

func (q *MongoQuery) Limit(n int) Query

func (*MongoQuery) One

func (q *MongoQuery) One(result interface{}) error

func (*MongoQuery) Select

func (q *MongoQuery) Select(selector interface{}) Query

func (*MongoQuery) Skip

func (q *MongoQuery) Skip(n int) Query

func (*MongoQuery) Sort

func (q *MongoQuery) Sort(fields ...string) Query

type MongoSession

type MongoSession struct {
	*mgo.Session
}

MongoSession is currently a Mongo session.

func (MongoSession) DB

func (s MongoSession) DB(name string) Database

DB shadows *mgo.DB to returns a DataLayer interface instead of *mgo.Database.

type MongoUploader

type MongoUploader struct {
	DB Database
}

A MongoUploader uploads files to a MongoDB database. This struct satisfies the DatabaseUploader interface

func (*MongoUploader) Upload

func (u *MongoUploader) Upload(reader io.Reader, name, path string) (*DatabaseUploadResponse, error)

Upload uploads a file into the MongoDB GridFS system

type Query

type Query interface {
	All(result interface{}) error
	Count() (int, error)
	Distinct(key string, result interface{}) error
	Limit(n int) Query
	One(result interface{}) (err error)
	Select(selector interface{}) Query
	Skip(n int) Query
	Sort(fields ...string) Query
}

Query is an interface to access to the database struct

type QueryMock

type QueryMock struct {
	AllFunc      func(result interface{}) error
	CountFunc    func() (int, error)
	DistinctFunc func(key string, result interface{}) error
	LimitFunc    func(n int) Query
	OneFunc      func(result interface{}) error
	SelectFunc   func(selector interface{}) Query
	SkipFunc     func(n int) Query
	SortFunc     func(fields ...string) Query
}

func (*QueryMock) All

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

func (*QueryMock) Count

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

func (*QueryMock) Distinct

func (q *QueryMock) Distinct(key string, result interface{}) error

func (*QueryMock) Limit

func (q *QueryMock) Limit(n int) Query

func (*QueryMock) One

func (q *QueryMock) One(result interface{}) error

func (*QueryMock) Select

func (q *QueryMock) Select(selector interface{}) Query

func (*QueryMock) Skip

func (q *QueryMock) Skip(n int) Query

func (*QueryMock) Sort

func (q *QueryMock) Sort(fields ...string) Query

type Session

type Session interface {
	DB(name string) Database
	Close()
}

Session is an interface to access to the Session struct.

func Dial

func Dial(url string) (Session, error)

Dial establishes a new session to one or more Mongo databases

type SessionMock

type SessionMock struct {
	DBFunc    func(name string) Database
	CloseFunc func()
}

func (*SessionMock) Close

func (s *SessionMock) Close()

func (*SessionMock) DB

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

Jump to

Keyboard shortcuts

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