beego: github.com/astaxie/beego/orm Index | Files

package orm

import "github.com/astaxie/beego/orm"

Package orm provide ORM for MySQL/PostgreSQL/sqlite Simple Usage

package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql" // import your used driver
)

// Model Struct
type User struct {
	Id   int    `orm:"auto"`
	Name string `orm:"size(100)"`
}

func init() {
	orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30)
}

func main() {
	o := orm.NewOrm()
	user := User{Name: "slene"}
	// insert
	id, err := o.Insert(&user)
	// update
	user.Name = "astaxie"
	num, err := o.Update(&user)
	// read one
	u := User{Id: user.Id}
	err = o.Read(&u)
	// delete
	num, err = o.Delete(&u)
}

more docs: http://beego.me/docs/mvc/model/overview.md

Index

Package Files

cmd.go cmd_utils.go db.go db_alias.go db_mysql.go db_oracle.go db_postgres.go db_sqlite.go db_tables.go db_tidb.go db_utils.go models.go models_boot.go models_fields.go models_info_f.go models_info_m.go models_utils.go orm.go orm_conds.go orm_log.go orm_object.go orm_querym2m.go orm_queryset.go orm_raw.go qb.go qb_mysql.go qb_tidb.go types.go utils.go

Constants

const (
    TypeBooleanField = 1 << iota
    TypeVarCharField
    TypeCharField
    TypeTextField
    TypeTimeField
    TypeDateField
    TypeDateTimeField
    TypeBitField
    TypeSmallIntegerField
    TypeIntegerField
    TypeBigIntegerField
    TypePositiveBitField
    TypePositiveSmallIntegerField
    TypePositiveIntegerField
    TypePositiveBigIntegerField
    TypeFloatField
    TypeDecimalField
    TypeJSONField
    TypeJsonbField
    RelForeignKey
    RelOneToOne
    RelManyToMany
    RelReverseOne
    RelReverseMany
)

Define the Type enum

const (
    IsIntegerField         = ^-TypePositiveBigIntegerField >> 6 << 7
    IsPositiveIntegerField = ^-TypePositiveBigIntegerField >> 10 << 11
    IsRelField             = ^-RelReverseMany >> 18 << 19
    IsFieldType            = ^-RelReverseMany<<1 + 1
)

Define some logic enum

const (
    ColAdd operator = iota
    ColMinus
    ColMultiply
    ColExcept
)

define Col operations

const CommaSpace = ", "

CommaSpace is the separation

const (
    DebugQueries = iota
)

DebugQueries define the debug

const (
    ExprSep = "__"
)

ExprSep define the expression separation

Variables

var (
    Debug            = false
    DebugLog         = NewLog(os.Stdout)
    DefaultRowsLimit = 1000
    DefaultRelsDepth = 2
    DefaultTimeLoc   = time.Local
    ErrTxHasBegan    = errors.New("<Ormer.Begin> transaction already begin")
    ErrTxDone        = errors.New("<Ormer.Commit/Rollback> transaction not begin")
    ErrMultiRows     = errors.New("<QuerySeter> return multi rows")
    ErrNoRows        = errors.New("<QuerySeter> no row found")
    ErrStmtClosed    = errors.New("<QuerySeter> stmt already closed")
    ErrArgs          = errors.New("<Ormer> args error may be empty")
    ErrNotImplement  = errors.New("have not implement")
)

Define common vars

var (
    // ErrMissPK missing pk error
    ErrMissPK = errors.New("missed pk value")
)
var (
    SnakeAcronymNameStrategy = "snakeStringWithAcronym"
)

func AddAliasWthDB Uses

func AddAliasWthDB(aliasName, driverName string, db *sql.DB) error

AddAliasWthDB add a aliasName for the drivename

func BootStrap Uses

func BootStrap()

BootStrap bootstrap models. make all model parsed and can not add more models

func ColValue Uses

func ColValue(opt operator, value interface{}) interface{}

ColValue do the field raw changes. e.g Nums = Nums + 10. usage:

Params{
	"Nums": ColValue(Col_Add, 10),
}

func GetDB Uses

func GetDB(aliasNames ...string) (*sql.DB, error)

GetDB Get *sql.DB from registered database by db alias name. Use "default" as alias name if you not set.

func RegisterDataBase Uses

func RegisterDataBase(aliasName, driverName, dataSource string, params ...int) error

RegisterDataBase Setting the database connect params. Use the database driver self dataSource args.

func RegisterDriver Uses

func RegisterDriver(driverName string, typ DriverType) error

RegisterDriver Register a database driver use specify driver name, this can be definition the driver is which database type.

func RegisterModel Uses

func RegisterModel(models ...interface{})

RegisterModel register models

func RegisterModelWithPrefix Uses

func RegisterModelWithPrefix(prefix string, models ...interface{})

RegisterModelWithPrefix register models with a prefix

func RegisterModelWithSuffix Uses

func RegisterModelWithSuffix(suffix string, models ...interface{})

RegisterModelWithSuffix register models with a suffix

func ResetModelCache Uses

func ResetModelCache()

ResetModelCache Clean model cache. Then you can re-RegisterModel. Common use this api for test case.

func RunCommand Uses

func RunCommand()

RunCommand listen for orm command and then run it if command arguments passed.

func RunSyncdb Uses

func RunSyncdb(name string, force bool, verbose bool) error

RunSyncdb run syncdb command line. name means table's alias name. default is "default". force means run next sql if the current is error. verbose means show all info when running command or not.

func SetDataBaseTZ Uses

func SetDataBaseTZ(aliasName string, tz *time.Location) error

SetDataBaseTZ Change the database default used timezone

func SetMaxIdleConns Uses

func SetMaxIdleConns(aliasName string, maxIdleConns int)

SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name

func SetMaxOpenConns Uses

func SetMaxOpenConns(aliasName string, maxOpenConns int)

SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name

func SetNameStrategy Uses

func SetNameStrategy(s string)

