orm

package
v0.0.0-...-576eb72 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2014 License: MPL-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ASC indicates that the results of the given query should be
	// returned in ascending order for the given field.
	ASC = Sort(driver.ASC)
	// DESC indicates that the results of the given query should be
	// returned in descending order for the given field.
	DESC = Sort(driver.DESC)
)
View Source
const (
	// WILL_INITIALIZE is emitted just before a gnd.la/orm.Orm is
	// initialized. The object is a *gnd.la/orm.Orm.
	WILL_INITIALIZE = "gnd.la/orm.will-initialize"
)

Variables

View Source
var (
	ErrInTransaction    = driver.ErrInTransaction
	ErrNotInTransaction = driver.ErrNotInTransaction
	ErrFinished         = driver.ErrFinished
)
View Source
var (
	// ErrNotSql indicates that the current driver is not using database/sql.
	ErrNoSql = errors.New("driver is not using database/sql")
)
View Source
var (

	// Rollback is returned from functions passed to Orm.Transaction to
	// indicate that they want the transaction to be rolled back without
	// returning any error from Orm.Transaction.
	Rollback = errors.New("transaction rolled back")
)

Functions

func And

func And(qs ...query.Q) query.Q

func Between

func Between(field string, begin interface{}, end interface{}) query.Q

Between is equivalent to field > begin AND field < end.

func CBetween

func CBetween(field string, begin interface{}, end interface{}) query.Q

CBetween stands for closed between and is equivalent to field >= begin AND field <= end.

func Contains

func Contains(field string, value interface{}) query.Q

func Eq

func Eq(field string, value interface{}) query.Q

func F

func F(field string) query.F

Field is a conveniency function which returns a reference to a field to be used in a query, mostly used for joins.

func Gt

func Gt(field string, value interface{}) query.Q

func Gte

func Gte(field string, value interface{}) query.Q

func In

func In(field string, value interface{}) query.Q

func LCBetween

func LCBetween(field string, begin interface{}, end interface{}) query.Q

LCBetween stands for left closed between and is equivalent to field >= begin AND field < end.

func Lt

func Lt(field string, value interface{}) query.Q

func Lte

func Lte(field string, value interface{}) query.Q

func Neq

func Neq(field string, value interface{}) query.Q

func Or

func Or(qs ...query.Q) query.Q

func RCBetween

func RCBetween(field string, begin interface{}, end interface{}) query.Q

RCBetween stands for right closed between and is equivalent to field > begin AND field <= end.

func Register

func Register(t interface{}, opts *Options)

Register registers a new type for all ORMs instantiated after this point. This is the preferred way to register structs and it generally should be called from an init() function.

func Subquery

func Subquery(q string) query.Subquery

Subquery is a conveniency function which returns a subquery which can used with any of the Q functions (Eq, Neq, Lt, In...).

Types

type Interface

type Interface interface {
	Table(t *Table) *Query
	Exists(t *Table, q query.Q) (bool, error)
	Count(t *Table, q query.Q) (uint64, error)
	Query(q query.Q) *Query
	One(q query.Q, out ...interface{}) (bool, error)
	MustOne(q query.Q, out ...interface{}) bool
	All() *Query
	Insert(obj interface{}) (Result, error)
	MustInsert(obj interface{}) Result
	Update(q query.Q, obj interface{}) (Result, error)
	MustUpdate(q query.Q, obj interface{}) Result
	Upsert(q query.Q, obj interface{}) (Result, error)
	MustUpsert(q query.Q, obj interface{}) Result
	Save(obj interface{}) (Result, error)
	MustSave(obj interface{}) Result
	DeleteFrom(t *Table, q query.Q) (Result, error)
	Delete(obj interface{}) error
	MustDelete(obj interface{})
	Begin() (*Tx, error)
}

Interface is implemented by both Orm and Transaction. This allows functions to receive an orm.Interface parameter and work with both transactions and outside of them. See the Orm documentation to find what each method does.

type Iter

type Iter struct {
	driver.Iter
	// contains filtered or unexported fields
}

func (*Iter) Assert

func (i *Iter) Assert()

Assert panics if the iter has an error. It's intended as a shorthand to save a few lines of code. For iterating over the results, a common pattern is:

for iter.Next(&obj) {
... do something with obj...
}
if err := iter.Err(); err != nil {
    panic(err)
}

With Assert() you can instead use this code and save a few keystrokes:

for iter.Next(&obj) {
... do something with obj...
}
iter.Assert()

func (*Iter) Close

func (i *Iter) Close() error

