mgorm

package module
v0.0.0-...-e9e7736 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2013 License: MIT Imports: 7 Imported by: 0

README

#Simple Model All model are struct type

package main

import (
	"github.com/elsonwu/mgorm"
)

type User struct {
	mgorm.Model `bson:",inline" json:",inline"` //embed all base methods
	Username    string      `bson:"username" json:"username"`
	Email       string      `bson:"email" json:"email"`
}

func (self *User) CollectionName() string {
	return "user"
}

#Embedded Model

type User struct {
	mgorm.Model `bson:",inline" json:",inline"` //embed all base methods
	Username    string      `bson:"username" json:"username"`
	Email       string      `bson:"email" json:"email"`
	Profile     UserProfile `bson:"profile" json:"profile"`
}

type UserProfile struct {
	mgorm.EmbeddedModel `bson:",inline" json:"-"` //use mgorm.EmbeddedModel
	SecondaryEmail      string `bson:"secondary_email" json:"secondary_email"`
	Website             string `bson:"website" json:"website"`
}

#FindById

user := new(User)
err := mgorm.FindById(user, "51ffc45fad51987c28276e55")
if nil != err {
    fmt.Println(err)
}

#Find One

user := new(User)
criteria := mgorm.NewCriteria()
criteria.AddCond("username", "==", "elsonwu")
mgorm.Find(user, criteria)
fmt.Println(user)

#Find List

criteria := mgorm.NewCriteria()
criteria.SetLimit(3)
criteria.SetOffset(10)
criteria.SetSelect([]string{"email"})
criteria.AddSort("username", mgorm.CriteriaSortDesc)
users := make([]User, 3)
mgorm.FindAll(user, criteria).All(&users)
fmt.Println(users)

#Create One

user := new(User)
if !mgorm.Save(user) {
	fmt.Println(user.GetErrors())
}

#Update One

user.Email = "test@gmail.com"
if !mgorm.Save(user) {
	fmt.Println(user.GetErrors())
}	

#Error

user.AddError("Test the error")
if !mgorm.Save(user) {
	fmt.Println(user.GetErrors())
	//[Test the error]
}

#Validate //use tag rules for field's validation type User struct { mgorm.Model bson:",inline" json:",inline" //embed all base methods Username string bson:"username" json:"username" Email string bson:"email" json:"email" rules:"email" Profile UserProfile bson:"profile" json:"profile" }

type UserProfile struct {
	mgorm.EmbeddedModel `bson:",inline" json:"-"` //use mgorm.EmbeddedModel
	SecondaryEmail      string `bson:"secondary_email" json:"secondary_email" rules:"email"`
	Website             string `bson:"website" json:"website" rules:"url"`
}

user := new(User)
if mgorm.Validate(user) {
	fmt.Println(user.GetErrors(), user.Profile.GetErrors())
}

//When you run Save method, it will call Validate method automatically.
if !user.Save() {
	fmt.Println(user.GetErrors(), user.Profile.GetErrors())
}

//You can also do more validate in your model, it will run when validating
func (self *User) Validate() bool {

	//Don't forget to call the parent's Validate
    if !self.Model.Validate() {
    	return false
    }
    
    if self.Username == "Admin" {
    	self.AddError("You cannot use Admin as your username")
    	return false
    }
    
    return true
}

#Event ##built-in event

user.Username = "Admin"

//The event name is case insensitive, so here you can also use "beforesave"
user.On("BeforeSave", func() error {
	if "Admin" == user.Username {
		return errors.New("You cannot use Admin")
	}
	return nil
})

if !mgorm.Save(user) {
	fmt.Println(user.GetErrors())
	//[You cannot use Admin]
}

##Customized event

//You can emit the event manually
user.Username = "Admin"
user.On("TestEvent", func() error {
    if "Admin" == user.Username {
		return errors.New("You cannot use Admin")
	}
	return nil
})

//Notice: the event name is case insensitive
err := user.Emit("testevent")
if nil != err {
	fmt.Println(err)
	//You cannot use Admin
}

Documentation

Index

Constants

View Source
const CriteriaSortAsc int = 1
View Source
const CriteriaSortDesc int = -1
View Source
const EXP_EMAIL = `^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`
View Source
const EXP_URL = `` /* 344-byte string literal not displayed */

Variables

This section is empty.

Functions

func Collection

func Collection(name string) *mgo.Collection

func DB

func DB() *mgo.Database

func EmailValidator

func EmailValidator(fieldValue reflect.Value, fieldType reflect.StructField) error

func Find

func Find(model IModel, criteria ICriteria) error

func FindById

func FindById(model IModel, id string) error

func InitDB

func InitDB(connectString, dbName string) error

func Insert

func Insert(model IModel) bool

