mdb

package
v0.13.2 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2023 License: MIT Imports: 15 Imported by: 0

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

View Source
const AccessTestDBname = "db-test"

Variables

View Source
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
)
View Source
var ErrNoDbName = errors.New("no database name")

Functions

func IDfilter added in v0.12.0

func IDfilter(id primitive.ObjectID) bson.D

IDfilter function returns a Mongo filter object for the specified ObjectID.

func IsDuplicate added in v0.9.0

func IsDuplicate(err error) bool

IsDuplicate checks to see if the specified error is for attempting to create a duplicate document.

func IsNotFound added in v0.9.0

func IsNotFound(err error) bool

IsNotFound checks an error condition to see if it matches the underlying database "not found" error.

func IsValidationFailure added in v0.9.0

func IsValidationFailure(err error) bool

IsValidationFailure checks to see if the specified error is for a validation failure.

func NoFilter added in v0.9.0

func NoFilter() bson.D

NoFilter returns an empty bson.D object for use as an empty filter.

Types

type Access

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

Access encapsulates database connection.

func Connect

func Connect(dbName string, config *Config) (*Access, error)

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

func ConnectOrPanic(dbName string, config *Config) *Access

ConnectOrPanic connects to Mongo DB and returns Access object or panics on error.

func (*Access) Client

func (a *Access) Client() *mongo.Client

Client returns the Mongo client object.

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

func (a *Access) CollectionExists(name string) (bool, error)

CollectionExists checks to see if a specific collection already exists.

func (*Access) Context

func (a *Access) Context() context.Context

Context returns the base context for the object.

func (*Access) ContextWithTimeout

func (a *Access) ContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

ContextWithTimeout returns the base context for the object with the specified timeout.

func (*Access) Database

func (a *Access) Database() *mongo.Database

Database returns the Mongo database object.

func (*Access) Disconnect

func (a *Access) Disconnect() error

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

func (*Access) Info

func (a *Access) Info(msg string)

Info prints a simple message in the format MDB: <msg>. This is used for a few calls within the Access code. It may be overridden to use another logger or to block these messages.

func (*Access) Ping

func (a *Access) Ping() error

Ping executes a ping against the Mongo server. This is separated from Connect() so that it can be overridden if necessary.

type AccessTestSuite added in v0.7.1

type AccessTestSuite struct {
	suite.Suite
	// contains filtered or unexported fields
}

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) Drop added in v0.10.0

func (c *Collection) Drop() error

Drop 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

func (c *Collection) StringValuesFor(field string, filter bson.D) ([]string, error)

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

type Identifier interface {
	ID() primitive.ObjectID
	IDfilter() bson.D
}

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

type Identity struct {
	ObjectID primitive.ObjectID `bson:"_id,omitempty"`
}

Identity instantiates the Identifier interface.

func (*Identity) ID added in v0.10.0

func (idm *Identity) ID() primitive.ObjectID

ID returns the primitive Mongo ObjectID for an item.

func (*Identity) IDfilter added in v0.10.0

func (idm *Identity) IDfilter() bson.D

IDfilter method returns a Mongo filter object for the item's ID.

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.

func (*TypedCollection[T]) Iterate added in v0.8.0

func (c *TypedCollection[T]) Iterate(filter bson.D, fn func(item *T) error) error

Iterate over a set of items, applying the specified function to each one.

Jump to

Keyboard shortcuts

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