Close closes the iter. It's automatically called when the results are exhausted, but if you're ignoring some results you must call Close manually to avoid leaking resources. Close is idempotent.

func (*Iter) Err

func (i *Iter) Err() error

Err returns the first error returned by the iterator. Once there's an error, Next() will return false.

func (*Iter) Next

func (i *Iter) Next(out ...interface{}) bool

Next advances the iter to the next result, filling the fields in the out parameter. It returns true iff there was a result.

type JoinType

type JoinType int

func (JoinType) String

func (j JoinType) String() string

type Logger

type Logger interface {
	SetLogger(*log.Logger)
}

type Options

type Options struct {
	// The name to use when creating for the table
	// or collection. If no name is provided, it will
	// be derived from the package and type name.
	// Type Baz in package foo/bar will be named
	// foo_bar_baz, but types in the main package will
	// omit the package name (e.g. Foo becomes foo,
	// not main_foo).
	Table string
	// Name is the model name which is going to be registered
	// by default, it's the type name in its package. The
	// model name is used when specifying relations and when
	// disambiguating field names.
	Name string
	// Any indexes that can't be declared using field tags
	// (most of the time because they index multiple fields
	// or require special flags).
	Indexes []*index.Index
	// The primary key when it's not specified in struct tags
	// or when it's a composite key. The names of the fields
	// must be qualified names (i.e. the name of the field
	// in the Go struct). If the primary key is
	// defined in both the a field tag and using this field, an
	// error will be returned when registering the model.
	PrimaryKey []string
}

Options are the structure used to specify further options when registing a model.

type Orm

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

func New

func New(url *config.URL) (*Orm, error)

Open creates a new ORM using the specified configuration URL.

func (*Orm) All

func (o *Orm) All() *Query

All is a shorthand for Query(nil)

func (*Orm) Begin

func (o *Orm) Begin() (*Tx, error)

Begin starts a new transaction. If the driver does not support transactions, Begin will return a fake transaction.

func (*Orm) Close

func (o *Orm) Close() error

Close closes the database connection. Since the ORM is thread safe and does its own connection pooling you should tipycally never call this function. Instead, create a ORM instance when starting up your application and always use it.

func (*Orm) Count

func (o *Orm) Count(t *Table, q query.Q) (uint64, error)

Count is a shorthand for Table(t).Filter(q).Count() Pass nil to count all the objects in the given table.

func (*Orm) Delete

func (o *Orm) Delete(obj interface{}) error

Delete removes the given object, which must be of a type previously registered as a table and must have a primary key, either simple or composite.

func (*Orm) DeleteFrom

func (o *Orm) DeleteFrom(t *Table, q query.Q) (Result, error)

DeleteFrom removes all objects from the given table matching the query.

func (*Orm) Driver

func (o *Orm) Driver() driver.Driver

Driver returns the underlying driver.

func (*Orm) Exists

func (o *Orm) Exists(t *Table, q query.Q) (bool, error)

Exists is a shorthand for Table(t).Filter(q).Exists()

func (*Orm) Initialize

func (o *Orm) Initialize() error

Initialize is a low level function and should only be used when dealing with multiple ORM types. If you're only using the default ORM as returned by gnd.la/app.App.Orm() or gnd.la/app.Context.Orm() you should not call this function manually.

Initialize resolves model references and creates tables and indexes required by the registered models. You MUST call it AFTER all the models have been registered and BEFORE starting to use the ORM for queries for each ORM type.

func (*Orm) Insert

func (o *Orm) Insert(obj interface{}) (Result, error)

Insert saves an object into its collection. Its type must be previously registered as a model. If the model has an integer primary key with auto_increment, it will be be populated with the database assigned id.

func (*Orm) Logger

func (o *Orm) Logger() *log.Logger

Logger returns the logger for this ORM. By default, it's nil.

func (*Orm) MustBegin

func (o *Orm) MustBegin() *Tx

MustBegin works like Begin, but panics if there's an error.

func (*Orm) MustDelete

func (o *Orm) MustDelete(obj interface{})

MustDelete works like Delete, but panics if there's an error.

func (*Orm) MustInsert

func (o *Orm) MustInsert(obj interface{}) Result

MustInsert works like Insert, but panics if there's an error.

func (*Orm) MustOne

func (o *Orm) MustOne(q query.Q, out ...interface{}) bool

MustOne works like One, but panics if there's an error.

func (*Orm) MustOperate

func (o *Orm) MustOperate(table *Table, q query.Q, ops ...*operation.Operation) Result

func (*Orm) MustSave

