coal

package
v0.34.4 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2024 License: MIT Imports: 31 Imported by: 2

Documentation

Overview

Package coal provides a mini ORM for mongoDB.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidated = xo.BF("invalidated")

ErrInvalidated may be returned to the receiver if the underlying collection or database has been invalidated due to a drop or rename.

View Source
var ErrMetaMismatch = xo.BF("provided model does not match managed model")

ErrMetaMismatch is returned if the provided model does not match the model that is manged by the manager.

View Source
var ErrReadOnlyTransaction = xo.BF("read only transaction")

ErrReadOnlyTransaction is returned when performing writes under a read only transaction.

View Source
var ErrStop = xo.BF("stop")

ErrStop may be returned by a receiver to stop the stream.

View Source
var ErrTransactionRequired = xo.BF("operation requires a transaction")

ErrTransactionRequired is returned if an operation would be unsafe to perform without a transaction.

Functions

func AddIndex added in v0.33.0

func AddIndex(model Model, unique bool, expiry time.Duration, fields ...string)

AddIndex will add an index to the models index list. Fields that are prefixed with a dash will result in a descending key. Fields may be paths to nested item fields or begin wih a "#" (after prefix) to specify unknown fields.

func AddPartialIndex added in v0.33.0

func AddPartialIndex(model Model, unique bool, expiry time.Duration, fields []string, filter bson.M)

AddPartialIndex adds an index with a partial filter expression.

func Apply added in v0.34.0

func Apply(model Model, update bson.M, translate bool) error

Apply will apply the provided update document to the specified model. If requested the document is translated before applying.

Note: The update operator "$unset" will not work as expected on structs, because the fields will not be set to their zero values. Use the "$set" operator instead.

func Clean added in v0.34.0

func Clean(model Model)

Clean will clean the model by removing expired tags.

func EnsureArrayField added in v0.32.0

func EnsureArrayField(ctx context.Context, store *Store, model Model, rawArrayField, rawField, value string) (int64, int64, error)

EnsureArrayField will add the provided field to all array elements in documents that do not have the field already.

func EnsureField added in v0.32.0

func EnsureField(ctx context.Context, store *Store, model Model, rawField string, value interface{}) (int64, int64, error)

EnsureField will add the provided raw field to all documents that do not have the field already.

func EnsureIndexes added in v0.33.0

func EnsureIndexes(store *Store, models ...Model) error

EnsureIndexes will ensure that the registered indexes of the specified models exist. It may fail early if some indexes are already existing and do not match the registered indexes.

func Extend added in v0.34.1

func Extend(ext Extension)

Extend will register the provided extension and build and set the default BSON registry.

func F

func F(m Model, field string) string

F is a shorthand function to extract the BSON key of a model field. Use the "-" prefix for retrieving sort keys. Fields may be paths to nested item fields or begin wih a "#" (after prefix) to specify unknown fields.

Note: F will panic if no field has been found.

func FindEachAndReplace added in v0.32.0

func FindEachAndReplace(ctx context.Context, store *Store, model Model, filter bson.M, concurrency int, fn func(Model) error) (int64, int64, error)

FindEachAndReplace will apply the provided function to each matching document and replace it with the result. Documents are not validated during lookup.

func FindEachAndUpdate added in v0.32.0

func FindEachAndUpdate(ctx context.Context, store *Store, model Model, filter bson.M, concurrency int, fn func(Model) (bson.M, error)) (int64, int64, error)

FindEachAndUpdate will apply the provided function to each matching document and update it with the resulting document. Documents are not validated during lookup.

func HasTransaction added in v0.29.0

func HasTransaction(ctx context.Context) bool

HasTransaction will return whether the context carries a transaction.

func IsDuplicate added in v0.27.0

func IsDuplicate(err error) bool

IsDuplicate returns whether the provided error describes a duplicate document.

func IsHex added in v0.20.0

func IsHex(str string) bool

IsHex will assess whether the provided string is a valid hex encoded ID.

func IsMissing added in v0.27.0

func IsMissing(err error) bool

IsMissing returns whether the provided error describes a missing document.

func L added in v0.19.0

func L(m Model, flag string, force bool) string

L is a shorthand function to look up a flagged field of a model.

Note: L will panic if multiple flagged fields have been found or force is requested and no flagged field has been found.

func ProcessEach added in v0.32.0

func ProcessEach(ctx context.Context, store *Store, model Model, filter bson.M, concurrency int, fn func(Model) error) (int64, int64, error)

ProcessEach will find all documents and yield them to the provided function in parallel up to the specified amount of concurrency. Documents are not validated during lookup.

func RenameArrayFields added in v0.32.0

func RenameArrayFields(ctx context.Context, store *Store, model Model, rawArrayField string, rawOldAndNewFields map[string]string) (int64, int64, error)

RenameArrayFields will rename the specified array fields in all matching document arrays that have an element with at least on of the fields.

func RenameFields added in v0.32.0

