Documentation
¶
Overview ¶
Package mdb provides infrastructure for using Mongo from Go.
This README file was generated using github.com/robertkrimen/godocdown
Use the Connect() function to connect to the DB and return an Access object. The Access object provides access to the Mongo DB and some common functionality. The dbName is required for Connect(), an optional pointer to an Config struct can be used to provide additional parameters for connecting to the DB. If these are not provided they are filled in from various default global variables which are visible and may be changed.
The Access object provides a Disconnect() method suitable for use with defer.
In addition, the Access object can be used to construct collections. The Collection() call takes a collection name, an optional validation JSON string, and optional list of "finisher" functions intended to create indices or otherwise configure the collection after it is created. The Index() call is used to add an index to a collection.
The CachedCollection object provides a caching layer for mostly static tables. Implementing the various provided interfaces in table record objects allows them to be created, deleted, and found by the CachedCollection object.
The AccessTestSuite struct is provided to wrap database connect/disconnect for use in tests that actually hit the database. The use of 'go:build database' separates these so that they are only run when using 'go test -tags database', without this tag only unit tests are run.
The IndexTester supports verifying that a specific index has been added to a collection.
Index ¶
- Constants
- Variables
- func IDfilter(id primitive.ObjectID) bson.D
- func IsDuplicate(err error) bool
- func IsNotFound(err error) bool
- func IsValidationFailure(err error) bool
- func NoFilter() bson.D
- type Access
- func (a *Access) Client() *mongo.Client
- func (a *Access) CollectionConnect(collection *Collection, definition *CollectionDefinition) error
- func (a *Access) CollectionExists(name string) (bool, error)
- func (a *Access) Context() context.Context
- func (a *Access) ContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)
- func (a *Access) Database() *mongo.Database
- func (a *Access) Disconnect() error
- func (a *Access) DisconnectOrPanic()
- func (a *Access) Index(collection *Collection, description *IndexDescription) error
- func (a *Access) Info(msg string)
- func (a *Access) Ping() error
- type AccessTestSuite
- func (suite *AccessTestSuite) Access() *Access
- func (suite *AccessTestSuite) ConnectCollection(definition *CollectionDefinition, indexDescriptions ...*IndexDescription) *Collection
- func (suite *AccessTestSuite) SetupSuite()
- func (suite *AccessTestSuite) SetupSuiteConfig(config *Config)
- func (suite *AccessTestSuite) TearDownSuite()
- type Collection
- func (c *Collection) ContextWithTimeout() (context.Context, context.CancelFunc)
- func (c *Collection) Count(filter bson.D) (int64, error)
- func (c *Collection) Create(item interface{}) error
- func (c *Collection) Delete(filter bson.D, idempotent bool) error
- func (c *Collection) DeleteAll() error
- func (c *Collection) Drop() error
- func (c *Collection) Find(filter bson.D) (interface{}, error)
- func (c *Collection) FindOrCreate(filter bson.D, item interface{}) (interface{}, error)
- func (c *Collection) Iterate(filter bson.D, fn func(item interface{}) error) error
- func (c *Collection) Replace(filter, item interface{}, opts ...*options.UpdateOptions) error
- func (c *Collection) StringValuesFor(field string, filter bson.D) ([]string, error)
- func (c *Collection) Update(filter, changes interface{}, opts ...*options.UpdateOptions) error
- type CollectionDefinition
- type CollectionFinisher
- type Config
- type Identifier
- type Identity
- type IndexDescription
- type IndexTester
- type Timeout
- type TypedCollection
Constants ¶
const AccessTestDBname = "db-test"
Variables ¶
var ( // DefaultURI is the default connection URI if not provided in Config.Options. DefaultURI = "mongodb://localhost:27017" // DefaultLogInfoFn is the default info logging function. DefaultLogInfoFn = func(msg string) { fmt.Printf("MDB: %s\n", msg) } // DefaultConnectTimeout is the default timeout for the initial connect. DefaultConnectTimeout = 10 * time.Second // DefaultDisconnectTimeout is the default timeout for the disconnect. DefaultDisconnectTimeout = 10 * time.Second // DefaultPingTimeout is the default timeout for the ping to make sure the connection is up. DefaultPingTimeout = 2 * time.Second // DefaultCollectionTimeout is the default timeout for collection access. DefaultCollectionTimeout = time.Second // DefaultIndexTimeout is the default timeout for index access. DefaultIndexTimeout = 5 * time.Second )
var ErrNoDbName = errors.New("no database name")
Functions ¶
func IDfilter ¶ added in v0.12.0
IDfilter function returns a Mongo filter object for the specified ObjectID.
func IsDuplicate ¶ added in v0.9.0
IsDuplicate checks to see if the specified error is for attempting to create a duplicate document.
func IsNotFound ¶ added in v0.9.0
IsNotFound checks an error condition to see if it matches the underlying database "not found" error.
func IsValidationFailure ¶ added in v0.9.0
IsValidationFailure checks to see if the specified error is for a validation failure.
Types ¶
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access encapsulates database connection.
func Connect ¶
Connect to Mongo DB and return Access object. If the ctxt is nil it will be provided as context.Background(). If the url is empty it will be set to mdb.DefaultURI.
func ConnectOrPanic ¶
ConnectOrPanic connects to Mongo DB and returns Access object or panics on error.
func (*Access) CollectionConnect ¶ added in v0.10.0
func (a *Access) CollectionConnect(collection *Collection, definition *CollectionDefinition) error
CollectionConnect configures a Collection object per the collection definition. If the collection does not exist it will be created for use.
func (*Access) CollectionExists ¶
CollectionExists checks to see if a specific collection already exists.
func (*Access) ContextWithTimeout ¶
ContextWithTimeout returns the base context for the object with the specified timeout.
func (*Access) Disconnect ¶
Disconnect Mongo DB client. Provided for use in defer statements.
func (*Access) DisconnectOrPanic ¶
func (a *Access) DisconnectOrPanic()
DisconnectOrPanic disconnects the Mongo DB client or panics on error. Provided for use in defer statements.
func (*Access) Index ¶
func (a *Access) Index(collection *Collection, description *IndexDescription) error
type AccessTestSuite ¶ added in v0.7.1
func (*AccessTestSuite) Access ¶ added in v0.7.1
func (suite *AccessTestSuite) Access() *Access
func (*AccessTestSuite) ConnectCollection ¶ added in v0.13.1
func (suite *AccessTestSuite) ConnectCollection( definition *CollectionDefinition, indexDescriptions ...*IndexDescription) *Collection
ConnectCollection connects to the specified collection and adds any provided indexes as necessary in a SetupSuite() with test checks so that any errors blow up the test.
func (*AccessTestSuite) SetupSuite ¶ added in v0.7.1
func (suite *AccessTestSuite) SetupSuite()
func (*AccessTestSuite) SetupSuiteConfig ¶ added in v0.7.1
func (suite *AccessTestSuite) SetupSuiteConfig(config *Config)
func (*AccessTestSuite) TearDownSuite ¶ added in v0.7.1
func (suite *AccessTestSuite) TearDownSuite()
type Collection ¶ added in v0.1.6
type Collection struct { *Access *mongo.Collection // contains filtered or unexported fields }
func ConnectCollection ¶ added in v0.10.0
func ConnectCollection(access *Access, definition *CollectionDefinition) (*Collection, error)
ConnectCollection creates a new collection object with the specified collection definition.
func (*Collection) ContextWithTimeout ¶ added in v0.10.0
func (c *Collection) ContextWithTimeout() (context.Context, context.CancelFunc)
func (*Collection) Count ¶ added in v0.8.0
func (c *Collection) Count(filter bson.D) (int64, error)
Count documents in collection matching filter.
func (*Collection) Create ¶ added in v0.8.0
func (c *Collection) Create(item interface{}) error
Create item in DB.
func (*Collection) Delete ¶ added in v0.8.0
func (c *Collection) Delete(filter bson.D, idempotent bool) error
Delete item from DB. Set idempotent to true to avoid errors if the item does not exist.
func (*Collection) DeleteAll ¶ added in v0.8.0
func (c *Collection) DeleteAll() error
DeleteAll items from this collection.
func (*Collection) Find ¶ added in v0.8.0
func (c *Collection) Find(filter bson.D) (interface{}, error)
Find an item in the database and return it as a blank interface. The result will likely contain bson objects.
func (*Collection) FindOrCreate ¶ added in v0.9.0
func (c *Collection) FindOrCreate(filter bson.D, item interface{}) (interface{}, error)
FindOrCreate returns an existing object or creates it if it does not already exist. The filter must correctly find the object as a second Find is done after any necessary creation.
func (*Collection) Iterate ¶ added in v0.8.0
func (c *Collection) Iterate(filter bson.D, fn func(item interface{}) error) error
Iterate over a set of items, applying the specified function to each one. The items passed to the function will likely contain bson objects.
func (*Collection) Replace ¶ added in v0.10.0
func (c *Collection) Replace(filter, item interface{}, opts ...*options.UpdateOptions) error
Replace entire item referenced by filter with specified item. If the filter matches more than one document mongo-go-driver will choose one to update.
func (*Collection) StringValuesFor ¶ added in v0.1.6
StringValuesFor returns an array of distinct string values for the specified filter and field.
func (*Collection) Update ¶ added in v0.10.0
func (c *Collection) Update(filter, changes interface{}, opts ...*options.UpdateOptions) error
Update item referenced by filter by applying update operator expressions. If the filter matches more than one document mongo-go-driver will choose one to update.
type CollectionDefinition ¶ added in v0.10.0
type CollectionDefinition struct { // Name of collection. Name string // Options used if collection already exists. ConnectOptions []*options.CollectionOptions // Options used to create collection. CreateOptions []*options.CreateCollectionOptions // Convenience field to specify validation data as JSON // which will be decoded and added to CreateOptions. ValidationJSON string // Collection Finishers are run after creation of a collection. // Finishers support mechanism such as index creation. Finishers []CollectionFinisher }
CollectionDefinition contains the definitions necessary for a Collection.
type CollectionFinisher ¶
type CollectionFinisher func(access *Access, collection *Collection) error
CollectionFinisher provides a way to add special processing when creating a collection.
type Config ¶
type Config struct { // Base context for use in calls to Mongo. Ctx context.Context // Mongo options. Options *options.ClientOptions // Optional BSON codec registry for handling special types. Registry *bsoncodec.Registry // Logging function for information messages may be overridden. LogInfoFn func(msg string) Timeout }
Config items for Mongo DB connection.
type Identifier ¶ added in v0.10.0
Identifier provides an interface to items that use the primitive Mongo ObjectID. When embedding this always use:
mdb.Identifier `bson:"inline"`
type Identity ¶ added in v0.10.0
Identity instantiates the Identifier interface.
type IndexDescription ¶
type IndexDescription struct {
// contains filtered or unexported fields
}
func NewIndexDescription ¶
func NewIndexDescription(unique bool, keys ...string) *IndexDescription
NewIndexDescription creates a new index description.
func (*IndexDescription) AsBSON ¶
func (id *IndexDescription) AsBSON() bson.D
func (*IndexDescription) Finisher ¶ added in v0.1.2
func (id *IndexDescription) Finisher() CollectionFinisher
Finisher returns a function that can be used as a CollectionFinisher for creating this index.
type IndexTester ¶
type IndexTester []indexDatum
IndexTester provides a utility for verifying index creation.
func NewIndexTester ¶
func NewIndexTester() IndexTester
func (IndexTester) TestIndexes ¶
func (it IndexTester) TestIndexes(t *testing.T, collection *Collection, descriptions ...*IndexDescription)
type Timeout ¶
type Timeout struct { // Timeout for the initial connect. Connect time.Duration // Timeout for the disconnect. Disconnect time.Duration // Timeout for the ping to make sure the connection is up. Ping time.Duration // Timeout for collection access. Collection time.Duration // Timeout for indexes. Index time.Duration }
Timeout settings for Mongo DB access.
type TypedCollection ¶ added in v0.8.0
type TypedCollection[T any] struct { Collection }
TypedCollection uses reflection to properly create objects returned from Mongo.
func ConnectTypedCollection ¶ added in v0.10.0
func ConnectTypedCollection[T any](access *Access, definition *CollectionDefinition) (*TypedCollection[T], error)
ConnectTypedCollection creates a new typed collection object with the specified collection definition.
func ConnectTypedCollectionHelper ¶ added in v0.13.1
func ConnectTypedCollectionHelper[T any]( suite *AccessTestSuite, definition *CollectionDefinition, indexDescriptions ...*IndexDescription) *TypedCollection[T]
ConnectTypedCollectionHelper is similar to AccessTestSuite.ConnectionCollection(). Go doesn't support generic methods so this can't be a method on AccessTestSuite.
func (*TypedCollection[T]) Find ¶ added in v0.8.0
func (c *TypedCollection[T]) Find(filter bson.D) (*T, error)
Find an item in the database. Will return an interface to an item of the collection's type.
func (*TypedCollection[T]) FindOrCreate ¶ added in v0.9.0
func (c *TypedCollection[T]) FindOrCreate(filter bson.D, item *T) (*T, error)
FindOrCreate returns an existing cacheable object or creates it if it does not already exist.