SetNameStrategy set different name strategy

func ToInt64 Uses

func ToInt64(value interface{}) (d int64)

ToInt64 interface to int64

func ToStr Uses

func ToStr(value interface{}, args ...int) (s string)

ToStr interface to string

type BigIntegerField Uses

type BigIntegerField int64

BigIntegerField -9223372036854775808 to 9223372036854775807.

func (*BigIntegerField) FieldType Uses

func (e *BigIntegerField) FieldType() int

FieldType return enum type

func (*BigIntegerField) RawValue Uses

func (e *BigIntegerField) RawValue() interface{}

RawValue return BigIntegerField value

func (*BigIntegerField) Set Uses

func (e *BigIntegerField) Set(d int64)

Set the BigIntegerField value

func (*BigIntegerField) SetRaw Uses

func (e *BigIntegerField) SetRaw(value interface{}) error

SetRaw convert interface int64/string to int64

func (*BigIntegerField) String Uses

func (e *BigIntegerField) String() string

String convert BigIntegerField to string

func (BigIntegerField) Value Uses

func (e BigIntegerField) Value() int64

Value return int64

type BooleanField Uses

type BooleanField bool

BooleanField A true/false field.

func (*BooleanField) FieldType Uses

func (e *BooleanField) FieldType() int

FieldType return BooleanField the type

func (*BooleanField) RawValue Uses

func (e *BooleanField) RawValue() interface{}

RawValue return the current value

func (*BooleanField) Set Uses

func (e *BooleanField) Set(d bool)

Set will set the BooleanField

func (*BooleanField) SetRaw Uses

func (e *BooleanField) SetRaw(value interface{}) error

SetRaw set the interface to bool

func (*BooleanField) String Uses

func (e *BooleanField) String() string

String format the Bool to string

func (BooleanField) Value Uses

func (e BooleanField) Value() bool

Value return the BooleanField

type CharField Uses

type CharField string

CharField A string field required values tag: size The size is enforced at the database level and in models’s validation. eg: `orm:"size(120)"`

func (*CharField) FieldType Uses

func (e *CharField) FieldType() int

FieldType return the enum type

func (*CharField) RawValue Uses

func (e *CharField) RawValue() interface{}

RawValue return the CharField value

func (*CharField) Set Uses

func (e *CharField) Set(d string)

Set CharField value

func (*CharField) SetRaw Uses

func (e *CharField) SetRaw(value interface{}) error

SetRaw set the interface to string

func (*CharField) String Uses

func (e *CharField) String() string

String return the CharField

func (CharField) Value Uses

func (e CharField) Value() string

Value return the CharField's Value

type Condition Uses

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

Condition struct. work for WHERE conditions.

func NewCondition Uses

func NewCondition() *Condition

NewCondition return new condition struct

func (Condition) And Uses

func (c Condition) And(expr string, args ...interface{}) *Condition

And add expression to condition

func (*Condition) AndCond Uses

func (c *Condition) AndCond(cond *Condition) *Condition

AndCond combine a condition to current condition

func (Condition) AndNot Uses

func (c Condition) AndNot(expr string, args ...interface{}) *Condition

AndNot add NOT expression to condition

func (*Condition) AndNotCond Uses

func (c *Condition) AndNotCond(cond *Condition) *Condition

AndNotCond combine a AND NOT condition to current condition

func (*Condition) IsEmpty Uses

func (c *Condition) IsEmpty() bool

IsEmpty check the condition arguments are empty or not.

func (Condition) Or Uses

func (c Condition) Or(expr string, args ...interface{}) *Condition

Or add OR expression to condition

func (*Condition) OrCond Uses

func (c *Condition) OrCond(cond *Condition) *Condition

OrCond combine a OR condition to current condition

func (Condition) OrNot Uses

func (c Condition) OrNot(expr string, args ...interface{}) *Condition

OrNot add OR NOT expression to condition

func (*Condition) OrNotCond Uses

func (c *Condition) OrNotCond(cond *Condition) *Condition

OrNotCond combine a OR NOT condition to current condition

func (Condition) Raw Uses

func (c Condition) Raw(expr string, sql string) *Condition

Raw add raw sql to condition

type DateField Uses

type DateField time.Time

DateField A date, represented in go by a time.Time instance. only date values like 2006-01-02 Has a few extra, optional attr tag:

auto_now: Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

auto_now_add: Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override.

eg: `orm:"auto_now"` or `orm:"auto_now_add"`

func (*DateField) FieldType Uses

func (e *DateField) FieldType() int

FieldType return enum type Date

func (*DateField) RawValue Uses

func (e *DateField) RawValue() interface{}

RawValue return Date value

func (*DateField) Set Uses

func (e *DateField) Set(d time.Time)

Set set the DateField's value

func (*DateField) SetRaw Uses

func (e *DateField) SetRaw(value interface{}) error

SetRaw convert the interface to time.Time. Allow string and time.Time

func (*DateField) String Uses

func (e *DateField) String() string

String convert datetime to string

func (DateField) Value Uses

func (e DateField) Value() time.Time

Value return the time.Time

type DateTimeField Uses

type DateTimeField time.Time

DateTimeField A date, represented in go by a time.Time instance. datetime values like 2006-01-02 15:04:05 Takes the same extra arguments as DateField.

func (*DateTimeField) FieldType Uses

func (e *DateTimeField) FieldType() int

FieldType return the enum TypeDateTimeField

func (*DateTimeField) RawValue Uses

func (e *DateTimeField) RawValue() interface{}

RawValue return the datetime value

func (*DateTimeField) Set Uses

func (e *DateTimeField) Set(d time.Time)

Set set the time.Time to datetime

func (*DateTimeField) SetRaw Uses

func (e *DateTimeField) SetRaw(value interface{}) error

SetRaw convert the string or time.Time to DateTimeField

func (*DateTimeField) String Uses

func (e *DateTimeField) String() string

String return the time's String

func (DateTimeField) Value Uses

func (e DateTimeField) Value() time.Time