func RenameFields(ctx context.Context, store *Store, model Model, rawOldToNewFields map[string]string) (int64, int64, error)

RenameFields will rename the fields in all documents where at least one old field exits.

func Require added in v0.19.0

func Require(m Model, flags ...string)

Require will check if the specified flags are set on the specified model and panic if one is missing.

func ReverseSort added in v0.32.0

func ReverseSort(sort []string) []string

ReverseSort is a helper function to revers a sort.

func Sort added in v0.20.0

func Sort(fields ...string) bson.D

Sort is a helper function to compute a sort object based on a list of fields with dash prefixes for descending sorting.

func T added in v0.17.0

func T(name string) string

T is a helper function to construct the BSON key for a tag.

func TE added in v0.34.0

func TE(name string) string

TE is a helper function to construct the BSON key for a tag expiry.

func TF added in v0.34.0

func TF(expired bool) bson.M

TF is a helper function to construct the BSON filter for a tag expiry. Only tags with a non-zero expiry can become expired.

func TV added in v0.34.0

func TV(name string) string

TV is a helper function to construct the BSON key for a tag value.

func UnsetArrayFields added in v0.32.0

func UnsetArrayFields(ctx context.Context, store *Store, model Model, rawArrayField string, rawFields ...string) (int64, int64, error)

UnsetArrayFields will unset the provided fields in all document arrays they exist.

func UnsetFields added in v0.32.0

func UnsetFields(ctx context.Context, store *Store, model Model, rawFields ...string) (int64, int64, error)

UnsetFields will unset the provided fields in all documents they exist.

func Verify added in v0.33.1

func Verify(models []Model, ignored ...string) error

Verify will verify a list of models to have fully connected relationships.

func Visualize added in v0.33.0

func Visualize(title, file string, models ...Model) error

Visualize writes a PDF document that visualizes the models and their relationships. The method expects the graphviz toolkit to be installed and accessible by the calling program.

func VisualizeDOT added in v0.33.0

func VisualizeDOT(title string, models ...Model) string

VisualizeDOT emits a string in DOT format which when rendered with graphviz visualizes the models and their relationships.

fdp -Tpdf models.dot > models.pdf

func VisualizePDF added in v0.33.0

func VisualizePDF(title string, models ...Model) ([]byte, error)

VisualizePDF returns a PDF document that visualizes the models and their relationships. The method expects the graphviz toolkit to be installed and accessible by the calling program.

Types

type Base

type Base struct {
	DocID ID             `json:"-" bson:"_id,omitempty"`
	Lock  int64          `json:"-" bson:"_lk,omitempty"`
	Token ID             `json:"-" bson:"_tk,omitempty"`
	Score float64        `json:"-" bson:"_sc,omitempty"`
	Tags  map[string]Tag `json:"-" bson:"_tg,omitempty"`
}

Base is the base for every coal model.

func B added in v0.26.1

func B(id ...ID) Base

B is a shorthand to construct a base with the provided ID or a generated ID if none specified.

func (*Base) GetAccessor added in v0.28.0

func (b *Base) GetAccessor(v interface{}) *stick.Accessor

GetAccessor implements the Model interface.

func (*Base) GetBase added in v0.26.1

func (b *Base) GetBase() *Base

GetBase implements the Model interface.

func (*Base) GetTag added in v0.34.0

func (b *Base) GetTag(name string) interface{}

GetTag will get the value for the specified tag.

func (*Base) ID

func (b *Base) ID() ID

ID implements the Model interface.

func (*Base) SetTag added in v0.34.0

func (b *Base) SetTag(name string, value interface{}, expiry time.Time)

SetTag will set the provided value for the specified tag.

type Collection added in v0.26.0

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

Collection mimics a collection and adds tracing.

func (*Collection) Aggregate added in v0.27.0

func (c *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Iterator, error)

Aggregate wraps the native Aggregate collection method and yields the returned cursor.

func (*Collection) BulkWrite added in v0.26.0

func (c *Collection) BulkWrite(ctx context.Context, models []mongo.WriteModel, opts ...*options.BulkWriteOptions) (*mongo.BulkWriteResult, error)

BulkWrite wraps the native BulkWrite collection method.

func (*Collection) CountDocuments added in v0.26.0

func (c *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)

CountDocuments wraps the native CountDocuments collection method.

func (*Collection) DeleteMany added in v0.26.0

