coal

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2019 License: MIT Imports: 15 Imported by: 2

Documentation

Overview

Package coal provides a mini ORM for mongoDB.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidated = errors.New("invalidated")

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

View Source
var ErrStop = errors.New("stop")

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

Functions

func A

func A(m Model, field string) string

A is a short-hand function to extract the attribute JSON key of a model field.

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

func C

func C(m Model) string

C is a short-hand function to extract the collection of a model.

func Contains added in v0.15.0

func Contains(list []ID, id ID) bool

Contains returns true if a list of object ids contains the specified id.

func F

func F(m Model, field string) string

F is a short-hand function to extract the database BSON field name 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

func Includes(all, subset []ID) bool

Includes returns true if a list of object ids includes another list of object ids.

func IsHex added in v0.20.0

func IsHex(str string) bool

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

func L added in v0.19.0

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

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

func R(m Model, field string) string

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

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 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(t time.Time) *time.Time

T is a short-hand function to get a pointer of a timestamp.

Types

type Base

type Base struct {
	DocID ID `json:"-" bson:"_id"`
	// contains filtered or unexported fields
}

Base is the base for every coal model.

func (*Base) ID

func (b *Base) ID() ID

ID returns the models id.

func (*Base) Meta

func (b *Base) Meta() *Meta

Meta returns the models Meta structure.

func (*Base) MustGet

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

MustGet returns the value of the given field. MustGet will panic if no field has been found.

func (*Base) MustSet

func (b *Base) MustSet(name string, value interface{})

MustSet will set the given field to the the passed valued. MustSet will panic if no field has been found.

type Catalog added in v0.8.8

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

A Catalog provides a mechanism for models to access each others meta data.

func NewCatalog added in v0.8.8

func NewCatalog(models ...Model) *Catalog

NewCatalog will create a new catalog.

func (*Catalog) Add added in v0.8.8

func (c *Catalog) Add(models ...Model)

Add will add the specified models to the catalog.

func (*Catalog) All added in v0.17.0

func (c *Catalog) All() []Model

All returns a list of all registered models.

func (*Catalog) Find added in v0.8.8

func (c *Catalog) Find(pluralName string) Model

Find will return a model with the specified plural name.

func (*Catalog) Visualize added in v0.13.3

func (c *Catalog) Visualize(title string) string

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

fdp -Tpdf models.dot > models.pdf

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 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 field e.g. "tire_size".
	BSONField 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
	// contains filtered or unexported fields
}

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

type ID = primitive.ObjectID

ID is short-hand 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 a object id.

func MustFromHex added in v0.20.0

func MustFromHex(str string) ID

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.

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.

func P added in v0.8.4

func P(id ID) *ID

P is a short-hand function to get a pointer of the specified object id.

func Unique added in v0.10.2

func Unique(ids []ID) []ID

Unique is a helper to get a unique list of object ids.

func Z added in v0.20.0

func Z() ID

Z is a short-hand to get a zero object id.

type Indexer

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

An Indexer can be used to manage indexes for models.

func NewIndexer

func NewIndexer() *Indexer

NewIndexer returns a new indexer.

func (*Indexer) Add

func (i *Indexer) Add(model Model, unique bool, expireAfter time.Duration, fields ...string)

Add 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 (*Indexer) AddPartial added in v0.17.1

func (i *Indexer) AddPartial(model Model, unique bool, expireAfter time.Duration, fields []string, filter bson.M)

AddPartial is similar to Add except that it adds a partial index.

func (*Indexer) AddRaw

func (i *Indexer) AddRaw(coll string, model mongo.IndexModel)

AddRaw will add a raw mongo.IndexModel to the internal index list.

func (*Indexer) Ensure

func (i *Indexer) Ensure(store *Store) error

Ensure will ensure that the required indexes exist. It may fail early if some of the indexes are already existing and do not match the supplied index.

type Map added in v0.22.0

type Map map[string]interface{}

Map represents a simple BSON map. In contrast to bson.M it provides methods to marshal and unmarshal concrete types to and from the map.

func MustMap added in v0.22.0

func MustMap(from interface{}) Map

MustMap will marshal the specified object to a map and panic on any error.

func (*Map) Marshal added in v0.22.0

func (m *Map) Marshal(from interface{}) error

Marshal will encode the type pointed by val and store the result.

func (*Map) MustMarshal added in v0.22.0

func (m *Map) MustMarshal(from interface{})

MustMarshal will marshal and panic on error.

func (*Map) MustUnmarshal added in v0.22.0

func (m *Map) MustUnmarshal(to interface{})

MustUnmarshal will unmarshal and panic on error.

func (*Map) Unmarshal added in v0.22.0

func (m *Map) Unmarshal(to interface{}) error

Unmarshal will unmarshal the raw value to the type pointed by val.

type Meta

type Meta struct {
	// 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
	// contains filtered or unexported fields
}

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 passed Model.

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

func (*Meta) Make

func (m *Meta) Make() Model

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

Note: Operations might replace the pointer content with a new structure, therefore the model eventually needs to be initialized again using Init().

func (*Meta) MakeSlice

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

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

Note: Don't forget to initialize the slice using InitSlice() after adding elements.

type Model