Value return the datetime value

type Driver Uses

type Driver interface {
    Name() string
    Type() DriverType
}

Driver define database driver

type DriverType Uses

type DriverType int

DriverType database driver constant int.

const (
    DRMySQL    DriverType // mysql
    DRSqlite              // sqlite
    DROracle              // oracle
    DRPostgres            // pgsql
    DRTiDB                // TiDB
)

Enum the Database driver

type Fielder Uses

type Fielder interface {
    String() string
    FieldType() int
    SetRaw(interface{}) error
    RawValue() interface{}
}

Fielder define field info

type FloatField Uses

type FloatField float64

FloatField A floating-point number represented in go by a float32 value.

func (*FloatField) FieldType Uses

func (e *FloatField) FieldType() int

FieldType return the enum type

func (*FloatField) RawValue Uses

func (e *FloatField) RawValue() interface{}

RawValue return the FloatField value

func (*FloatField) Set Uses

func (e *FloatField) Set(d float64)

Set the Float64

func (*FloatField) SetRaw Uses

func (e *FloatField) SetRaw(value interface{}) error

SetRaw converter interface Float64 float32 or string to FloatField

func (*FloatField) String Uses

func (e *FloatField) String() string

String return the string

func (FloatField) Value Uses

func (e FloatField) Value() float64

Value return the FloatField value

type Inserter Uses

type Inserter interface {
    Insert(interface{}) (int64, error)
    Close() error
}

Inserter insert prepared statement

type IntegerField Uses

type IntegerField int32

IntegerField -2147483648 to 2147483647

func (*IntegerField) FieldType Uses

func (e *IntegerField) FieldType() int

FieldType return the enum type

func (*IntegerField) RawValue Uses

func (e *IntegerField) RawValue() interface{}

RawValue return IntegerField value

func (*IntegerField) Set Uses

func (e *IntegerField) Set(d int32)

Set IntegerField value

func (*IntegerField) SetRaw Uses

func (e *IntegerField) SetRaw(value interface{}) error

SetRaw convert interface int32/string to int32

func (*IntegerField) String Uses

func (e *IntegerField) String() string

String convert Int32 to string

func (IntegerField) Value Uses

func (e IntegerField) Value() int32

Value return the int32

type JSONField Uses

type JSONField string

JSONField postgres json field.

func (*JSONField) FieldType Uses

func (j *JSONField) FieldType() int

FieldType return enum type

func (*JSONField) RawValue Uses

func (j *JSONField) RawValue() interface{}

RawValue return JSONField value

func (*JSONField) Set Uses

func (j *JSONField) Set(d string)

Set the JSONField value

func (*JSONField) SetRaw Uses

func (j *JSONField) SetRaw(value interface{}) error

SetRaw convert interface string to string

func (*JSONField) String Uses

func (j *JSONField) String() string

String convert JSONField to string

func (JSONField) Value Uses

func (j JSONField) Value() string

Value return JSONField value

type JsonbField Uses

type JsonbField string

JsonbField postgres json field.

func (*JsonbField) FieldType Uses

func (j *JsonbField) FieldType() int

FieldType return enum type

func (*JsonbField) RawValue Uses

func (j *JsonbField) RawValue() interface{}

RawValue return JsonbField value

func (*JsonbField) Set Uses

func (j *JsonbField) Set(d string)

Set the JsonbField value

func (*JsonbField) SetRaw Uses

func (j *JsonbField) SetRaw(value interface{}) error

SetRaw convert interface string to string

func (*JsonbField) String Uses

func (j *JsonbField) String() string

String convert JsonbField to string

func (JsonbField) Value Uses

func (j JsonbField) Value() string

Value return JsonbField value

type Log Uses

type Log struct {
    *log.Logger
}

Log implement the log.Logger

func NewLog Uses

func NewLog(out io.Writer) *Log

NewLog set io.Writer to create a Logger.

type MySQLQueryBuilder Uses

type MySQLQueryBuilder struct {
    Tokens []string
}

MySQLQueryBuilder is the SQL build

func (*MySQLQueryBuilder) And Uses

func (qb *MySQLQueryBuilder) And(cond string) QueryBuilder

And join the and cond

func (*MySQLQueryBuilder) Asc Uses

func (qb *MySQLQueryBuilder) Asc() QueryBuilder

Asc join the asc

func (*MySQLQueryBuilder) Delete Uses

func (qb *MySQLQueryBuilder) Delete(tables ...string) QueryBuilder

Delete join the Delete tables

func (*MySQLQueryBuilder) Desc Uses

func (qb *MySQLQueryBuilder) Desc() QueryBuilder

Desc join the desc

func (*MySQLQueryBuilder) ForUpdate Uses

func (qb *MySQLQueryBuilder) ForUpdate() QueryBuilder

ForUpdate add the FOR UPDATE clause

func (*MySQLQueryBuilder) From Uses

func (qb *MySQLQueryBuilder) From(tables ...string) QueryBuilder

From join the tables

func (*MySQLQueryBuilder) GroupBy Uses

func (qb *MySQLQueryBuilder) GroupBy(fields ...string) QueryBuilder

GroupBy join the Group by fields

func (*MySQLQueryBuilder) Having Uses

func (qb *MySQLQueryBuilder) Having(cond string) QueryBuilder

Having join the Having cond

func (*MySQLQueryBuilder) In Uses

func (qb *MySQLQueryBuilder) In(vals ...string) QueryBuilder

In join the IN (vals)

func (*MySQLQueryBuilder) InnerJoin Uses

func (qb *MySQLQueryBuilder) InnerJoin(table string) QueryBuilder

InnerJoin INNER JOIN the table

func (*MySQLQueryBuilder) InsertInto Uses