func (o *Orm) MustSave(obj interface{}) Result

MustSave works like save, but panics if there's an error.

func (*Orm) MustUpdate

func (o *Orm) MustUpdate(q query.Q, obj interface{}) Result

MustUpdate works like update, but panics if there's an error.

func (*Orm) MustUpsert

func (o *Orm) MustUpsert(q query.Q, obj interface{}) Result

MustUpsert works like Upsert, but panics if there's an error.

func (*Orm) NameTable

func (o *Orm) NameTable(name string) *Table

NameTable returns the Table for the model with the given Name. Note that this is not the table name, but model name, provided in the Options.Name field. If no Name was provided in the Options for a given type, a name is assigned using the following rules:

  • Types in package main use the type name as is. type Something... in package main is named Something

  • Types in non-main packages use the fully qualified type name. type Something... in package foo/bar is named foo/bar.Something type Something... in package example.com/mypkg is named example.com/mypkg.Something

func (*Orm) One

func (o *Orm) One(q query.Q, out ...interface{}) (bool, error)

One is a shorthand for Query(q).One(&out)

func (*Orm) Operate

func (o *Orm) Operate(table *Table, q query.Q, ops ...*operation.Operation) (Result, error)

func (*Orm) Query

func (o *Orm) Query(q query.Q) *Query

