Movatterモバイル変換


[0]ホーム

URL:


Notice  The highest tagged major version isv2.

mongoifc

packagemodule
v1.17.3Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2025 License:MITImports:10Imported by:5

Details

Repository

github.com/sv-tools/mongoifc

Links

README

mongoifc

Code AnalysisGo ReferencecodecovGitHub tag (latest SemVer)OpenSSF Best PracticesOpenSSF Scorecard

The Interfaces for the MongoDB driver

Versioning Policy

Themongoifc code is stabilized, so now the version will match the version of the MongoDB driver sincev1.8.0.

In case of need for bug fixes inmongoifc, the version will be in this formatv1.8.1+N, wherev1.8.1 is theversion of MongoDB driver andN is a patch ofmongoifc. The new version for changes in README.md, tests, examples,GitHub workflows is not required.

Important

It is not a simple drop in replacement because of the limitations in Go. You should rewrite your code to use thislibrary instead of mongo driver.

conn := mongoifc.Connect(...)

instead of

conn := mongo.Connect(...)

or if you have a special code that returns the mongo object then you need to use one ofWrap functions to wrapthemongo.Client ormongo.Database ormongo.Collection ormongo.Session objects:

orig := mongo.Connect(...)...conn := mongoifc.WrapClient(orig)

or