func (qb *MySQLQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder

InsertInto join the insert SQL

func (*MySQLQueryBuilder) LeftJoin Uses

func (qb *MySQLQueryBuilder) LeftJoin(table string) QueryBuilder

LeftJoin LEFT JOIN the table

func (*MySQLQueryBuilder) Limit Uses

func (qb *MySQLQueryBuilder) Limit(limit int) QueryBuilder

Limit join the limit num

func (*MySQLQueryBuilder) Offset Uses

func (qb *MySQLQueryBuilder) Offset(offset int) QueryBuilder

Offset join the offset num

func (*MySQLQueryBuilder) On Uses

func (qb *MySQLQueryBuilder) On(cond string) QueryBuilder

On join with on cond

func (*MySQLQueryBuilder) Or Uses

func (qb *MySQLQueryBuilder) Or(cond string) QueryBuilder

Or join the or cond

func (*MySQLQueryBuilder) OrderBy Uses

func (qb *MySQLQueryBuilder) OrderBy(fields ...string) QueryBuilder

OrderBy join the Order by fields

func (*MySQLQueryBuilder) RightJoin Uses

func (qb *MySQLQueryBuilder) RightJoin(table string) QueryBuilder

RightJoin RIGHT JOIN the table

func (*MySQLQueryBuilder) Select Uses

func (qb *MySQLQueryBuilder) Select(fields ...string) QueryBuilder

Select will join the fields

func (*MySQLQueryBuilder) Set Uses

func (qb *MySQLQueryBuilder) Set(kv ...string) QueryBuilder

Set join the set kv

func (*MySQLQueryBuilder) String Uses

func (qb *MySQLQueryBuilder) String() string

String join all Tokens

func (*MySQLQueryBuilder) Subquery Uses

func (qb *MySQLQueryBuilder) Subquery(sub string, alias string) string

Subquery join the sub as alias

func (*MySQLQueryBuilder) Update Uses

func (qb *MySQLQueryBuilder) Update(tables ...string) QueryBuilder

Update join the update table

func (*MySQLQueryBuilder) Values Uses

func (qb *MySQLQueryBuilder) Values(vals ...string) QueryBuilder

Values join the Values(vals)

func (*MySQLQueryBuilder) Where Uses

func (qb *MySQLQueryBuilder) Where(cond string) QueryBuilder

Where join the Where cond

type Ormer Uses

type Ormer interface {
    // read data to model
    // for example:
    //	this will find User by Id field
    // 	u = &User{Id: user.Id}
    // 	err = Ormer.Read(u)
    //	this will find User by UserName field
    // 	u = &User{UserName: "astaxie", Password: "pass"}
    //	err = Ormer.Read(u, "UserName")
    Read(md interface{}, cols ...string) error
    // Like Read(), but with "FOR UPDATE" clause, useful in transaction.
    // Some databases are not support this feature.
    ReadForUpdate(md interface{}, cols ...string) error
    // Try to read a row from the database, or insert one if it doesn't exist
    ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error)
    // insert model data to database
    // for example:
    //  user := new(User)
    //  id, err = Ormer.Insert(user)
    //  user must a pointer and Insert will set user's pk field
    Insert(interface{}) (int64, error)
    // mysql:InsertOrUpdate(model) or InsertOrUpdate(model,"colu=colu+value")
    // if colu type is integer : can use(+-*/), string : convert(colu,"value")
    // postgres: InsertOrUpdate(model,"conflictColumnName") or InsertOrUpdate(model,"conflictColumnName","colu=colu+value")
    // if colu type is integer : can use(+-*/), string : colu || "value"
    InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error)
    // insert some models to database
    InsertMulti(bulk int, mds interface{}) (int64, error)
    // update model to database.
    // cols set the columns those want to update.
    // find model by Id(pk) field and update columns specified by fields, if cols is null then update all columns
    // for example:
    // user := User{Id: 2}
    //	user.Langs = append(user.Langs, "zh-CN", "en-US")
    //	user.Extra.Name = "beego"
    //	user.Extra.Data = "orm"
    //	num, err = Ormer.Update(&user, "Langs", "Extra")
    Update(md interface{}, cols ...string) (int64, error)
    // delete model in database
    Delete(md interface{}, cols ...string) (int64, error)
    // load related models to md model.
    // args are limit, offset int and order string.
    //
    // example:
    // 	Ormer.LoadRelated(post,"Tags")
    // 	for _,tag := range post.Tags{...}
    //args[0] bool true useDefaultRelsDepth ; false  depth 0
    //args[0] int  loadRelationDepth
    //args[1] int limit default limit 1000
    //args[2] int offset default offset 0
    //args[3] string order  for example : "-Id"
    // make sure the relation is defined in model struct tags.
    LoadRelated(md interface{}, name string, args ...interface{}) (int64, error)
    // create a models to models queryer
    // for example:
    // 	post := Post{Id: 4}
    // 	m2m := Ormer.QueryM2M(&post, "Tags")
    QueryM2M(md interface{}, name string) QueryM2Mer
    // return a QuerySeter for table operations.
    // table name can be string or struct.
    // e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)),
    QueryTable(ptrStructOrTableName interface{}) QuerySeter
    // switch to another registered database driver by given name.
    Using(name string) error
    // begin transaction
    // for example:
    // 	o := NewOrm()
    // 	err := o.Begin()
    // 	...
    // 	err = o.Rollback()
    Begin() error
    // begin transaction with provided context and option
    // the provided context is used until the transaction is committed or rolled back.
    // if the context is canceled, the transaction will be rolled back.
    // the provided TxOptions is optional and may be nil if defaults should be used.
    // if a non-default isolation level is used that the driver doesn't support, an error will be returned.
    // for example:
    //  o := NewOrm()
    // 	err := o.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
    //  ...
    //  err = o.Rollback()
    BeginTx(ctx context.Context, opts *sql.TxOptions) error
    // commit transaction
    Commit() error
    // rollback transaction
    Rollback() error
    // return a raw query seter for raw sql string.
    // for example:
    //	 ormer.Raw("UPDATE `user` SET `user_name` = ? WHERE `user_name` = ?", "slene", "testing").Exec()
    //	// update user testing's name to slene
    Raw(query string, args ...interface{}) RawSeter
    Driver() Driver
}