func (c *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

DeleteMany wraps the native DeleteMany collection method.

func (*Collection) DeleteOne added in v0.26.0

func (c *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

DeleteOne wraps the native DeleteOne collection method.

func (*Collection) Distinct added in v0.26.0

func (c *Collection) Distinct(ctx context.Context, field string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error)

Distinct wraps the native Distinct collection method.

func (*Collection) EstimatedDocumentCount added in v0.26.0

func (c *Collection) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error)

EstimatedDocumentCount wraps the native EstimatedDocumentCount collection method.

func (*Collection) Find added in v0.27.0

func (c *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*Iterator, error)

Find wraps the native Find collection method and yields the returned cursor.

func (*Collection) FindOne added in v0.26.0

func (c *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) lungo.ISingleResult

FindOne wraps the native FindOne collection method.

func (*Collection) FindOneAndDelete added in v0.26.0

func (c *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) lungo.ISingleResult

FindOneAndDelete wraps the native FindOneAndDelete collection method.

func (*Collection) FindOneAndReplace added in v0.26.0

func (c *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) lungo.ISingleResult

FindOneAndReplace wraps the native FindOneAndReplace collection method.

func (*Collection) FindOneAndUpdate added in v0.26.0

func (c *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, opts ...*options.FindOneAndUpdateOptions) lungo.ISingleResult

FindOneAndUpdate wraps the native FindOneAndUpdate collection method.

func (*Collection) InsertMany added in v0.26.0

func (c *Collection) InsertMany(ctx context.Context, documents []interface{}, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error)

InsertMany wraps the native InsertMany collection method.

func (*Collection) InsertOne added in v0.26.0

func (c *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)

InsertOne wraps the native InsertOne collection method.

func (*Collection) Native added in v0.27.0

func (c *Collection) Native() lungo.ICollection

Native will return the underlying native collection.

func (*Collection) ReplaceOne added in v0.26.0

func (c *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)

ReplaceOne wraps the native ReplaceOne collection method.

func (*Collection) UpdateMany added in v0.26.0

func (c *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateMany wraps the native UpdateMany collection method.

func (*Collection) UpdateOne added in v0.26.0

func (c *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateOne wraps the native UpdateOne collection method.

type Decimal added in v0.31.0

type Decimal = decimal.Decimal

Decimal supports coding to and from the BSON decimal128 type.

type Event added in v0.17.1

type Event string

Event defines the event type.

const (
	// Opened is emitted when the stream has been opened the first time. If the
	// receiver returns without and error it will not be emitted again in favor
	// of the resumed event.
	Opened Event = "opened"

	// Resumed is emitted after the stream has been resumed.
	Resumed Event = "resumed"

	// Created is emitted when a document has been created.
	Created Event = "created"

	// Updated is emitted when a document has been updated.
	Updated Event = "updated"

	// Deleted is emitted when a document has been deleted.
	Deleted Event = "deleted"

	// Errored is emitted when the underlying stream or the receiver returned an
	// error.
	Errored Event = "errored"

	// Stopped is emitted when the stream has been stopped
	Stopped Event = "stopped"
)

type Extension added in v0.34.1

type Extension func(builder *bsoncodec.RegistryBuilder)

Extension is a function that registers custom encoder and decoder on the provided BSON registry builder.

type Field

type Field struct {
	// The underlying item field.
	ItemField

	// The custom flags.
	Flags []string

	// The relationship status.
	ToOne   bool
	ToMany  bool
	HasOne  bool
	HasMany bool

	// The relationship information.
	RelName    string
	RelType    string
	RelInverse string
}

A Field contains the meta information about a single field of a model.

type Flags added in v0.29.1

type Flags int

Flags can be used to change the behaviour of operations.

const (
	// NoTransaction will allow running operations without a transaction that by
	// default require a transaction.
	NoTransaction Flags = 1 << iota

	// NoValidation will allow storing and retrieving invalid models.
	NoValidation

	// TextScoreSort will prepend the sort with a sort based on the text score
	// of documents. The Base.Score attribute is set to the respective score.
	TextScoreSort
)

func Merge added in v0.29.1

func Merge(flags []Flags) Flags

Merge will combine the provided flags.

func (Flags) Has added in v0.29.1

func (f Flags) Has(flags Flags) bool

Has returns whether the receiver has set all provided flags.

type HasMany

type HasMany struct{}

The HasMany type denotes a has-many relationship in a model declaration.

type HasOne added in v0.8.3

type HasOne struct{}

The HasOne type denotes a has-one relationship in a model declaration.

Has-one relationships requires that the referencing side is ensuring that the reference is unique. In fire this should be done using a uniqueness validator and a unique index on the collection.

type ID added in v0.20.0

type ID = primitive.ObjectID

ID is shorthand type for the object ID.

func FromHex added in v0.20.0

func FromHex(str string) (ID, error)

FromHex will convert the provided string to an ID.

func MustFromHex added in v0.20.0

func MustFromHex(str string) ID

MustFromHex will convert the provided string to an ID and panic if the string is not a valid ID.

func New added in v0.20.0

func New(timestamp ...time.Time) ID

New will return a new object ID, optionally using a custom timestamp.

type Index added in v0.25.4

type Index struct {
	// The un-prefixed index fields.
	Fields []string

	// The translated keys of the index.
	Keys bson.D

	// Whether the index is unique.
	Unique bool

	// The automatic expiry of documents.
	Expiry time.Duration

	// The partial filter expression.
	Filter bson.D
}

Index is an index registered with a model.

func (*Index) Compile added in v0.25.4

func (i *Index) Compile() mongo.IndexModel

Compile will compile the index to a mongo.IndexModel.

type Item added in v0.34.1

type Item interface {
	ID() string
	Validate() error
	GetBase() *ItemBase
	GetAccessor(interface{}) *stick.Accessor
}

Item defines the shape of an item stored in a model. Custom types must implement the interface by embedding the Base type.

type ItemBase added in v0.34.1

type ItemBase struct {
	ItemID string `json:"id,omitempty" bson:"_id,omitempty"`
}

ItemBase is the base for every coal model item.

func I added in v0.34.1

func I(id ...string) ItemBase

I is a shorthand to construct an item base with the provided ID or a generated ID if none specified.

func (*ItemBase) GetAccessor added in v0.34.1

func (*ItemBase) GetAccessor(v interface{}) *stick.Accessor

GetAccessor implements the Model interface.

func (*ItemBase) GetBase added in v0.34.1

func (b *ItemBase) GetBase() *ItemBase

GetBase implements the Item interface.

func (*ItemBase) ID added in v0.34.1

func (b *ItemBase) ID() string

ID implements the Item interface.

type ItemField added in v0.34.1

type ItemField struct {
	// The index of the field in the struct.
	Index int

	// The struct field name e.g. "TireSize".
	Name string

	// The struct field type and kind.
	Type reflect.Type
	Kind reflect.Kind

	// The JSON object key name e.g. "tire-size".
	JSONKey string

	// The BSON document key name e.g. "tire_size".
	BSONKey string

	// Whether the field is a pointer and thus optional.
	Optional bool

	// The item meta if field is a type embedding ItemBase.
	ItemMeta *ItemMeta
}

ItemField contains the meta information about a single field of an item.

type ItemMeta added in v0.34.1

type ItemMeta struct {
	// The struct type.
	Type reflect.Type

	// The struct type name e.g. "models.CarWheel".
	Name string

	// The struct fields.
	Fields map[string]*ItemField

	// The struct fields ordered.
	OrderedFields []*ItemField

	// The database fields.
	DatabaseFields map[string]*ItemField

	// The attributes.
	Attributes map[string]*ItemField

	// The accessor.
	Accessor *stick.Accessor
}

ItemMeta stores extracted meta data from a model item.

func GetItemMeta added in v0.34.1

func GetItemMeta(typ reflect.Type) *ItemMeta

GetItemMeta returns the meta structure for the specified item type. It will always return the same value for the same item.

type Iterator added in v0.27.0

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

Iterator manages the iteration over a cursor.

func (*Iterator) All added in v0.29.4

func (i *Iterator) All(list interface{}) error

All will load all documents from the cursor and add them to the provided list. If the cursor is exhausted or an error occurred the cursor is closed.

func (*Iterator) Close added in v0.27.0

func (i *Iterator) Close()

Close will close the underlying cursor. A call to it should be deferred right after obtaining an iterator. Close should be called also if the iterator is still valid but no longer used by the application.

func (*Iterator) Decode added in v0.27.0

func (i *Iterator) Decode(v interface{}) error

Decode will decode the loaded document to the specified value.

func (*Iterator) Error added in v0.27.0

func (i *Iterator) Error() error

Error returns the first error encountered during iteration. It should always be checked when done to ensure there have been no errors.

func (*Iterator) Next added in v0.27.0

func (i *Iterator) Next() bool

Next will load the next document from the cursor and if available return true. If it returns false the iteration must be stopped due to the cursor being exhausted or an error.

type List added in v0.34.1

type List[T Item] []T

List wraps any type that embeds ItemBase as a slice that automatically merges existing items with new items if they have the same ID values.

func (*List[T]) UnmarshalBSONValue added in v0.34.1

func (l *List[T]) UnmarshalBSONValue(typ bsontype.Type, bytes []byte) error

UnmarshalBSONValue implement the bson.ValueUnmarshaler interface.

func (*List[T]) UnmarshalJSON added in v0.34.1

func (l *List[T]) UnmarshalJSON(bytes []byte) error

UnmarshalJSON implement the json.Unmarshaler interface.

func (*List[T]) Validate added in v0.34.1

func (l *List[T]) Validate() error

Validate will validate all items and return the first error.

type ManagedIterator added in v0.29.1

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

ManagedIterator wraps an iterator to enforce decoding to a model.

func (*ManagedIterator) Close added in v0.29.1

func (i *ManagedIterator) Close()

Close will close the underlying cursor. A call to it should be deferred right after obtaining an iterator. Close should be called also if the iterator is still valid but no longer used by the application.

func (*ManagedIterator) Decode added in v0.29.1

func (i *ManagedIterator) Decode(model Model) error

Decode will decode the loaded document to the specified model.

func (*ManagedIterator) Error added in v0.29.1

func (i *ManagedIterator) Error() error

Error returns the first error encountered during iteration. It should always be checked when done to ensure there have been no errors.

func (*ManagedIterator) Next added in v0.29.1

func (i *ManagedIterator) Next() bool

Next will load the next document from the cursor and if available return true. If it returns false the iteration must be stopped due to the cursor being exhausted or an error.

type Manager added in v0.27.0

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

Manager manages operations on collection of documents. It will validate operations and ensure that they are safe under the MongoDB guarantees.

func (*Manager) C added in v0.27.0

func (m *Manager) C() *Collection

C is a shorthand to access the underlying collection.

func (*Manager) Count added in v0.27.0

func (m *Manager) Count(ctx context.Context, filter bson.M, skip, limit int64, lock bool, flags ...Flags) (int64, error)

Count will count the documents that match the specified filter. Lock can be set to true to force a write lock on the documents and prevent a stale read during a transaction.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) Delete added in v0.27.0

func (m *Manager) Delete(ctx context.Context, model Model, id ID) (bool, error)

Delete will remove the document with the specified ID. It will return whether a document has been found and deleted.

func (*Manager) DeleteAll added in v0.27.0

func (m *Manager) DeleteAll(ctx context.Context, filter bson.M) (int64, error)

DeleteAll will delete the documents that match the specified filter. It will return the number of deleted documents.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run as part of a transaction.

func (*Manager) DeleteFirst added in v0.27.0

func (m *Manager) DeleteFirst(ctx context.Context, model Model, filter bson.M, sort []string) (bool, error)

DeleteFirst will delete the first document that matches the specified filter. It will return whether a document has been found and deleted.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run as part of a transaction.

func (*Manager) Distinct added in v0.27.1

func (m *Manager) Distinct(ctx context.Context, field string, filter bson.M, lock bool, flags ...Flags) ([]interface{}, error)

Distinct will find all documents that match the specified filter and collect the specified field. Lock can be set to true to force a write lock on the documents and prevent a stale read during a transaction.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) Find added in v0.27.0

func (m *Manager) Find(ctx context.Context, model Model, id ID, lock bool, flags ...Flags) (bool, error)

Find will find the document with the specified ID. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction.

A transaction is required for locking.

func (*Manager) FindAll added in v0.27.0

func (m *Manager) FindAll(ctx context.Context, list interface{}, filter bson.M, sort []string, skip, limit int64, lock bool, flags ...Flags) error

FindAll will find all documents that match the specified filter. Lock can be set to true to force a write lock on the documents and prevent a stale read during a transaction.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) FindEach added in v0.27.0

func (m *Manager) FindEach(ctx context.Context, filter bson.M, sort []string, skip, limit int64, lock bool, flags ...Flags) (*ManagedIterator, error)

FindEach will find all documents that match the specified filter. Lock can be set to true to force a write lock on the documents and prevent a stale read during a transaction.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) FindFirst added in v0.27.0

func (m *Manager) FindFirst(ctx context.Context, model Model, filter bson.M, sort []string, skip int64, lock bool, flags ...Flags) (bool, error)

FindFirst will find the first document that matches the specified filter. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction.

A transaction is required for locking.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run during a transaction.

func (*Manager) Insert added in v0.27.0

func (m *Manager) Insert(ctx context.Context, models Model, flags ...Flags) error

Insert will insert the provided document. If the document has a zero ID a new ID will be generated and assigned.

func (*Manager) InsertAll added in v0.29.1

func (m *Manager) InsertAll(ctx context.Context, models []Model, flags ...Flags) error

InsertAll will insert the provided documents. If a document has a zero ID a new ID will be generated and assigned. The documents are inserted in order until an error is encountered.

func (*Manager) InsertIfMissing added in v0.27.0

func (m *Manager) InsertIfMissing(ctx context.Context, filter bson.M, model Model, lock bool, flags ...Flags) (bool, error)

InsertIfMissing will insert the provided document if no document matched the provided filter. If the document has a zero ID a new ID will be generated and assigned. It will return whether a document has been inserted. The underlying upsert operation will Merge the filter with the model fields. Lock can be set to true to force a write lock on the existing document and prevent a stale read during a transaction.

A transaction is required for locking.

Warning: Even with transactions there is a risk for duplicate inserts when the filter is not covered by a unique index.

func (*Manager) Project added in v0.29.1

func (m *Manager) Project(ctx context.Context, id ID, field string, lock bool) (interface{}, bool, error)

Project will return the field of the specified document. It will also return whether a document has been found at all.

A transaction is required for locking.

func (*Manager) ProjectAll added in v0.29.1

func (m *Manager) ProjectAll(ctx context.Context, filter bson.M, field string, sort []string, skip, limit int64, lock bool, flags ...Flags) (map[ID]interface{}, error)

ProjectAll will look up the specified field for all matching documents and return a map with their IDs and field values.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) ProjectEach added in v0.29.1

func (m *Manager) ProjectEach(ctx context.Context, filter bson.M, field string, sort []string, skip, limit int64, lock bool, fn func(id ID, val interface{}) bool, flags ...Flags) error

ProjectEach will look up the specified field for all documents matching the specified filter and yield them to the provided function until all have been found or false has been returned.

A transaction is required to ensure isolation.

NoTransaction: The result may miss documents or include them multiple times if interleaving operations move the documents in the used index.

func (*Manager) ProjectFirst added in v0.29.1

func (m *Manager) ProjectFirst(ctx context.Context, filter bson.M, field string, sort []string, skip int64, lock bool) (interface{}, bool, error)

ProjectFirst will return the field of the first matching document. It will also return whether a document has been found at all.

A transaction is required for locking.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run during a transaction.

func (*Manager) Replace added in v0.27.0

func (m *Manager) Replace(ctx context.Context, model Model, lock bool, flags ...Flags) (bool, error)

Replace will replace the existing document with the provided one. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction in case the replace did not change the document.

A transaction is required for locking.

func (*Manager) ReplaceFirst added in v0.27.0

func (m *Manager) ReplaceFirst(ctx context.Context, filter bson.M, model Model, lock bool, flags ...Flags) (bool, error)

ReplaceFirst will replace the first document that matches the specified filter. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction if the replace did not cause an update.

A transaction is required for locking.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run as part of a transaction.

func (*Manager) T added in v0.27.0

func (m *Manager) T() *Translator

T is a shorthand to access the underlying translator.

func (*Manager) Update added in v0.27.0

func (m *Manager) Update(ctx context.Context, model Model, id ID, update bson.M, lock bool, flags ...Flags) (bool, error)

Update will update the document with the specified ID. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction in case the update did not change the document.

A transaction is required for locking.

func (*Manager) UpdateAll added in v0.27.0

func (m *Manager) UpdateAll(ctx context.Context, filter, update bson.M, lock bool) (int64, error)

UpdateAll will update the documents that match the specified filter. It will return the number of matched documents. Lock can be set to true to force a write lock on the documents and prevent a stale read during a transaction in case the operation did not change all documents.

A transaction is required for locking.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run as part of a transaction.

func (*Manager) UpdateFirst added in v0.27.0

func (m *Manager) UpdateFirst(ctx context.Context, model Model, filter, update bson.M, sort []string, lock bool, flags ...Flags) (bool, error)

UpdateFirst will update the first document that matches the specified filter. It will return whether a document has been found. Lock can be set to true to force a write lock on the document and prevent a stale read during a transaction in case the update did not change the document.

A transaction is required for locking.

Warning: If the operation depends on interleaving writes to not include or exclude documents from the filter it should be run as part of a transaction.

func (*Manager) Upsert added in v0.27.0

func (m *Manager) Upsert(ctx context.Context, model Model, filter, update bson.M, sort []string, lock bool, flags ...Flags) (bool, error)

Upsert will update the first document that matches the specified filter. If no document has been found, the update document is applied to the filter and inserted. It will return whether a document has been inserted. Lock can be set to true to force a write lock on the existing document and prevent a stale read during a transaction.

A transaction is required for locking.

Warning: Even with transactions there is a risk for duplicate inserts when the filter is not covered by a unique index.

type Meta

type Meta struct {
	// The struct type.
	Type reflect.Type

	// The struct type name e.g. "models.CarWheel".
	Name string

	// The plural resource name e.g. "car-wheels".
	PluralName string

	// The collection name e.g. "car_wheels".
	Collection string

	// The struct fields.
	Fields map[string]*Field

	// The struct fields ordered.
	OrderedFields []*Field

	// The database fields.
	DatabaseFields map[string]*Field

	// The attributes.
	Attributes map[string]*Field

	// The relationships.
	Relationships map[string]*Field

	// The request fields.
	RequestFields map[string]*Field

	// The flagged fields.
	FlaggedFields map[string][]*Field

	// The accessor.
	Accessor *stick.Accessor

	// The registered indexes.
	Indexes []Index
}

Meta stores extracted meta data from a model.

func GetMeta added in v0.20.0

func GetMeta(model Model) *Meta

GetMeta returns the meta structure for the specified model. It will always return the same value for the same model.

Note: This method panics if the passed Model has invalid fields or tags.

func (*Meta) Make

func (m *Meta) Make() Model

Make returns a pointer to a new zero initialized model e.g. *Post.

func (*Meta) MakeSlice

func (m *Meta) MakeSlice() interface{}

MakeSlice returns a pointer to a zero length slice of the model e.g. *[]*Post.

type Migration added in v0.32.0

type Migration struct {
	// The name.
	Name string

	// The timeout.
	//
	// Default: 5m.
	Timeout time.Duration

	// Whether the migration should be run asynchronously after all synchronous
	// migrations.
	Async bool

	// The migration function.
	Migrator func(ctx context.Context, store *Store) (int64, int64, error)
}

Migration is a single migration.

type Migrator added in v0.32.0

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

Migrator manages multiple migrations.

func NewMigrator added in v0.32.0

func NewMigrator() *Migrator

NewMigrator creates and returns a new migrator.