func Save

func Save(model IModel) bool

func Update

func Update(model IModel, attributes Map) bool

func UrlValidator

func UrlValidator(fieldValue reflect.Value, fieldType reflect.StructField) error

func Validate

func Validate(model IEmbeddedModel) bool

Types

type Criteria

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

func (*Criteria) AddCond

func (self *Criteria) AddCond(field, opt string, value interface{}) ICriteria

add more opt later when it does need.

func (*Criteria) AddSort

func (self *Criteria) AddSort(field string, sort int) ICriteria

func (*Criteria) GetConditions

func (self *Criteria) GetConditions() Map

func (*Criteria) GetLimit

func (self *Criteria) GetLimit() int

func (*Criteria) GetOffset

func (self *Criteria) GetOffset() int

func (*Criteria) GetSelect

func (self *Criteria) GetSelect() []string

func (*Criteria) GetSort

func (self *Criteria) GetSort() map[string]int

func (*Criteria) SetConditions

func (self *Criteria) SetConditions(conditions Map) ICriteria

func (*Criteria) SetLimit

func (self *Criteria) SetLimit(limit int) ICriteria

func (*Criteria) SetOffset

func (self *Criteria) SetOffset(offset int) ICriteria

func (*Criteria) SetSelect

func (self *Criteria) SetSelect(selects []string) ICriteria

func (*Criteria) SetSort

func (self *Criteria) SetSort(sort map[string]int) ICriteria

type EmbeddedModel

type EmbeddedModel struct {
	ErrorHandler `bson:",inline" json:"-"`
	Event        `bson:",inline" json:"-"`
}

func (*EmbeddedModel) Validate

func (self *EmbeddedModel) Validate() bool

type ErrorHandler

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

func (*ErrorHandler) AddError

func (self *ErrorHandler) AddError(err string)

func (*ErrorHandler) ClearErrors

func (self *ErrorHandler) ClearErrors()

func (*ErrorHandler) GetErrors

func (self *ErrorHandler) GetErrors() []error

func (*ErrorHandler) HasErrors

func (self *ErrorHandler) HasErrors() bool

type Event

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

func (*Event) Emit

func (self *Event) Emit(event string) error

func (*Event) On

func (self *Event) On(event string, fn EventFn)

type EventFn

type EventFn func() error

type ICriteria

type ICriteria interface {
	AddSort(field string, sort int) ICriteria
	SetSort(sort map[string]int) ICriteria
	GetSort() map[string]int
	SetSelect(selects []string) ICriteria
	GetSelect() []string
	GetLimit() int
	SetLimit(limit int) ICriteria
	GetOffset() int
	SetOffset(offset int) ICriteria
	GetConditions() Map
	SetConditions(conditions Map) ICriteria
	AddCond(field, opt string, value interface{}) ICriteria
}

func NewCriteria

func NewCriteria() ICriteria

type IEmbeddedModel

type IEmbeddedModel interface {
	IErrorHandler
	IValidator
	IEvent
}

type IErrorHandler

type IErrorHandler interface {
	HasErrors() bool
	AddError(err string)
	GetErrors() []error
	ClearErrors()
}

type IEvent

type IEvent interface {
	On(event string, fn EventFn)
	Emit(event string) error
}

type IModel

type IModel interface {
	IEmbeddedModel
	IsNew() bool
	GetId() bson.ObjectId
	AfterFind()
	BeforeSave() error
	AfterSave()
	CollectionName() string
}

type IValidator

type IValidator interface {
	Validate() bool
}

type Map

type Map map[string]interface{}

type Model

type Model struct {
	EmbeddedModel `bson:",inline" json:"-"`
	Id            bson.ObjectId `bson:"_id" json:"id"`
	// contains filtered or unexported fields
}

func (*Model) AfterFind

func (self *Model) AfterFind()

func (*Model) AfterSave

func (self *Model) AfterSave()

func (*Model) BeforeSave

func (self *Model) BeforeSave() error

func (*Model) GetId

func (self *Model) GetId() bson.ObjectId

func (*Model) IsNew

func (self *Model) IsNew() bool

type Query

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

func FindAll

func FindAll(model IModel, criteria ICriteria) *Query

func (*Query) All

func (self *Query) All(models interface{})

func (*Query) Close

func (self *Query) Close() error

func (*Query) Count

func (self *Query) Count() int

func (*Query) Iter

func (self *Query) Iter() *mgo.Iter

func (*Query) Next

func (self *Query) Next(model IModel) bool

func (*Query) One

func (self *Query) One(model IModel)

func (*Query) Query

func (self *Query) Query() *mgo.Query

type ValidateFn

type ValidateFn func(fieldValue reflect.Value, fieldType reflect.StructField) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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