Ormer define the orm interface

func NewOrm Uses

func NewOrm() Ormer

NewOrm create new orm

func NewOrmWithDB Uses

func NewOrmWithDB(driverName, aliasName string, db *sql.DB) (Ormer, error)

NewOrmWithDB create a new ormer object with specify *sql.DB for query

type Params Uses

type Params map[string]interface{}

Params stores the Params

type ParamsList Uses

type ParamsList []interface{}

ParamsList stores paramslist

type PositiveBigIntegerField Uses

type PositiveBigIntegerField uint64

PositiveBigIntegerField 0 to 18446744073709551615

func (*PositiveBigIntegerField) FieldType Uses

func (e *PositiveBigIntegerField) FieldType() int

FieldType return enum type

func (*PositiveBigIntegerField) RawValue Uses

func (e *PositiveBigIntegerField) RawValue() interface{}

RawValue return PositiveBigIntegerField value

func (*PositiveBigIntegerField) Set Uses

func (e *PositiveBigIntegerField) Set(d uint64)

Set PositiveBigIntegerField value

func (*PositiveBigIntegerField) SetRaw Uses

func (e *PositiveBigIntegerField) SetRaw(value interface{}) error

SetRaw convert interface uint64/string to Uint64

func (*PositiveBigIntegerField) String Uses

func (e *PositiveBigIntegerField) String() string

String convert PositiveBigIntegerField to string

func (PositiveBigIntegerField) Value Uses

func (e PositiveBigIntegerField) Value() uint64

Value return uint64

type PositiveIntegerField Uses

type PositiveIntegerField uint32

PositiveIntegerField 0 to 4294967295

func (*PositiveIntegerField) FieldType Uses

func (e *PositiveIntegerField) FieldType() int

FieldType return enum type

func (*PositiveIntegerField) RawValue Uses

func (e *PositiveIntegerField) RawValue() interface{}

RawValue return the PositiveIntegerField Value

func (*PositiveIntegerField) Set Uses

func (e *PositiveIntegerField) Set(d uint32)

Set the PositiveIntegerField value

func (*PositiveIntegerField) SetRaw Uses

func (e *PositiveIntegerField) SetRaw(value interface{}) error

SetRaw convert interface uint32/string to Uint32

func (*PositiveIntegerField) String Uses

func (e *PositiveIntegerField) String() string

String convert PositiveIntegerField to string

func (PositiveIntegerField) Value Uses

func (e PositiveIntegerField) Value() uint32

Value return PositiveIntegerField value. Uint32

type PositiveSmallIntegerField Uses

type PositiveSmallIntegerField uint16

PositiveSmallIntegerField 0 to 65535

func (*PositiveSmallIntegerField) FieldType Uses

func (e *PositiveSmallIntegerField) FieldType() int

FieldType return enum type

func (*PositiveSmallIntegerField) RawValue Uses

func (e *PositiveSmallIntegerField) RawValue() interface{}

RawValue returns PositiveSmallIntegerField value

func (*PositiveSmallIntegerField) Set Uses

func (e *PositiveSmallIntegerField) Set(d uint16)

Set PositiveSmallIntegerField value

func (*PositiveSmallIntegerField) SetRaw Uses

func (e *PositiveSmallIntegerField) SetRaw(value interface{}) error

SetRaw convert Interface uint16/string to uint16

func (*PositiveSmallIntegerField) String Uses

func (e *PositiveSmallIntegerField) String() string

String convert uint16 to string

func (PositiveSmallIntegerField) Value Uses

func (e PositiveSmallIntegerField) Value() uint16

Value return uint16

type QueryBuilder Uses

type QueryBuilder interface {
    Select(fields ...string) QueryBuilder
    ForUpdate() QueryBuilder
    From(tables ...string) QueryBuilder
    InnerJoin(table string) QueryBuilder
    LeftJoin(table string) QueryBuilder
    RightJoin(table string) QueryBuilder
    On(cond string) QueryBuilder
    Where(cond string) QueryBuilder
    And(cond string) QueryBuilder
    Or(cond string) QueryBuilder
    In(vals ...string) QueryBuilder
    OrderBy(fields ...string) QueryBuilder
    Asc() QueryBuilder
    Desc() QueryBuilder
    Limit(limit int) QueryBuilder
    Offset(offset int) QueryBuilder
    GroupBy(fields ...string) QueryBuilder
    Having(cond string) QueryBuilder
    Update(tables ...string) QueryBuilder
    Set(kv ...string) QueryBuilder
    Delete(tables ...string) QueryBuilder
    InsertInto(table string, fields ...string) QueryBuilder
    Values(vals ...string) QueryBuilder
    Subquery(sub string, alias string) string
    String() string
}

QueryBuilder is the Query builder interface

func NewQueryBuilder Uses

func NewQueryBuilder(driver string) (qb QueryBuilder, err error)

NewQueryBuilder return the QueryBuilder

type QueryM2Mer Uses

type QueryM2Mer interface {
    // add models to origin models when creating queryM2M.
    // example:
    // 	m2m := orm.QueryM2M(post,"Tag")
    // 	m2m.Add(&Tag1{},&Tag2{})
    //  	for _,tag := range post.Tags{}{ ... }
    // param could also be any of the follow
    // 	[]*Tag{{Id:3,Name: "TestTag1"}, {Id:4,Name: "TestTag2"}}
    //	&Tag{Id:5,Name: "TestTag3"}
    //	[]interface{}{&Tag{Id:6,Name: "TestTag4"}}
    // insert one or more rows to m2m table
    // make sure the relation is defined in post model struct tag.
    Add(...interface{}) (int64, error)
    // remove models following the origin model relationship
    // only delete rows from m2m table
    // for example:
    //tag3 := &Tag{Id:5,Name: "TestTag3"}
    //num, err = m2m.Remove(tag3)
    Remove(...interface{}) (int64, error)
    // check model is existed in relationship of origin model
    Exist(interface{}) bool
    // clean all models in related of origin model
    Clear() (int64, error)
    // count all related models of origin model
    Count() (int64, error)
}

QueryM2Mer model to model query struct all operations are on the m2m table only, will not affect the origin model table

type QuerySeter Uses

type QuerySeter interface {
    // add condition expression to QuerySeter.
    // for example:
    //	filter by UserName == 'slene'
    //	qs.Filter("UserName", "slene")
    //	sql : left outer join profile on t0.id1==t1.id2 where t1.age == 28
    //	Filter("profile__Age", 28)
    // 	 // time compare
    //	qs.Filter("created", time.Now())
    Filter(string, ...interface{}) QuerySeter
    // add raw sql to querySeter.
    // for example:
    // qs.FilterRaw("user_id IN (SELECT id FROM profile WHERE age>=18)")
    // //sql-> WHERE user_id IN (SELECT id FROM profile WHERE age>=18)
    FilterRaw(string, string) QuerySeter
    // add NOT condition to querySeter.
    // have the same usage as Filter
    Exclude(string, ...interface{}) QuerySeter
    // set condition to QuerySeter.
    // sql's where condition
    //	cond := orm.NewCondition()
    //	cond1 := cond.And("profile__isnull", false).AndNot("status__in", 1).Or("profile__age__gt", 2000)
    //	//sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` >  2000
    //	num, err := qs.SetCond(cond1).Count()
    SetCond(*Condition) QuerySeter
    // get condition from QuerySeter.
    // sql's where condition
    //  cond := orm.NewCondition()
    //  cond = cond.And("profile__isnull", false).AndNot("status__in", 1)
    //  qs = qs.SetCond(cond)
    //  cond = qs.GetCond()
    //  cond := cond.Or("profile__age__gt", 2000)
    //  //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` >  2000
    //  num, err := qs.SetCond(cond).Count()
    GetCond() *Condition
    // add LIMIT value.
    // args[0] means offset, e.g. LIMIT num,offset.
    // if Limit <= 0 then Limit will be set to default limit ,eg 1000
    // if QuerySeter doesn't call Limit, the sql's Limit will be set to default limit, eg 1000
    //  for example:
    //	qs.Limit(10, 2)
    //	// sql-> limit 10 offset 2
    Limit(limit interface{}, args ...interface{}) QuerySeter
    // add OFFSET value
    // same as Limit function's args[0]
    Offset(offset interface{}) QuerySeter
    // add GROUP BY expression
    // for example:
    //	qs.GroupBy("id")
    GroupBy(exprs ...string) QuerySeter
    // add ORDER expression.
    // "column" means ASC, "-column" means DESC.
    // for example:
    //	qs.OrderBy("-status")
    OrderBy(exprs ...string) QuerySeter
    // set relation model to query together.
    // it will query relation models and assign to parent model.
    // for example:
    //	// will load all related fields use left join .
    // 	qs.RelatedSel().One(&user)
    //	// will  load related field only profile
    //	qs.RelatedSel("profile").One(&user)
    //	user.Profile.Age = 32
    RelatedSel(params ...interface{}) QuerySeter
    // Set Distinct
    // for example:
    //  o.QueryTable("policy").Filter("Groups__Group__Users__User", user).
    //    Distinct().
    //    All(&permissions)
    Distinct() QuerySeter
    // set FOR UPDATE to query.
    // for example:
    //  o.QueryTable("user").Filter("uid", uid).ForUpdate().All(&users)
    ForUpdate() QuerySeter
    // return QuerySeter execution result number
    // for example:
    //	num, err = qs.Filter("profile__age__gt", 28).Count()
    Count() (int64, error)
    // check result empty or not after QuerySeter executed
    // the same as QuerySeter.Count > 0
    Exist() bool
    // execute update with parameters
    // for example:
    //	num, err = qs.Filter("user_name", "slene").Update(Params{
    //		"Nums": ColValue(Col_Minus, 50),
    //	}) // user slene's Nums will minus 50
    //	num, err = qs.Filter("UserName", "slene").Update(Params{
    //		"user_name": "slene2"
    //	}) // user slene's  name will change to slene2
    Update(values Params) (int64, error)
    // delete from table
    //for example:
    //	num ,err = qs.Filter("user_name__in", "testing1", "testing2").Delete()
    // 	//delete two user  who's name is testing1 or testing2
    Delete() (int64, error)
    // return a insert queryer.
    // it can be used in times.
    // example:
    // 	i,err := sq.PrepareInsert()
    // 	num, err = i.Insert(&user1) // user table will add one record user1 at once
    //	num, err = i.Insert(&user2) // user table will add one record user2 at once
    //	err = i.Close() //don't forget call Close
    PrepareInsert() (Inserter, error)
    // query all data and map to containers.
    // cols means the columns when querying.
    // for example:
    //	var users []*User
    //	qs.All(&users) // users[0],users[1],users[2] ...
    All(container interface{}, cols ...string) (int64, error)
    // query one row data and map to containers.
    // cols means the columns when querying.
    // for example:
    //	var user User
    //	qs.One(&user) //user.UserName == "slene"
    One(container interface{}, cols ...string) error
    // query all data and map to []map[string]interface.
    // expres means condition expression.
    // it converts data to []map[column]value.
    // for example:
    //	var maps []Params
    //	qs.Values(&maps) //maps[0]["UserName"]=="slene"
    Values(results *[]Params, exprs ...string) (int64, error)
    // query all data and map to [][]interface
    // it converts data to [][column_index]value
    // for example:
    //	var list []ParamsList
    //	qs.ValuesList(&list) // list[0][1] == "slene"
    ValuesList(results *[]ParamsList, exprs ...string) (int64, error)
    // query all data and map to []interface.
    // it's designed for one column record set, auto change to []value, not [][column]value.
    // for example:
    //	var list ParamsList
    //	qs.ValuesFlat(&list, "UserName") // list[0] == "slene"
    ValuesFlat(result *ParamsList, expr string) (int64, error)
    // query all rows into map[string]interface with specify key and value column name.
    // keyCol = "name", valueCol = "value"
    // table data
    // name  | value
    // total | 100
    // found | 200
    // to map[string]interface{}{
    // 	"total": 100,
    // 	"found": 200,
    // }
    RowsToMap(result *Params, keyCol, valueCol string) (int64, error)
    // query all rows into struct with specify key and value column name.
    // keyCol = "name", valueCol = "value"
    // table data
    // name  | value
    // total | 100
    // found | 200
    // to struct {
    // 	Total int
    // 	Found int
    // }
    RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error)
}

QuerySeter query seter

type RawPreparer Uses

type RawPreparer interface {
    Exec(...interface{}) (sql.Result, error)
    Close() error
}

RawPreparer raw query statement

type RawSeter Uses

type RawSeter interface {
    //execute sql and get result
    Exec() (sql.Result, error)
    //query data and map to container
    //for example:
    //	var name string
    //	var id int
    //	rs.QueryRow(&id,&name) // id==2 name=="slene"
    QueryRow(containers ...interface{}) error

    // query data rows and map to container
    //	var ids []int
    //	var names []int
    //	query = fmt.Sprintf("SELECT 'id','name' FROM %suser%s", Q, Q)
    //	num, err = dORM.Raw(query).QueryRows(&ids,&names) // ids=>{1,2},names=>{"nobody","slene"}
    QueryRows(containers ...interface{}) (int64, error)
    SetArgs(...interface{}) RawSeter
    // query data to []map[string]interface
    // see QuerySeter's Values
    Values(container *[]Params, cols ...string) (int64, error)
    // query data to [][]interface
    // see QuerySeter's ValuesList
    ValuesList(container *[]ParamsList, cols ...string) (int64, error)
    // query data to []interface
    // see QuerySeter's ValuesFlat
    ValuesFlat(container *ParamsList, cols ...string) (int64, error)
    // query all rows into map[string]interface with specify key and value column name.
    // keyCol = "name", valueCol = "value"
    // table data
    // name  | value
    // total | 100
    // found | 200
    // to map[string]interface{}{
    // 	"total": 100,
    // 	"found": 200,
    // }
    RowsToMap(result *Params, keyCol, valueCol string) (int64, error)
    // query all rows into struct with specify key and value column name.
    // keyCol = "name", valueCol = "value"
    // table data
    // name  | value
    // total | 100
    // found | 200
    // to struct {
    // 	Total int
    // 	Found int
    // }
    RowsToStruct(ptrStruct interface{}, keyCol, valueCol string) (int64, error)

    // return prepared raw statement for used in times.
    // for example:
    // 	pre, err := dORM.Raw("INSERT INTO tag (name) VALUES (?)").Prepare()
    // 	r, err := pre.Exec("name1") // INSERT INTO tag (name) VALUES (`name1`)
    Prepare() (RawPreparer, error)
}

RawSeter raw query seter create From Ormer.Raw for example:

sql := fmt.Sprintf("SELECT %sid%s,%sname%s FROM %suser%s WHERE id = ?",Q,Q,Q,Q,Q,Q)
rs := Ormer.Raw(sql, 1)

type SmallIntegerField Uses

type SmallIntegerField int16

SmallIntegerField -32768 to 32767

func (*SmallIntegerField) FieldType Uses

func (e *SmallIntegerField) FieldType() int

FieldType return enum type SmallIntegerField

func (*SmallIntegerField) RawValue Uses

func (e *SmallIntegerField) RawValue() interface{}

RawValue return smallint value

func (*SmallIntegerField) Set Uses

func (e *SmallIntegerField) Set(d int16)

Set the SmallIntegerField value

func (*SmallIntegerField) SetRaw Uses

func (e *SmallIntegerField) SetRaw(value interface{}) error

SetRaw convert interface int16/string to int16

func (*SmallIntegerField) String Uses

func (e *SmallIntegerField) String() string

String convert smallint to string

func (SmallIntegerField) Value Uses

func (e SmallIntegerField) Value() int16

Value return int16 value

type StrTo Uses

type StrTo string

StrTo is the target string

func (StrTo) Bool Uses

func (f StrTo) Bool() (bool, error)

Bool string to bool

func (*StrTo) Clear Uses

func (f *StrTo) Clear()

Clear string

func (StrTo) Exist Uses

func (f StrTo) Exist() bool

Exist check string exist

func (StrTo) Float32 Uses

func (f StrTo) Float32() (float32, error)

Float32 string to float32

func (StrTo) Float64 Uses

func (f StrTo) Float64() (float64, error)

Float64 string to float64

func (StrTo) Int Uses

func (f StrTo) Int() (int, error)

Int string to int

func (StrTo) Int16 Uses

func (f StrTo) Int16() (int16, error)

Int16 string to int16

func (StrTo) Int32 Uses

func (f StrTo) Int32() (int32, error)

Int32 string to int32

func (StrTo) Int64 Uses

func (f StrTo) Int64() (int64, error)

Int64 string to int64

func (StrTo) Int8 Uses

func (f StrTo) Int8() (int8, error)

Int8 string to int8

func (*StrTo) Set Uses

func (f *StrTo) Set(v string)

Set string

func (StrTo) String Uses

func (f StrTo) String() string

String string to string

func (StrTo) Uint Uses

func (f StrTo) Uint() (uint, error)

Uint string to uint

func (StrTo) Uint16 Uses

func (f StrTo) Uint16() (uint16, error)

Uint16 string to uint16

func (StrTo) Uint32 Uses

func (f StrTo) Uint32() (uint32, error)

Uint32 string to uint31

func (StrTo) Uint64 Uses

func (f StrTo) Uint64() (uint64, error)

Uint64 string to uint64

func (StrTo) Uint8 Uses

func (f StrTo) Uint8() (uint8, error)

Uint8 string to uint8

type TextField Uses

type TextField string

TextField A large text field.

func (*TextField) FieldType Uses

func (e *TextField) FieldType() int

FieldType return enum type

func (*TextField) RawValue Uses

func (e *TextField) RawValue() interface{}

RawValue return TextField value

func (*TextField) Set Uses

func (e *TextField) Set(d string)

Set the TextField value

func (*TextField) SetRaw Uses

func (e *TextField) SetRaw(value interface{}) error

SetRaw convert interface string to string

func (*TextField) String Uses

func (e *TextField) String() string

String convert TextField to string

func (TextField) Value Uses

func (e TextField) Value() string

Value return TextField value

type TiDBQueryBuilder Uses

type TiDBQueryBuilder struct {
    Tokens []string
}

TiDBQueryBuilder is the SQL build

func (*TiDBQueryBuilder) And Uses

func (qb *TiDBQueryBuilder) And(cond string) QueryBuilder

And join the and cond

func (*TiDBQueryBuilder) Asc Uses

func (qb *TiDBQueryBuilder) Asc() QueryBuilder

Asc join the asc

func (*TiDBQueryBuilder) Delete Uses

func (qb *TiDBQueryBuilder) Delete(tables ...string) QueryBuilder

Delete join the Delete tables

func (*TiDBQueryBuilder) Desc Uses

func (qb *TiDBQueryBuilder) Desc() QueryBuilder

Desc join the desc

func (*TiDBQueryBuilder) ForUpdate Uses

func (qb *TiDBQueryBuilder) ForUpdate() QueryBuilder

ForUpdate add the FOR UPDATE clause

func (*TiDBQueryBuilder) From Uses

func (qb *TiDBQueryBuilder) From(tables ...string) QueryBuilder

From join the tables

func (*TiDBQueryBuilder) GroupBy Uses

func (qb *TiDBQueryBuilder) GroupBy(fields ...string) QueryBuilder

GroupBy join the Group by fields

func (*TiDBQueryBuilder) Having Uses

func (qb *TiDBQueryBuilder) Having(cond string) QueryBuilder

Having join the Having cond

func (*TiDBQueryBuilder) In Uses

func (qb *TiDBQueryBuilder) In(vals ...string) QueryBuilder

In join the IN (vals)

func (*TiDBQueryBuilder) InnerJoin Uses

func (qb *TiDBQueryBuilder) InnerJoin(table string) QueryBuilder

InnerJoin INNER JOIN the table

func (*TiDBQueryBuilder) InsertInto Uses

func (qb *TiDBQueryBuilder) InsertInto(table string, fields ...string) QueryBuilder

InsertInto join the insert SQL

func (*TiDBQueryBuilder) LeftJoin Uses

func (qb *TiDBQueryBuilder) LeftJoin(table string) QueryBuilder

LeftJoin LEFT JOIN the table

func (*TiDBQueryBuilder) Limit Uses

func (qb *TiDBQueryBuilder) Limit(limit int) QueryBuilder

Limit join the limit num

func (*TiDBQueryBuilder) Offset Uses

func (qb *TiDBQueryBuilder) Offset(offset int) QueryBuilder

Offset join the offset num

func (*TiDBQueryBuilder) On Uses

func (qb *TiDBQueryBuilder) On(cond string) QueryBuilder

On join with on cond

func (*TiDBQueryBuilder) Or Uses

func (qb *TiDBQueryBuilder) Or(cond string) QueryBuilder

Or join the or cond

func (*TiDBQueryBuilder) OrderBy Uses

func (qb *TiDBQueryBuilder) OrderBy(fields ...string) QueryBuilder

OrderBy join the Order by fields

func (*TiDBQueryBuilder) RightJoin Uses

func (qb *TiDBQueryBuilder) RightJoin(table string) QueryBuilder

RightJoin RIGHT JOIN the table

func (*TiDBQueryBuilder) Select Uses

func (qb *TiDBQueryBuilder) Select(fields ...string) QueryBuilder

Select will join the fields

func (*TiDBQueryBuilder) Set Uses

func (qb *TiDBQueryBuilder) Set(kv ...string) QueryBuilder

Set join the set kv

func (*TiDBQueryBuilder) String Uses

func (qb *TiDBQueryBuilder) String() string

String join all Tokens

func (*TiDBQueryBuilder) Subquery Uses

func (qb *TiDBQueryBuilder) Subquery(sub string, alias string) string

Subquery join the sub as alias

func (*TiDBQueryBuilder) Update Uses

func (qb *TiDBQueryBuilder) Update(tables ...string) QueryBuilder

Update join the update table

func (*TiDBQueryBuilder) Values Uses

func (qb *TiDBQueryBuilder) Values(vals ...string) QueryBuilder

Values join the Values(vals)

func (*TiDBQueryBuilder) Where Uses

func (qb *TiDBQueryBuilder) Where(cond string) QueryBuilder

Where join the Where cond

type TimeField Uses

type TimeField time.Time

TimeField A time, represented in go by a time.Time instance. only time values like 10:00:00 Has a few extra, optional attr tag:

auto_now: Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

auto_now_add: Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override.

eg: `orm:"auto_now"` or `orm:"auto_now_add"`

func (*TimeField) FieldType Uses

func (e *TimeField) FieldType() int

FieldType return enum type Date

func (*TimeField) RawValue Uses

func (e *TimeField) RawValue() interface{}

RawValue return time value

func (*TimeField) Set Uses

func (e *TimeField) Set(d time.Time)

Set set the TimeField's value

func (*TimeField) SetRaw Uses

func (e *TimeField) SetRaw(value interface{}) error

SetRaw convert the interface to time.Time. Allow string and time.Time

func (*TimeField) String Uses

func (e *TimeField) String() string

String convert time to string

func (TimeField) Value Uses

func (e TimeField) Value() time.Time

Value return the time.Time

Package orm imports 14 packages (graph) and is imported by 1276 packages. Updated 2018-12-19. Refresh now. Tools for package owners.