type Model interface {
	ID() ID
	Meta() *Meta

	MustGet(string) interface{}
	MustSet(string, interface{})
	// contains filtered or unexported methods
}

Model is the main interface implemented by every coal model embedding Base.

func Init

func Init(model Model) Model

Init initializes the internals of a model and should be called before using a newly created Model.

func InitSlice

func InitSlice(ptr interface{}) []Model

InitSlice initializes all models in a slice of the form *[]*Post and returns a new slice that contains all initialized 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 Store

type Store struct {
	// The session used by the store.
	Client *mongo.Client

	// The default db used by the store.
	DefaultDB string
}

A Store manages the usage of a database client.

func CreateStore

func CreateStore(uri string) (*Store, error)

CreateStore will connect to the specified database and return a new store. It will return an error if the initial connection failed

func MustCreateStore

func MustCreateStore(uri string) *Store

MustCreateStore will connect to the passed database and return a new store. It will panic if the initial connection failed.

func NewStore

func NewStore(client *mongo.Client, defaultDB string) *Store

NewStore returns a Store that uses the passed client and its default database.

func (*Store) C added in v0.20.0

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

C will return the collection associated to the specified model.

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() *mongo.Database

DB returns the database used by this store.

func (*Store) TC added in v0.20.0

func (s *Store) TC(tracer Tracer, model Model) *TracedCollection

TC will return a traced collection for the specified model.

func (*Store) TX added in v0.20.2

func (s *Store) TX(ctx context.Context, fn func(sc mongo.SessionContext) error) error

TX will create a transaction around the specified callback. If the callback returns no error the transaction will be committed.

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, created, updated func(Model), deleted func(ID), reporter 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 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.

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.

func (*Tester) Count added in v0.20.0

func (t *Tester) Count(model Model) 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) 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) interface{}

FindAll will return all saved models.

func (*Tester) FindLast added in v0.17.1

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

FindLast will return the last saved model.

func (*Tester) Save added in v0.17.1

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

Save will save the specified model.

func (*Tester) Update added in v0.17.1

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

Update will update the specified model.

type TracedCollection added in v0.20.0

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

TracedCollection wraps a collection to automatically push tracing spans for run queries.

func (*TracedCollection) AggregateAll added in v0.20.0

func (c *TracedCollection) AggregateAll(ctx context.Context, slicePtr interface{}, pipeline interface{}, opts ...*options.AggregateOptions) error

AggregateAll wraps the native Aggregate collection method and decodes all documents to the provided slice.

func (*TracedCollection) BulkWrite added in v0.20.0

BulkWrite wraps the native BulkWrite collection method.

func (*TracedCollection) CountDocuments added in v0.20.0

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

CountDocuments wraps the native CountDocuments collection method.

func (*TracedCollection) DeleteMany added in v0.20.0

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

DeleteMany wraps the native DeleteMany collection method.

func (*TracedCollection) DeleteOne added in v0.20.0

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

DeleteOne wraps the native DeleteOne collection method.

func (*TracedCollection) Distinct added in v0.20.0

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

Distinct wraps the native Distinct collection method.

func (*TracedCollection) EstimatedDocumentCount added in v0.20.0

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

EstimatedDocumentCount wraps the native EstimatedDocumentCount collection method.

func (*TracedCollection) FindAll added in v0.20.0

func (c *TracedCollection) FindAll(ctx context.Context, slicePtr interface{}, filter interface{}, opts ...*options.FindOptions) error

FindAll wraps the native Find collection method and decodes all documents to the provided slice.

func (*TracedCollection) FindOne added in v0.20.0

func (c *TracedCollection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult

FindOne wraps the native FindOne collection method.

func (*TracedCollection) FindOneAndDelete added in v0.20.0

func (c *TracedCollection) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongo.SingleResult

FindOneAndDelete wraps the native FindOneAndDelete collection method.

func (*TracedCollection) FindOneAndReplace added in v0.20.0

func (c *TracedCollection) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongo.SingleResult

FindOneAndReplace wraps the native FindOneAndReplace collection method.

func (*TracedCollection) FindOneAndUpdate added in v0.20.0

func (c *TracedCollection) FindOneAndUpdate(ctx context.Context, filter interface{}, update interface{}, opts ...*options.FindOneAndUpdateOptions) *mongo.SingleResult

FindOneAndUpdate wraps the native FindOneAndUpdate collection method.

func (*TracedCollection) InsertMany added in v0.20.0

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

InsertMany wraps the native InsertMany collection method.

func (*TracedCollection) InsertOne added in v0.20.0

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

InsertOne wraps the native InsertOne collection method.

func (*TracedCollection) ReplaceOne added in v0.20.0

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

ReplaceOne wraps the native ReplaceOne collection method.

func (*TracedCollection) UpdateMany added in v0.20.0

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

UpdateMany wraps the native UpdateMany collection method.

func (*TracedCollection) UpdateOne added in v0.20.0

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

UpdateOne wraps the native UpdateOne collection method.

type Tracer added in v0.20.0

type Tracer interface {
	Push(name string)
	Tag(key string, value interface{})
	Log(key string, value interface{})
	Pop()
}

Tracer is used by a traced collection to push tracing spans for database queries.

Jump to

Keyboard shortcuts

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