coal

package
v0.13.2 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2018 License: MIT Imports: 9 Imported by: 2

Documentation

Overview

Package coal provides a mini ORM for mongoDB.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func A

func A(m Model, field string) string

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

func C

func C(m Model) string

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

func F

func F(m Model, field string) string

F is a short-hand function to extract the BSON field name of a model attribute.

func P added in v0.8.4

func P(id bson.ObjectId) *bson.ObjectId

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

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 attribute.

func Unique added in v0.10.2

func Unique(ids []bson.ObjectId) []bson.ObjectId

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

func Validate

func Validate(m Model) error

Validate uses the govalidator package to validate the model based on the "valid" struct tags. If the passed model also implements the ValidatableModel interface, Validate method will be invoked after the struct validation.

func ValidateTimestamps

func ValidateTimestamps(m Model, createdAtField, updatedAtField string)

ValidateTimestamps is a helper function that can be used inside a models Validate method to maintain "created-at" and "updated-at" timestamps.

Note: You can pass an empty string to disable certain timestamps.

Types

type Base

type Base struct {
	DocID bson.ObjectId `json:"-" bson:"_id" valid:"required,object-id"`
	// contains filtered or unexported fields
}

Base is the base for every coal model.

func (*Base) ID

func (b *Base) ID() bson.ObjectId

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.

Note: MustGet will return the value of the first field that has a matching Name, JSONName, or BSONName and will panic if no field can be found.

func (*Base) MustSet

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

MustSet will set the given field to the the passed valued.

Note: MustSet will set the value of the first field that has a matching Name, JSONName, or BSONName and will panic if no field can been found. The method will also panic if the type of the field and the passed value do not match.

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) 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) VisualizeModels added in v0.13.2

func (c *Catalog) VisualizeModels(name string) string

VisualizeModels emits a string in dot format that when put through graphviz visualizes the model dependencies.

Example
catalog := NewCatalog(&postModel{}, &commentModel{}, &selectionModel{}, &noteModel{})
fmt.Print(catalog.VisualizeModels("Test"))
Output:

digraph G {
  rankdir="LR";
  ranksep="0.5";
  nodesep="0.4";
  pad="0.4,0.4";
  margin="0,0";
  concentrate="true";
  labelloc="t";
  fontsize="13";
  fontname="Arial BoldMT";
  splines="spline";
  label="Test";
  "coal.commentModel" [ label=<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">coal.commentModel</font></td></tr></table>|<table border="0" align="left" cellspacing="2" cellpadding="0" width="134"><tr><td align="left" width="130" port="Message">Message<font face="Arial ItalicMT" color="grey60"> string</font></td></tr><tr><td align="left" width="130" port="Parent">Parent<font face="Arial ItalicMT" color="grey60"> *bson.ObjectId</font></td></tr><tr><td align="left" width="130" port="Post">Post<font face="Arial ItalicMT" color="grey60"> bson.ObjectId</font></td></tr></table>>, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];
  "coal.noteModel" [ label=<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">coal.noteModel</font></td></tr></table>|<table border="0" align="left" cellspacing="2" cellpadding="0" width="134"><tr><td align="left" width="130" port="Title">Title<font face="Arial ItalicMT" color="grey60"> string</font></td></tr><tr><td align="left" width="130" port="CreatedAt">CreatedAt<font face="Arial ItalicMT" color="grey60"> time.Time</font></td></tr><tr><td align="left" width="130" port="UpdatedAt">UpdatedAt<font face="Arial ItalicMT" color="grey60"> time.Time</font></td></tr><tr><td align="left" width="130" port="Post">Post<font face="Arial ItalicMT" color="grey60"> bson.ObjectId</font></td></tr></table>>, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];
  "coal.postModel" [ label=<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">coal.postModel</font></td></tr></table>|<table border="0" align="left" cellspacing="2" cellpadding="0" width="134"><tr><td align="left" width="130" port="Title">Title<font face="Arial ItalicMT" color="grey60"> string</font></td></tr><tr><td align="left" width="130" port="Published">Published<font face="Arial ItalicMT" color="grey60"> bool</font></td></tr><tr><td align="left" width="130" port="TextBody">TextBody<font face="Arial ItalicMT" color="grey60"> string</font></td></tr><tr><td align="left" width="130" port="Comments">Comments<font face="Arial ItalicMT" color="grey60"> coal.HasMany</font></td></tr><tr><td align="left" width="130" port="Selections">Selections<font face="Arial ItalicMT" color="grey60"> coal.HasMany</font></td></tr><tr><td align="left" width="130" port="Note">Note<font face="Arial ItalicMT" color="grey60"> coal.HasOne</font></td></tr></table>>, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];
  "coal.selectionModel" [ label=<<table border="0" align="center" cellspacing="0.5" cellpadding="0" width="134"><tr><td align="center" valign="bottom" width="130"><font face="Arial BoldMT" point-size="11">coal.selectionModel</font></td></tr></table>|<table border="0" align="left" cellspacing="2" cellpadding="0" width="134"><tr><td align="left" width="130" port="Name">Name<font face="Arial ItalicMT" color="grey60"> string</font></td></tr><tr><td align="left" width="130" port="Posts">Posts<font face="Arial ItalicMT" color="grey60"> []bson.ObjectId</font></td></tr></table>>, shape=Mrecord, fontsize=10, fontname="ArialMT", margin="0.07,0.05", penwidth="1.0" ];
  "coal.commentModel"->"coal.commentModel"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=dotted, arrowhead=none, arrowtail=none ];
  "coal.commentModel"->"coal.postModel"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=solid, arrowhead=normal, arrowtail=none ];
  "coal.noteModel"->"coal.postModel"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=solid, arrowhead=none, arrowtail=none ];
  "coal.selectionModel"->"coal.postModel"[ fontname="ArialMT", fontsize=7, dir=both, arrowsize="0.9", penwidth="0.9", labelangle=32, labeldistance="1.8", style=solid, arrowhead=normal, arrowtail=normal ];
}