func GetTenantDB(ctx context.Context, tenantID, dbName string) (*mongo.Database, error) {// a code that returns a special database for a given tenant and database name}...orig, err := GetTenantDB(ctx, tenant, "users")if err != nil {...}db = mongoifc.WrapDatabase(orig)

Now let's dig a bit into the limitations. Assume that you have a function to return a list of admin users, and yourewrote it usingmongoifc:

package users// Original: func GetAdmins(ctx context.Context, db *mongo.Database) ([]*User, error)func GetAdmins(ctx context.Context, db mongoifc.Database) ([]User, error) {var users []Usercur, err := db.Collection(UsersCollection).Find(ctx, User{Active:  true,IsAdmin: true,})if err != nil {return nil, err}if err := cur.All(ctx, &users); err != nil {return nil, err}return users, err}

and if you pass an object of*mongo.Database type instead ofmongoifc.Database

conn, _ := mongo.Connect(context.Background(), ...)db := conn.Database(...)users.GetAdmins(context.Background(), db)

then compilation fails with such error:

 cannot use db (type *mongo.Database) as type mongoifc.Database in argument to simple.GetAdmins:     *mongo.Database does not implement mongoifc.Database (wrong type for Aggregate method)         have Aggregate(context.Context, interface {}, ...*"go.mongodb.org/mongo-driver/mongo/options".AggregateOptions) (*mongo.Cursor, error)         want Aggregate(context.Context, interface {}, ...*"go.mongodb.org/mongo-driver/mongo/options".AggregateOptions) (mongoifc.Cursor, error)

This is the main reason of wrapping the original objects and using themongoifc instead.

Wrapped Interfaces

Mocks

Themocks folder contains the mocks generated bymockeryandgomock tools.

The examples of how to use the mocks can be found in theexamples folder or check any of the*_test.go files aswell.

Simple Example

user workflow
  1. Create 4 users, with two admins, usingInsertMany function.
  2. Get the admin users only usingFind function
  3. Delete all users usingDeleteMany function
  • users.go is a file with a set of functions, like:
    • Create to create the users usingInsertMany
    • Delete to delete the users by given IDs
    • GetAdmins to return the list of admin users
  • users_test.go is a file withTestUsersWorkflow unit tests:
    • mockery tests the workflow usingmockery mocks
    • gomock tests the workflow usinggomock mocks
    • docker tests the workflow using real mongo database run by docker
collection workflow
  1. Create a collection with random name.
  2. Check that the collection exists.
  3. Check that another collection does not exist.
  4. Drop collection.
  5. Check that the original collection does not exist.
  • collections.go is a file with a set of functions, like:
    • CreateCollection to create a collection usingCreateCollection
    • DropCollection to delete a collection by given name
    • CollectionExists to check that a collection exists
  • collections_test.go is a file withTestCollectionsWorkflow unit tests:
    • mockery tests the workflow usingmockery mocks
    • gomock tests the workflow usinggomock mocks
    • docker tests the workflow using real mongo database run by docker

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcUnWrapClientadded inv1.0.0

func UnWrapClient(clClient) *mongo.Client

UnWrapClient returns original mongo.Client

funcUnWrapCollectionadded inv1.8.2

func UnWrapCollection(coCollection) *mongo.Collection

UnWrapCollection returns original mongo.Collection

funcUnWrapDatabaseadded inv1.8.2

func UnWrapDatabase(dbDatabase) *mongo.Database

UnWrapDatabase returns original mongo.Database

funcUnWrapSessionadded inv1.8.2

func UnWrapSession(ssSession)mongo.Session

UnWrapSession returns original mongo.Session

funcWithSession

func WithSession(ctxcontext.Context, sessSession, fn func(scSessionContext)error)error

WithSession is a wrapper for `mongo.WithSession` function to call then `mongo.WithSession` functionDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#WithSession

Types

typeChangeStream

type ChangeStream interface {Current()bson.RawClose(ctxcontext.Context)errorDecode(val interface{})errorErr()errorID()int64Next(ctxcontext.Context)boolResumeToken()bson.RawSetBatchSize(sizeint32)TryNext(ctxcontext.Context)bool}

ChangeStream is an interface for `mongo.ChangeStream` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ChangeStream

typeClient

type Client interface {Connect(ctxcontext.Context)errorDatabase(namestring, opts ...*options.DatabaseOptions)DatabaseDisconnect(ctxcontext.Context)errorListDatabaseNames(ctxcontext.Context,filter interface{},opts ...*options.ListDatabasesOptions,) ([]string,error)ListDatabases(ctxcontext.Context,filter interface{},opts ...*options.ListDatabasesOptions,) (mongo.ListDatabasesResult,error)NumberSessionsInProgress()intPing(ctxcontext.Context, rp *readpref.ReadPref)errorStartSession(opts ...*options.SessionOptions) (Session,error)Timeout() *time.DurationUseSession(ctxcontext.Context,fn func(scSessionContext)error,)errorUseSessionWithOptions(ctxcontext.Context,opts *options.SessionOptions,fn func(scSessionContext)error,)errorWatch(ctxcontext.Context,pipeline interface{},opts ...*options.ChangeStreamOptions,) (ChangeStream,error)}

Client is an interface for `mongo.Client` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Client

funcConnect

func Connect(ctxcontext.Context, opts ...*options.ClientOptions) (Client,error)

Connect is a wrapper for `mongo.Connect` function to return the object as `Client` interfaceDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Connect

funcNewClientdeprecated

func NewClient(opts ...*options.ClientOptions) (Client,error)

NewClient is a wrapper for `mongo.NewClient` function to return the object as `Client` interfaceDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewClient

Deprecated: UseConnect instead.

funcWrapClient

func WrapClient(cl *mongo.Client)Client

WrapClient returns an instance of Client interface for given mongo.Client object

typeClientEncryptionadded inv1.13.0

type ClientEncryption interface {AddKeyAltName(ctxcontext.Context,idprimitive.Binary,keyAltNamestring,)SingleResultClose(ctxcontext.Context)errorCreateDataKey(ctxcontext.Context,kmsProviderstring,opts ...*options.DataKeyOptions,) (primitive.Binary,error)CreateEncryptedCollection(ctxcontext.Context,dbDatabase,collstring,createOpts *options.CreateCollectionOptions,kmsProviderstring,masterKey interface{},) (Collection,bson.M,error)Decrypt(ctxcontext.Context, valprimitive.Binary) (bson.RawValue,error)DeleteKey(ctxcontext.Context, idprimitive.Binary) (*mongo.DeleteResult,error)Encrypt(ctxcontext.Context,valbson.RawValue,opts ...*options.EncryptOptions,) (primitive.Binary,error)EncryptExpression(ctxcontext.Context,expr interface{},result interface{},opts ...*options.EncryptOptions,)errorGetKey(ctxcontext.Context, idprimitive.Binary)SingleResultGetKeyByAltName(ctxcontext.Context, keyAltNamestring)SingleResultGetKeys(ctxcontext.Context) (Cursor,error)RemoveKeyAltName(ctxcontext.Context,idprimitive.Binary,keyAltNamestring,)SingleResultRewrapManyDataKey(ctxcontext.Context,filter interface{},opts ...*options.RewrapManyDataKeyOptions,) (*mongo.RewrapManyDataKeyResult,error)}

ClientEncryption is an interface for `mongo.ClientEncryption` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ClientEncryption

funcNewClientEncryptionadded inv1.13.0

func NewClientEncryption(keyVaultClientClient, opts ...*options.ClientEncryptionOptions) (ClientEncryption,error)

typeCollection

type Collection interface {Aggregate(ctxcontext.Context, pipeline interface{}, opts ...*options.AggregateOptions) (Cursor,error)BulkWrite(ctxcontext.Context,models []mongo.WriteModel,opts ...*options.BulkWriteOptions,) (*mongo.BulkWriteResult,error)Clone(opts ...*options.CollectionOptions) (Collection,error)CountDocuments(ctxcontext.Context, filter interface{}, opts ...*options.CountOptions) (int64,error)Database()DatabaseDeleteMany(ctxcontext.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult,error)DeleteOne(ctxcontext.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult,error)Distinct(ctxcontext.Context,fieldNamestring,filter interface{},opts ...*options.DistinctOptions,) ([]interface{},error)Drop(ctxcontext.Context)errorEstimatedDocumentCount(ctxcontext.Context, opts ...*options.EstimatedDocumentCountOptions) (int64,error)Find(ctxcontext.Context, filter interface{}, opts ...*options.FindOptions) (Cursor,error)FindOne(ctxcontext.Context, filter interface{}, opts ...*options.FindOneOptions)SingleResultFindOneAndDelete(ctxcontext.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions)SingleResultFindOneAndReplace(ctxcontext.Context,filter interface{},replacement interface{},opts ...*options.FindOneAndReplaceOptions,)SingleResultFindOneAndUpdate(ctxcontext.Context,filter interface{},update interface{},opts ...*options.FindOneAndUpdateOptions,)SingleResultIndexes()IndexViewInsertMany(ctxcontext.Context,documents []interface{},opts ...*options.InsertManyOptions,) (*mongo.InsertManyResult,error)InsertOne(ctxcontext.Context,document interface{},opts ...*options.InsertOneOptions,) (*mongo.InsertOneResult,error)Name()stringReplaceOne(ctxcontext.Context,filter interface{},replacement interface{},opts ...*options.ReplaceOptions,) (*mongo.UpdateResult,error)SearchIndexes()SearchIndexViewUpdateByID(ctxcontext.Context,id interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)UpdateMany(ctxcontext.Context,filter interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)UpdateOne(ctxcontext.Context,filter interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)Watch(ctxcontext.Context, pipeline interface{}, opts ...*options.ChangeStreamOptions) (ChangeStream,error)}

Collection is an interface for `mongo.Collection` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Collection

funcWrapCollectionadded inv1.8.2

func WrapCollection(co *mongo.Collection)Collection

WrapCollection returns an instance of Collection interface for given mongo.Collection object

typeCursor

type Cursor interface {Current()bson.RawAll(ctxcontext.Context, results interface{})errorClose(ctxcontext.Context)errorDecode(val interface{})errorErr()errorID()int64Next(ctxcontext.Context)boolRemainingBatchLength()intSetBatchSize(batchSizeint32)SetComment(comment interface{})SetMaxTime(durtime.Duration)TryNext(ctxcontext.Context)bool}

Cursor is an interface for `mongo.Cursor` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Cursor

funcNewCursorFromDocumentsadded inv1.9.0

func NewCursorFromDocuments(documents []interface{}, errerror, registry *bsoncodec.Registry) (Cursor,error)

NewCursorFromDocuments is a wrapper for NewCursorFromDocuments function of the mongodb to return Cursorhttps://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewCursorFromDocuments

typeDatabase

type Database interface {Aggregate(ctxcontext.Context, pipeline interface{}, opts ...*options.AggregateOptions) (Cursor,error)Client()ClientCollection(namestring, opts ...*options.CollectionOptions)CollectionCreateCollection(ctxcontext.Context, namestring, opts ...*options.CreateCollectionOptions)errorCreateView(ctxcontext.Context,viewName, viewOnstring,pipeline interface{},opts ...*options.CreateViewOptions,)errorDrop(ctxcontext.Context)errorListCollectionNames(ctxcontext.Context,filter interface{},opts ...*options.ListCollectionsOptions,) ([]string,error)ListCollectionSpecifications(ctxcontext.Context,filter interface{},opts ...*options.ListCollectionsOptions,) ([]*mongo.CollectionSpecification,error)ListCollections(ctxcontext.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (Cursor,error)Name()stringReadConcern() *readconcern.ReadConcernReadPreference() *readpref.ReadPrefRunCommand(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions)SingleResultRunCommandCursor(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (Cursor,error)Watch(ctxcontext.Context,pipeline interface{},opts ...*options.ChangeStreamOptions,) (ChangeStream,error)WriteConcern() *writeconcern.WriteConcern}

Database is an interface for `mongo.Database` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Database

funcWrapDatabaseadded inv1.8.2

func WrapDatabase(db *mongo.Database)Database

WrapDatabase returns an instance of Database interface for given mongo.Database object

typeIndexView

type IndexView interface {CreateMany(ctxcontext.Context, models []mongo.IndexModel, opts ...*options.CreateIndexesOptions) ([]string,error)CreateOne(ctxcontext.Context, modelmongo.IndexModel, opts ...*options.CreateIndexesOptions) (string,error)DropAll(ctxcontext.Context, opts ...*options.DropIndexesOptions) (bson.Raw,error)DropOne(ctxcontext.Context, namestring, opts ...*options.DropIndexesOptions) (bson.Raw,error)DropOneWithKey(ctxcontext.Context,keySpecDocument interface{},opts ...*options.DropIndexesOptions,) (bson.Raw,error)List(ctxcontext.Context, opts ...*options.ListIndexesOptions) (Cursor,error)ListSpecifications(ctxcontext.Context, opts ...*options.ListIndexesOptions) ([]*mongo.IndexSpecification,error)}

IndexView is an interface for `mongo.IndexView` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#IndexView

typeSearchIndexViewadded inv1.13.0

type SearchIndexView interface {CreateMany(ctxcontext.Context,models []mongo.SearchIndexModel,opts ...*options.CreateSearchIndexesOptions,) ([]string,error)CreateOne(ctxcontext.Context,modelmongo.SearchIndexModel,opts ...*options.CreateSearchIndexesOptions,) (string,error)DropOne(ctxcontext.Context,namestring,opts ...*options.DropSearchIndexOptions,)errorList(ctxcontext.Context,searchIdxOpts *options.SearchIndexesOptions,opts ...*options.ListSearchIndexesOptions,) (Cursor,error)UpdateOne(ctxcontext.Context,namestring,definition interface{},opts ...*options.UpdateSearchIndexOptions,)error}

SearchIndexView is an interface for `mongo.SearchIndexView` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SearchIndexView

typeSession

type Session interface {StartTransaction(opts ...*options.TransactionOptions)errorAbortTransaction(ctxcontext.Context)errorCommitTransaction(ctxcontext.Context)errorWithTransaction(ctxcontext.Context,fn func(scSessionContext) (interface{},error),opts ...*options.TransactionOptions,) (interface{},error)EndSession(ctxcontext.Context)ClusterTime()bson.RawOperationTime() *primitive.TimestampClient()ClientID()bson.RawAdvanceClusterTime(bson.Raw)errorAdvanceOperationTime(*primitive.Timestamp)error}

Session is an interface for `mongo.Session` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Session

funcSessionFromContextadded inv1.10.1

func SessionFromContext(ctxcontext.Context)Session

SessionFromContext for `mongo.SessionFromContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SessionFromContext

funcWrapSessionadded inv1.8.2

func WrapSession(ssmongo.Session)Session

WrapSession returns an instance of Session interface for given mongo.Session object

typeSessionContextadded inv1.0.0

type SessionContext interface {context.ContextSession}

SessionContext is an interface emulates `mongo.SessionContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SessionContext

funcNewSessionContextadded inv1.10.1

func NewSessionContext(ctxcontext.Context, sessSession)SessionContext

NewSessionContext is wrapper for `mongo.NewSessionContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewSessionContext

typeSingleResult

type SingleResult interface {Decode(v interface{})errorDecodeBytes() (bson.Raw,error)Err()errorRaw() (bson.Raw,error)}

SingleResult is an interface for `mongo.SingleResult` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SingleResult

funcNewSingleResultFromDocumentadded inv1.9.0

func NewSingleResultFromDocument(document interface{}, errerror, registry *bsoncodec.Registry)SingleResult

NewSingleResultFromDocument is a wrapper for NewSingleResultFromDocument function of the mongodbto return SingleResulthttps://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewSingleResultFromDocument

Source Files

View all Source files

Directories

PathSynopsis
examples
mocks
gomock
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp