Documentation ¶
Overview ¶
Package coal provides a mini ORM for mongoDB.
Index ¶
- Variables
- func A(m Model, field string) string
- func C(m Model) string
- func Contains(list []ID, id ID) bool
- func F(m Model, field string) string
- func Includes(all, subset []ID) bool
- func IsDuplicate(err error) bool
- func IsHex(str string) bool
- func IsMissing(err error) bool
- func L(m Model, flag string, force bool) string
- func R(m Model, field string) string
- func Require(m Model, flags ...string)
- func Sort(fields ...string) bson.D
- func T(t time.Time) *time.Time
- func ToD(model Model) bson.D
- func ToM(model Model) bson.M
- type Base
- type Catalog
- func (c *Catalog) Add(models ...Model)
- func (c *Catalog) AddIndex(model Model, unique bool, expiry time.Duration, fields ...string)
- func (c *Catalog) AddPartialIndex(model Model, unique bool, expiry time.Duration, fields []string, filter bson.D)
- func (c *Catalog) All() map[Model][]Index
- func (c *Catalog) EnsureIndexes(store *Store) error
- func (c *Catalog) Find(pluralName string) Model
- func (c *Catalog) FindIndexes(pluralName string) []Index
- func (c *Catalog) VisualizeDOT(title string) string
- func (c *Catalog) VisualizePDF(title string) ([]byte, error)
- type Collection
- func (c *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*Iterator, error)
- func (c *Collection) AggregateAll(ctx context.Context, list interface{}, pipeline interface{}, ...) error
- func (c *Collection) BulkWrite(ctx context.Context, models []mongo.WriteModel, ...) (*mongo.BulkWriteResult, error)
- func (c *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error)
- func (c *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
- func (c *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)
- func (c *Collection) Distinct(ctx context.Context, field string, filter interface{}, ...) ([]interface{}, error)
- func (c *Collection) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error)
- func (c *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*Iterator, error)
- func (c *Collection) FindAll(ctx context.Context, list interface{}, filter interface{}, ...) error
- func (c *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) lungo.ISingleResult
- func (c *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, ...) lungo.ISingleResult
- func (c *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, ...) lungo.ISingleResult
- func (c *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, ...) lungo.ISingleResult
- func (c *Collection) InsertMany(ctx context.Context, documents []interface{}, ...) (*mongo.InsertManyResult, error)
- func (c *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
- func (c *Collection) Native() lungo.ICollection
- func (c *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, ...) (*mongo.UpdateResult, error)
- func (c *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, ...) (*mongo.UpdateResult, error)
- func (c *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, ...) (*mongo.UpdateResult, error)
- type Event
- type Field
- type HasMany
- type HasOne
- type ID
- type Index
- type Iterator
- type Level
- type Manager
- func (m *Manager) C() *Collection
- func (m *Manager) Count(ctx context.Context, filter bson.M, skip, limit int64, lock bool, ...) (int64, error)
- func (m *Manager) Delete(ctx context.Context, model Model, id ID) (bool, error)
- func (m *Manager) DeleteAll(ctx context.Context, filter bson.M) (int64, error)
- func (m *Manager) DeleteFirst(ctx context.Context, model Model, filter bson.M, sort []string) (bool, error)
- func (m *Manager) Distinct(ctx context.Context, field string, filter bson.M, lock bool, level ...Level) ([]interface{}, error)
- func (m *Manager) Find(ctx context.Context, model Model, id ID, lock bool) (bool, error)
- func (m *Manager) FindAll(ctx context.Context, list interface{}, filter bson.M, sort []string, ...) error
- func (m *Manager) FindEach(ctx context.Context, filter bson.M, sort []string, skip, limit int64, ...) (*Iterator, error)
- func (m *Manager) FindFirst(ctx context.Context, model Model, filter bson.M, sort []string, skip int64, ...) (bool, error)
- func (m *Manager) Insert(ctx context.Context, models ...Model) error
- func (m *Manager) InsertIfMissing(ctx context.Context, filter bson.M, model Model, lock bool) (bool, error)
- func (m *Manager) Replace(ctx context.Context, model Model, lock bool) (bool, error)
- func (m *Manager) ReplaceFirst(ctx context.Context, filter bson.M, model Model, lock bool) (bool, error)
- func (m *Manager) T() *Translator
- func (m *Manager) Update(ctx context.Context, model Model, id ID, update bson.M, lock bool) (bool, error)
- func (m *Manager) UpdateAll(ctx context.Context, filter, update bson.M, lock bool) (int64, error)
- func (m *Manager) UpdateFirst(ctx context.Context, model Model, filter, update bson.M, sort []string, ...) (bool, error)
- func (m *Manager) Upsert(ctx context.Context, model Model, filter, update bson.M, sort []string, ...) (bool, error)
- type Meta
- type Model
- type Receiver
- type Store
- func Connect(uri string) (*Store, error)
- func MustConnect(uri string) *Store
- func MustOpen(store lungo.Store, defaultDB string, reporter func(error)) *Store
- func NewStore(client lungo.IClient, defaultDB string, engine *lungo.Engine) *Store
- func Open(store lungo.Store, defaultDB string, reporter func(error)) (*Store, error)
- type Stream
- type Tester
- func (t *Tester) Clean()
- func (t *Tester) Count(model Model, query ...bson.M) int
- func (t *Tester) Delete(model Model)
- func (t *Tester) Fetch(model Model, id ID) Model
- func (t *Tester) FindAll(model Model, query ...bson.M) interface{}
- func (t *Tester) FindLast(model Model, query ...bson.M) Model
- func (t *Tester) Insert(model Model) Model
- func (t *Tester) Replace(model Model) Model
- func (t *Tester) Update(model Model, update bson.M) Model
- type Translator
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidated = errors.New("invalidated")
ErrInvalidated may be returned to the receiver if the underlying collection or database has been invalidated due to a drop or rename.
var ErrStop = errors.New("stop")
ErrStop may be returned by a receiver to stop the stream.
var ErrTransactionRequired = errors.New("operation requires a transaction")
ErrTransactionRequired is returned if an operation would be unsafe to perform without a transaction.
Functions ¶
func A ¶
A is a short-hand function to extract the JSON key of a model field.
Note: A will panic if no field has been found.
func Contains ¶ added in v0.15.0
Contains returns true if a list of object ids contains the specified id.
func F ¶
F is a short-hand function to extract the BSON key of a model field. Additionally, it supports the "-" prefix for retrieving sort keys.
Note: F will panic if no field has been found.
func Includes ¶ added in v0.15.1
Includes returns true if a list of object ids includes another list of object ids.
func IsDuplicate ¶ added in v0.27.0
IsDuplicate returns whether the provided error describes a duplicate document.
func IsHex ¶ added in v0.20.0
IsHex will assess whether the provided string is a valid hex encoded object id.
func IsMissing ¶ added in v0.27.0
IsMissing returns whether the provided error describes a missing document.
func L ¶ added in v0.19.0
L is a short-hand function to lookup 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 R ¶ added in v0.11.2
R is a short-hand function to extract the relationship name of a model field.
Note: R will panic if no field has been found.
func Require ¶ added in v0.19.0
Require will check if the specified flags are set on the specified model and panic if one is missing.
func Sort ¶ added in v0.20.0
Sort is a helper function to compute a sort object based on a list of fields with dash prefixes for descending sorting.
Types ¶
type Base ¶
type Base struct { DocID ID `json:"-" bson:"_id,omitempty"` Lock int64 `json:"-" bson:"_lk,omitempty"` Token ID `json:"-" bson:"_tk,omitempty"` }
Base is the base for every coal model.
func B ¶ added in v0.26.1
B is a short-hand to construct a base with the provided id or a generated id if none specified.
func (*Base) GetAccessor ¶ added in v0.28.0
GetAccessor implements the Model interface.
type Catalog ¶ added in v0.8.8
type Catalog struct {
// contains filtered or unexported fields
}
A Catalog provides a central mechanism for registering models and indexes.
func NewCatalog ¶ added in v0.8.8
NewCatalog will create a new catalog.
func (*Catalog) AddIndex ¶ added in v0.25.4
AddIndex will add an index to the internal index list. Fields that are prefixed with a dash will result in an descending index. See the MongoDB documentation for more details.
func (*Catalog) AddPartialIndex ¶ added in v0.25.4
func (c *Catalog) AddPartialIndex(model Model, unique bool, expiry time.Duration, fields []string, filter bson.D)
AddPartialIndex is similar to Add except that it adds a partial index. The filter must be an ordered document to ensure equality.
func (*Catalog) EnsureIndexes ¶ added in v0.25.4
EnsureIndexes will ensure that the added indexes exist. It may fail early if some of the indexes are already existing and do not match the supplied index.
func (*Catalog) FindIndexes ¶ added in v0.25.4
FindIndexes will return the indexes for the specified plural name.
func (*Catalog) VisualizeDOT ¶ added in v0.25.4
VisualizeDOT emits a string in DOT format which when rendered with graphviz visualizes the models and their relationships.
fdp -Tpdf models.dot > models.pdf
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) AggregateAll ¶ added in v0.26.0
func (c *Collection) AggregateAll(ctx context.Context, list interface{}, pipeline interface{}, opts ...*options.AggregateOptions) error
AggregateAll wraps the native Aggregate collection method and decodes all documents to the provided slice.
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) FindAll ¶ added in v0.26.0
func (c *Collection) FindAll(ctx context.Context, list interface{}, filter interface{}, opts ...*options.FindOptions) error
FindAll wraps the native Find collection method and decodes all documents to the provided slice.
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 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 Field ¶
type Field 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 // The custom flags. Flags []string // Whether the field is a pointer and thus optional. Optional bool // 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 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
ID is short-hand type for the object id.
func MustFromHex ¶ added in v0.20.0
MustFromHex will convert the provided string to a object id and panic if the string is not a valid object id.
func N ¶ added in v0.14.0
func N() *ID
N is a short-hand function to get a typed nil object id pointer.
type Index ¶ added in v0.25.4
Index is an index registered with a catalog.
func (*Index) Compile ¶ added in v0.25.4
func (i *Index) Compile() mongo.IndexModel
Compile will compile the index to a mongo.IndexModel.
type Iterator ¶ added in v0.27.0
type Iterator struct {
// contains filtered or unexported fields
}
Iterator manages the iteration over a cursor.
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
Decode will decode the loaded document to the specified value.
type Level ¶ added in v0.27.0
type Level int
Level describes the safety level under which an operation should be executed.
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 short-hand to access the mangers collection.
func (*Manager) Count ¶ added in v0.27.0
func (m *Manager) Count(ctx context.Context, filter bson.M, skip, limit int64, lock bool, level ...Level) (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 always required to ensure isolation.
Unsafe: The count 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
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
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, level ...Level) ([]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.
Unsafe: 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
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, level ...Level) 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.
Unsafe: 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, level ...Level) (*Iterator, 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 always required to ensure isolation.
Unsafe: 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) (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
Insert 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) (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) Replace ¶ added in v0.27.0
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) (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 short-hand to access the managers 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) (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
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) (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) (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 flagged fields. FlaggedFields map[string][]*Field // The accessor. Accessor *stick.Accessor }
Meta stores extracted meta data from a model.
func GetMeta ¶ added in v0.20.0
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.
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.
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
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
MustConnect will call Connect and panic on errors.
func NewStore ¶
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
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) M ¶ added in v0.27.0
M will return the manager for the specified model. The manager will translate query and update documents as well as perform extensive checks before running operations to ensure they are as safe as possible.
func (*Store) T ¶ added in v0.27.0
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 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 an also commit concurrently. Therefore, documents that must "survive" the transaction and cause transactional writes to abort, must be locked by incrementing or 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
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.
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 (*Tester) Clean ¶ added in v0.17.1
func (t *Tester) Clean()
Clean will remove the collections of models that have been registered and reset the header map.
type Translator ¶ added in v0.27.0
type Translator struct {
// contains filtered or unexported fields
}
Translator is capable of translating query, update and sort documents from struct field names to database fields names.
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
Document will convert the provided query or update document and translate all field names to refer to known database fields. It will also validate the query or update and return an error if an unsafe operator is used.