func (*Migrator) Add added in v0.32.0

func (m *Migrator) Add(migration Migration)

Add will add the provided migration.

func (*Migrator) Run added in v0.32.0

func (m *Migrator) Run(store *Store, logger io.Writer, reporter func(error)) error

Run will run all added migrations.

type Model

type Model interface {
	ID() ID
	Validate() error
	GetBase() *Base
	GetAccessor(interface{}) *stick.Accessor
}

Model defines the shape of a document stored in a collection. Custom types must implement the interface by embedding the Base type.

func Slice added in v0.26.1

func Slice(val interface{}) []Model

Slice takes a slice of the form []Post, []*Post, *[]Post or *[]*Post and returns a new slice that contains all models.

type Receiver added in v0.17.1

type Receiver func(event Event, id ID, model Model, err error, token []byte) error

Receiver is a callback that receives stream events.

type Registry added in v0.33.2

type Registry struct {
	*stick.Registry[Model]
}

Registry is a collection of known models.

func NewRegistry added in v0.33.0

func NewRegistry(models ...Model) *Registry

NewRegistry will return a model registry indexed by plural name.

func (*Registry) Lookup added in v0.33.2

func (r *Registry) Lookup(pluralName string) Model

Lookup will lookup a model by its plural name.

type SingleResult added in v0.29.0

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

SingleResult wraps a single operation result.

func (*SingleResult) Decode added in v0.29.0

func (r *SingleResult) Decode(i interface{}) error

Decode will decode the document to the specified value.

func (*SingleResult) DecodeBytes added in v0.29.0

func (r *SingleResult) DecodeBytes() (bson.Raw, error)

DecodeBytes will return the raw document bytes.

func (*SingleResult) Err added in v0.29.0

func (r *SingleResult) Err() error

Err return will return the last error.

func (*SingleResult) Raw added in v0.34.3

func (r *SingleResult) Raw() (bson.Raw, error)

Raw will return the raw document bytes.

type Store

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

A Store manages the usage of a database client.

func Connect added in v0.24.0

func Connect(uri string, reporter func(error), opts ...*options.ClientOptions) (*Store, error)

Connect will connect to the specified database and return a new store. The read and write concern is set to majority by default.

In summary, queries may return data that has bas been committed but may not be the most recent committed data. Also, long-running cursors on indexed fields may return duplicate or missing documents due to the documents moving within the index. For operations involving multiple documents a transaction must be used to ensure atomicity, consistency and isolation.

func MustConnect added in v0.24.0

func MustConnect(uri string, reporter func(error), opts ...*options.ClientOptions) *Store

MustConnect will call Connect and panic on errors.

func MustOpen added in v0.24.0

func MustOpen(store lungo.Store, defaultDB string, reporter func(error)) *Store

MustOpen will call Open and panic on errors.

func NewStore

func NewStore(client lungo.IClient, defaultDB string, engine *lungo.Engine, reporter func(error)) *Store

NewStore creates a store that uses the specified client, default database and engine. The engine may be nil if no lungo database is used.

func Open added in v0.24.0

func Open(store lungo.Store, defaultDB string, reporter func(error)) (*Store, error)

Open will open the database using the provided lungo store. If the store is missing an in-memory store will be created.

func (*Store) C added in v0.20.0

func (s *Store) C(model Model) *Collection

C will return the collection for the specified model. The collection is just a thin wrapper around the driver collection API to integrate tracing. Since it does not perform any checks, it is recommended to use the manager to perform safe CRUD operations.

func (*Store) Client added in v0.20.0

func (s *Store) Client() lungo.IClient

Client returns the client used by this store.

func (*Store) Close

func (s *Store) Close() error

Close will close the store and its associated client.

func (*Store) DB added in v0.20.0

func (s *Store) DB() lungo.IDatabase

DB returns the database used by this store.

func (*Store) Lungo added in v0.32.0

func (s *Store) Lungo() bool

Lungo returns whether the stores is using a lungo instead of a mongo client.

func (*Store) M added in v0.27.0

func (s *Store) M(model Model) *Manager

M will return the manager for the specified model. The manager will translate query documents as well as perform extensive checks before running operations to ensure they are as safe as possible.

func (*Store) RT added in v0.32.2

func (s *Store) RT(ctx context.Context, maxAttempts int, fn func(ctx context.Context) error) error

RT will create a transaction around the specified callback and retry the transaction on transient errors up to the specified amount of attempts. See T for details on other transactional behaviours.

func (*Store) T added in v0.27.0

func (s *Store) T(ctx context.Context, readOnly bool, fn func(ctx context.Context) error) error

T will create a transaction around the specified callback. If the callback returns no error the transaction will be committed. If T itself does not return an error the transaction has been committed. The created context must be used with all operations that should be included in the transaction. A read only transaction will always abort the transaction when done.