type Field

type Field struct {
	Name       string
	Type       reflect.Type
	Kind       reflect.Kind
	JSONName   string
	BSONName   string
	Optional   bool
	ToOne      bool
	ToMany     bool
	HasOne     bool
	HasMany    bool
	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.

Note: In fire has-many relationships will be fetched without authorization. This means that the query could return ids to resources that would normally not be accessible.

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.

Note: In fire has-one relationships will be fetched without authorization. This means that the query could return ids to resources that would normally not be accessible.

type Indexer

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

An Indexer can be used to ensure indexes for models.

func NewIndexer

func NewIndexer() *Indexer

NewIndexer returns a new indexer.

func (*Indexer) Add

func (i *Indexer) Add(model Model, unique, sparse bool, 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) AddRaw

func (i *Indexer) AddRaw(coll string, idx mgo.Index)

AddRaw will add a raw mgo.Index 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 Meta

type Meta struct {
	Name       string
	PluralName string
	Collection string
	Fields     []Field
	// contains filtered or unexported fields
}

Meta stores extracted meta data from a model.

func NewMeta

func NewMeta(model Model) *Meta

NewMeta returns the Meta structure for the passed Model.

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

func (*Meta) FindField

func (m *Meta) FindField(name string) *Field

FindField returns the first field that has a matching Name, JSONName, BSONName or RelName. FindField will return nil if no field has been found.

func (*Meta) Make

func (m *Meta) Make() Model

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

Note: Other libraries like mgo 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 with libraries like mgo.

func (*Meta) MustFindField

func (m *Meta) MustFindField(name string) *Field

MustFindField returns the first field that has a matching Name, JSONName, BSONName or RelName. MustFindField will panic if no field has been found.

type Model

type Model interface {
	ID() bson.ObjectId
	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 Store

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

A Store manages the usage of database connections.

func CreateStore

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

CreateStore will dial the passed 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 dial the passed database and return a new store. It will panic if the initial connection failed.

func NewStore

func NewStore(session *mgo.Session) *Store

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

func (*Store) Close

func (s *Store) Close()

Close will close the store and its associated session.

func (*Store) Copy

func (s *Store) Copy() *SubStore

Copy will make a copy of the store and the underlying session. Copied stores that are not used anymore must be closed.

type SubStore

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

A SubStore allows access to the database.

func (*SubStore) C

func (s *SubStore) C(model Model) *mgo.Collection

C will return the collection associated to the passed model.

func (*SubStore) Close

func (s *SubStore) Close()

Close will close the store and its associated session.

func (*SubStore) DB

func (s *SubStore) DB() *mgo.Database

DB returns the database used by this store.

type ValidatableModel

type ValidatableModel interface {
	Model

	// The Validate method that should return normal errors about invalid fields.
	Validate() error
}

The ValidatableModel interface can be additionally implemented to provide a custom validation method that is used by the Validate function.

Jump to

Keyboard shortcuts

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