Query returns a Query object, on which you can call Limit, Offset or Iter, to start iterating the results. If you want to iterate over all the items on a given table pass nil as the q argument. By default, the query will use the table of the first object passed to Next(), but you can override it using Table() (and you most do so for Count() and other functions which don't take objects).

func (*Orm) Register

func (o *Orm) Register(t interface{}, opts *Options) (*Table, error)

Register is considered a low-level function and should only be used if your app uses multiple ORM sources (e.g. Postgres and MongoDB). Most of the time, users should use orm.Register()

Register registers a struct for future usage with the ORMs with the same driver. If you're using ORM instances with different drivers you must register each object type with each driver by creating an ORM of each type, calling Register() and then Initialize. The first returned value is a Table object, which must be using when querying the ORM in cases when an object is not provided (like e.g. Count()). If you want to use the same type in multiple tables, you must register it for every table and then use the Table object returned to specify on which table you want to operate. If no table is specified, the first registered table will be used.

func (*Orm) Save

func (o *Orm) Save(obj interface{}) (Result, error)

Save takes an object, with its type registered as a model and either inserts it (if the primary key is zero or it has no primary key) or updates it using the primary key as the query (if it's non zero). If the update results in no affected rows, an insert will be performed. Save also supports models with composite keys. If any field forming the composite key is non-zero, an update will be tried before performing an insert.

func (*Orm) SetLogger

func (o *Orm) SetLogger(logger *log.Logger)

SetLogger sets the logger for this ORM. If the underlying driver implements the interface orm.Logger, the logger will be set for it too (the sql driver implements this interface).

func (*Orm) SqlDB

func (o *Orm) SqlDB() *sql.DB

SqlDB returns the underlying database connection iff the ORM driver is using database/sql. Otherwise, it returns nil. Note that the returned value isn't of type database/sql.DB, but gnd.la/orm/driver/sql.DB, which is a small compatibility wrapper around the former. See the gnd.la/orm/driver/sql.DB documentation for further information.

func (*Orm) Table

func (o *Orm) Table(t *Table) *Query

Table returns a Query object initialized with the given table. The Table object is returned when registering the model. If you need to obtain a Table from a model type or name, see Orm.TypeTable and orm.NamedTable.

func (*Orm) Transaction

func (o *Orm) Transaction(f func(o *Orm) error) error

Transaction runs the given function f inside a transaction. This interface is provided because some drivers (most of the NoSQL based) don't support the Begin/Commit interface and must run a transaction as a function. To return from f rolling back the transaction without generating an error return in Transaction, use Rollback. Returning any other error will cause the transaction to be rolled back and the error will be returned from Transaction. If no errors are returned from f, the transaction is commited and the only error that might be returned from Transaction will be one produced while committing.

func (*Orm) TypeTable

func (o *Orm) TypeTable(typ reflect.Type) *Table

TypeTable returns the Table for the given type, or nil if there's no such table.

func (*Orm) Update

func (o *Orm) Update(q query.Q, obj interface{}) (Result, error)

func (*Orm) Upsert

func (o *Orm) Upsert(q query.Q, obj interface{}) (Result, error)

Upsert tries to perform an update with the given query and object. If there are not affected rows, it performs an insert. Some drivers (like mongodb) are able to perform this operation in just one query, but most require two trips to the database.

type Query

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

func (*Query) All

func (q *Query) All(out ...interface{}) error

All returns all results for this query in slices. Arguments to All must be pointers to slices of elements. Basically, All is a shortcut for:

 var objs []*MyObject
 var obj *MyObject
 iter := some_query.Iter()
 for iter.Next(obj) {
	objs = append(objs, obj)
 }
 err := iter.Err()

Using All instead, we can do the same in this shorter way:

var objs []*MyObject
err := some_query.All(&objects)

Please, keep in mind that All will load all the objects into memory at the same time, so you shouldn't use it for large result sets.

func (*Query) Clone

func (q *Query) Clone() *Query

Clone returns a copy of the query.

func (*Query) Count

func (q *Query) Count() (uint64, error)

Count returns the number of results for the query. Note that you have to set the table manually before calling Count().

func (*Query) Exists

func (q *Query) Exists() (bool, error)

Exists returns wheter a result with the specified query exists.

func (*Query) Filter

func (q *Query) Filter(qu query.Q) *Query

Filter adds another condition to the query. In other words, it ANDs the previous condition with the one passed in.

func (*Query) Iter

func (q *Query) Iter() *Iter

Iter returns an Iter object which lets you iterate over the results produced by the query.

func (*Query) Join

func (q *Query) Join(jt JoinType) *Query

Join sets the default join type for this query. If not specifed, an INNER JOIN is performed. Note that not all drivers support RIGHT joins (e.g. sqlite).

func (*Query) Limit

func (q *Query) Limit(limit int) *Query

Limit sets the maximum number of results for the query.

func (*Query) MustAll

func (q *Query) MustAll(out ...interface{})

MustAll works like All, but panics if there's an error.

func (*Query) MustCount

func (q *Query) MustCount() uint64

MustCount works like Count, but panics if there's an error.

func (*Query) MustOne

func (q *Query) MustOne(out ...interface{}) bool

MustOne works like One, but panics if there's an error.

func (*Query) Offset

func (q *Query) Offset(offset int) *Query

Offset sets the offset for the query.

func (*Query) One

func (q *Query) One(out ...interface{}) (bool, error)

One fetches the first result for this query. The first return value indicates if a result was found.

func (*Query) Sort

func (q *Query) Sort(field string, dir Sort) *Query

Sort sets the field and direction used for sorting this query. To Sort by multiple fields, call Sort multiple times.

func (*Query) Table

func (q *Query) Table(t *Table) *Query

Table sets the table for the query. If the table was previously set, it's overridden. Rather than using strings to select tables, a Table object (which is returned from Register) is used. This way is not possible to mistype a table name, which avoids lots of errors.

type Result

type Result interface {
	LastInsertId() (int64, error)
	RowsAffected() (int64, error)
}

type Sort

type Sort int

type Table

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

func (*Table) Join

func (t *Table) Join(table *Table, q query.Q, jt JoinType) (*Table, error)

func (*Table) MustJoin

func (t *Table) MustJoin(table *Table, q query.Q, jt JoinType) *Table

func (*Table) Skip

func (t *Table) Skip() *Table

type Tx

type Tx struct {
	Orm
	// contains filtered or unexported fields
}

func (*Tx) Begin

func (t *Tx) Begin() (*Tx, error)

Begin just returns ErrInTransaction when called from a transaction.

func (*Tx) Close

func (t *Tx) Close()

Close finishes this transaction with a rollback if it hasn't been commited or rolled back yet. It's intended to be called using defer so you can cleanly release a transaction even if your code panics before commiting it. e.g.

 tx, err := o.Begin()
 if err != nil {
	panic(err)
 }
 defer tx.Close()
 // do some stuff with tx
 tx.MustCommit()

func (*Tx) Commit

func (t *Tx) Commit() error

Commit commits the current transaction. If the transaction was already committed or rolled back, it returns ErrFinished.

func (*Tx) MustCommit

func (t *Tx) MustCommit()

MustCommit works like Commit, but panics if there's an error.

func (*Tx) MustRollback

func (t *Tx) MustRollback()

MustRollback works like Rollback, but panics if there's an error.

func (*Tx) Rollback

func (t *Tx) Rollback() error

Rollback rolls back the current transaction. If the transaction was already committed or rolled back, it returns ErrFinished.

Directories

Path Synopsis
datastore
Package datastore implements an App Engine datastore driver the Gondola's ORM.
Package datastore implements an App Engine datastore driver the Gondola's ORM.
sql

Jump to

Keyboard shortcuts

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