A transaction has the effect that the read concern is upgraded to "snapshot" which results in isolated and linearizable reads and writes of the data that has been committed prior to the start of the transaction:

  • Writes that conflict with other transactional writes will return an error. Non-transactional writes will wait until the transaction has completed.
  • Reads are not guaranteed to be stable, another transaction may delete or modify the document and also commit concurrently. Therefore, documents that must "survive" the transaction and cause transactional writes to abort, must be locked by changing a field to a new value.

type Stream added in v0.17.1

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

Stream simplifies the handling of change streams to receive changes to documents.

func OpenStream added in v0.19.2

func OpenStream(store *Store, model Model, token []byte, receiver Receiver) *Stream

OpenStream will open a stream and continuously forward events to the specified receiver until the stream is closed. If a token is present it will be used to resume the stream.

The stream automatically resumes on errors using an internally stored resume token. Applications that need more control should store the token externally and reopen the stream manually to resume from a specific position.

func Reconcile added in v0.20.0

func Reconcile(store *Store, model Model, loaded func(), created, updated func(Model), deleted func(ID), errored func(error)) *Stream

Reconcile uses a stream to reconcile changes to a collection. It will automatically load existing models once the underlying stream has been opened. After that it will yield all changes to the collection until the returned stream has been closed.

func (*Stream) Close added in v0.17.1

func (s *Stream) Close()

Close will close the stream.

type Tag added in v0.34.0

type Tag struct {
	Value  interface{} `bson:"v"`
	Expiry time.Time   `bson:"e,omitempty"`
}

Tag is underlying model tag structure.

type Tester added in v0.17.1

type Tester struct {
	// The store to use for cleaning the database.
	Store *Store

	// The registered models.
	Models []Model
}

Tester provides facilities to work with coal models in tests.

func NewTester added in v0.17.1

func NewTester(store *Store, models ...Model) *Tester

NewTester returns a new tester. If no store is provided one will be created.

func (*Tester) Clean added in v0.17.1

func (t *Tester) Clean()

Clean will clean the collections of models that have been registered.

func (*Tester) Count added in v0.20.0

func (t *Tester) Count(model Model, filters ...bson.M) int

Count will count all saved models.

func (*Tester) Delete added in v0.17.1

func (t *Tester) Delete(model Model)

Delete will delete the specified model.

func (*Tester) DeleteAll added in v0.32.1

func (t *Tester) DeleteAll(model Model, filters ...bson.M)

DeleteAll will delete all specified models.

func (*Tester) Drop added in v0.33.0

func (t *Tester) Drop(models ...Model)

Drop will drop the model collections.

func (*Tester) Ensure added in v0.33.3

func (t *Tester) Ensure()

Ensure will ensure existing collections by inserting models and cleaning them right after.

func (*Tester) Fetch added in v0.17.1

func (t *Tester) Fetch(model Model, id ID) Model

Fetch will return the saved model.

func (*Tester) FindAll added in v0.17.1

func (t *Tester) FindAll(model Model, filters ...bson.M) interface{}

FindAll will return all saved models.

func (*Tester) FindLast added in v0.17.1

func (t *Tester) FindLast(model Model, filters ...bson.M) Model

FindLast will return the last saved model.

func (*Tester) Insert added in v0.26.1

func (t *Tester) Insert(model Model) Model

Insert will insert the specified model.

func (*Tester) Refresh added in v0.29.5

func (t *Tester) Refresh(model Model)

Refresh will refresh the provided model.

func (*Tester) Replace added in v0.26.1

func (t *Tester) Replace(model Model) Model

Replace will replace the specified model.

func (*Tester) Update added in v0.17.1

func (t *Tester) Update(model Model, update bson.M) Model

Update will update the specified model.

type Transaction added in v0.34.0

type Transaction struct {
	Store    *Store
	ReadOnly bool
}

Transaction describes a transaction.

func GetTransaction added in v0.29.1

func GetTransaction(ctx context.Context) (bool, Transaction)

GetTransaction will return whether the context carries a transaction and the store used to create the transaction.

type Translator added in v0.27.0

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

Translator is capable of translating filter, update and sort documents from struct field names to database fields names. It also checks documents against as list of unsafe operators. Field names may be prefixed with a "#" to bypass any validation.

func NewTranslator added in v0.27.0

func NewTranslator(model Model) *Translator

NewTranslator will return a translator for the specified model.

func (*Translator) Document added in v0.27.0

func (t *Translator) Document(query bson.M) (bson.D, error)

Document will convert the provided filter or update document and translate all field names to refer to known database fields. It will also validate the filter or update and return an error for unsafe expressions or operators.

func (*Translator) Field added in v0.27.1

func (t *Translator) Field(field string) (string, error)

Field will translate the specified field. The field may be a path to a nested item field or begin wih a "#" (after prefix) to specify a unknown field.

func (*Translator) Sort added in v0.27.0

func (t *Translator) Sort(fields []string) (bson.D, error)

Sort will convert the provided sort array to a sort document and translate all field names to refer to known database fields.

Jump to

Keyboard shortcuts

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