orm

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2022 License: MIT Imports: 20 Imported by: 0

README

Bhojpur Web - ORM Framework

A powerful Object Relational Mapping framework for the Bhojpur Web. It is heavily influenced by Django ORM, SQLAlchemy.

Support Database:

Features:

  • full Go language type support
  • easy for usage, simple CRUD operation
  • auto join with relation table
  • cross Database compatible query
  • Raw SQL query / mapper without ORM model
  • full test keep stable and strong

Installation:

go get github.com/bhojpur/web/pkg/client/orm

Quick Start

Simple Usage
package main

import (
	"fmt"
	"github.com/bhojpur/web/pkg/client/orm"
	_ "github.com/go-sql-driver/mysql" // import your database driver
)

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

func init() {
	// register model
	orm.RegisterModel(new(User))

	// set default database
	orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8", 30)
	
	// create table
	orm.RunSyncdb("default", false, true)	
}

func main() {
	o := orm.NewOrm()

	user := User{Name: "pramila"}

	// insert
	id, err := o.Insert(&user)

	// update
	user.Name = "bhojpur"
	num, err := o.Update(&user)

	// read one
	u := User{Id: user.Id}
	err = o.Read(&u)

	// delete
	num, err = o.Delete(&u)	
}
Next with Relation
type Post struct {
	Id    int    `orm:"auto"`
	Title string `orm:"size(100)"`
	User  *User  `orm:"rel(fk)"`
}

var posts []*Post
qs := o.QueryTable("post")
num, err := qs.Filter("User__Name", "pramila").All(&posts)
Use Raw sql

If you don't like ORM,use Raw SQL to query / mapping without ORM setting

var maps []Params
num, err := o.Raw("SELECT id FROM user WHERE name = ?", "pramila").Values(&maps)
if num > 0 {
	fmt.Println(maps[0]["id"])
}
Transactions
o.Begin()
...
user := User{Name: "pramila"}
id, err := o.Insert(&user)
if err == nil {
	o.Commit()
} else {
	o.Rollback()
}

Debug Log Queries

In development env, you can simple use

func main() {
	orm.Debug = true
...

enable log queries.

output include all queries, such as exec / prepare / transaction.

like this:

[ORM] - 2018-03-26 13:18:16 - [Queries/default] - [    db.Exec /     0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `pramila`
...

Documentation

more details and examples in docs and test

documents

Documentation

Index

Constants

View Source
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

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

Define some logic enum

View Source
const (
	ColAdd operator = iota
	ColMinus
	ColMultiply
	ColExcept
	ColBitAnd
	ColBitRShift
	ColBitLShift
	ColBitXOR
	ColBitOr
)

define Col operations

View Source
const CommaSpace = ", "

CommaSpace is the separation

View Source
const (
	DebugQueries = iota
)

DebugQueries define the debug

View Source
const (
	ExprSep = "__"
)

ExprSep define the expression separation

View Source
const (
	TxNameKey = "TxName"
)

Variables

View Source
var (
	Debug            = false
	DebugLog         = NewLog(os.Stdout)
	DefaultRowsLimit = -1
	DefaultRelsDepth = 2
	DefaultTimeLoc   = time.Local
	ErrTxDone        = errors.New("<TxOrmer.Commit/Rollback> transaction already done")
	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")

	ErrLastInsertIdUnavailable = errors.New("<Ormer> last insert id is unavailable")
)

Define common vars

View Source
var (
	// ErrMissPK missing pk error
	ErrMissPK = errors.New("missed pk value")
)
View Source
var LogFunc func(query map[string]interface{})

costomer log func

View Source
var (
	SnakeAcronymNameStrategy = "snakeStringWithAcronym"
)

Functions

func AddAliasWthDB added in v0.0.4

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

AddAliasWthDB add a aliasName for the drivename

func AddGlobalFilterChain added in v0.0.4

func AddGlobalFilterChain(filterChain ...FilterChain)

AddGlobalFilterChain adds a new FilterChain All orm instances built after this invocation will use this filterChain, but instances built before this invocation will not be affected

func BootStrap added in v0.0.4

func BootStrap()

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

func ColValue added in v0.0.4

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 added in v0.0.4

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 NewModelCacheHandler added in v0.0.4

func NewModelCacheHandler() *_modelCache

NewModelCacheHandler generator of _modelCache

func RegisterDataBase added in v0.0.4

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

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

func RegisterDriver added in v0.0.4

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 added in v0.0.4

func RegisterModel(models ...interface{})

RegisterModel register models

func RegisterModelWithPrefix added in v0.0.4

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

RegisterModelWithPrefix register models with a prefix

func RegisterModelWithSuffix added in v0.0.4

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

RegisterModelWithSuffix register models with a suffix

func ResetModelCache added in v0.0.4

func ResetModelCache()

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

func RunCommand

func RunCommand()

RunCommand listens for orm command and runs if command arguments have been passed.

func RunSyncdb

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

RunSyncdb run syncdb command line. name: Table's alias name (default is "default") force: Run the next sql command even if the current gave an error verbose: Print all information, useful for debugging

func SetDataBaseTZ added in v0.0.4

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

SetDataBaseTZ Change the database default used timezone

func SetMaxIdleConns added in v0.0.4

func SetMaxIdleConns(aliasName string, maxIdleConns int)

SetMaxIdleConns Change the max idle conns for *sql.DB, use specify database alias name Deprecated you should not use this, we will remove it in the future

func SetMaxOpenConns added in v0.0.4

func SetMaxOpenConns(aliasName string, maxOpenConns int)

SetMaxOpenConns Change the max open conns for *sql.DB, use specify database alias name Deprecated you should not use this, we will remove it in the future

func SetNameStrategy added in v0.0.4

func SetNameStrategy(s string)

SetNameStrategy set different name strategy

func ToInt64 added in v0.0.4

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

ToInt64 interface to int64

func ToStr added in v0.0.4

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

ToStr interface to string

Types

type BigIntegerField added in v0.0.4

type BigIntegerField int64

BigIntegerField -9223372036854775808 to 9223372036854775807.

func (*BigIntegerField) FieldType added in v0.0.4

func (e *BigIntegerField) FieldType() int

FieldType return enum type

func (*BigIntegerField) RawValue added in v0.0.4

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

RawValue return BigIntegerField value

func (*BigIntegerField) Set added in v0.0.4

func (e *BigIntegerField) Set(d int64)

Set the BigIntegerField value

func (*BigIntegerField) SetRaw added in v0.0.4

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

SetRaw convert interface int64/string to int64

func (*BigIntegerField) String added in v0.0.4

func (e *BigIntegerField) String() string

String convert BigIntegerField to string

func (BigIntegerField) Value added in v0.0.4

func (e BigIntegerField) Value() int64

Value return int64

type BooleanField added in v0.0.4

type BooleanField bool

BooleanField A true/false field.

func (*BooleanField) FieldType added in v0.0.4

func (e *BooleanField) FieldType() int

FieldType return BooleanField the type

func (*BooleanField) RawValue added in v0.0.4

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

RawValue return the current value

func (*BooleanField) Set added in v0.0.4

func (e *BooleanField) Set(d bool)

Set will set the BooleanField

func (*BooleanField) SetRaw added in v0.0.4

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

SetRaw set the interface to bool

func (*BooleanField) String added in v0.0.4

func (e *BooleanField) String() string

String format the Bool to string

func (BooleanField) Value added in v0.0.4

func (e BooleanField) Value() bool

Value return the BooleanField

type CharField added in v0.0.4

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 added in v0.0.4

func (e *CharField) FieldType() int

FieldType return the enum type

func (*CharField) RawValue added in v0.0.4

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

RawValue return the CharField value

func (*CharField) Set added in v0.0.4

func (e *CharField) Set(d string)

Set CharField value

func (*CharField) SetRaw added in v0.0.4

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

SetRaw set the interface to string

func (*CharField) String added in v0.0.4

func (e *CharField) String() string

String return the CharField

func (CharField) Value added in v0.0.4

func (e CharField) Value() string

Value return the CharField's Value

type Condition added in v0.0.4

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

Condition struct. work for WHERE conditions.

func NewCondition added in v0.0.4

func NewCondition() *Condition

NewCondition return new condition struct

func (Condition) And added in v0.0.4

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

And add expression to condition

func (*Condition) AndCond added in v0.0.4

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

AndCond combine a condition to current condition

func (Condition) AndNot added in v0.0.4

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

AndNot add NOT expression to condition

func (*Condition) AndNotCond added in v0.0.4

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

AndNotCond combine a AND NOT condition to current condition

func (*Condition) IsEmpty added in v0.0.4

func (c *Condition) IsEmpty() bool

IsEmpty check the condition arguments are empty or not.

func (Condition) Or added in v0.0.4

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

Or add OR expression to condition

func (*Condition) OrCond added in v0.0.4

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

OrCond combine a OR condition to current condition

func (Condition) OrNot added in v0.0.4

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

OrNot add OR NOT expression to condition

func (*Condition) OrNotCond added in v0.0.4

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

OrNotCond combine a OR NOT condition to current condition

func (Condition) Raw added in v0.0.4

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

Raw add raw sql to condition

type DB added in v0.0.4

type DB struct {
	*sync.RWMutex
	DB *sql.DB
	// contains filtered or unexported fields
}

func (*DB) Begin added in v0.0.4

func (d *DB) Begin() (*sql.Tx, error)

func (*DB) BeginTx added in v0.0.4

func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

func (*DB) Exec added in v0.0.4

func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error)

func (*DB) ExecContext added in v0.0.4

func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*DB) Prepare added in v0.0.4

func (d *DB) Prepare(query string) (*sql.Stmt, error)

func (*DB) PrepareContext added in v0.0.4

func (d *DB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

func (*DB) Query added in v0.0.4

func (d *DB) Query(query string, args ...interface{}) (*sql.Rows, error)

func (*DB) QueryContext added in v0.0.4

func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

func (*DB) QueryRow added in v0.0.4

func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row

func (*DB) QueryRowContext added in v0.0.4

func (d *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

type DBOption added in v0.0.4

type DBOption func(al *alias)

func ConnMaxLifetime added in v0.0.4

func ConnMaxLifetime(v time.Duration) DBOption

ConnMaxLifetime return a hint about ConnMaxLifetime

func MaxIdleConnections added in v0.0.4

func MaxIdleConnections(maxIdleConn int) DBOption

MaxIdleConnections return a hint about MaxIdleConnections

func MaxOpenConnections added in v0.0.4

func MaxOpenConnections(maxOpenConn int) DBOption

MaxOpenConnections return a hint about MaxOpenConnections

func MaxStmtCacheSize added in v0.0.4

func MaxStmtCacheSize(v int) DBOption

MaxStmtCacheSize return a hint about MaxStmtCacheSize

type DML added in v0.0.4

type DML interface {
	// insert model data to database
	// for example:
	//  user := new(User)
	//  id, err = Ormer.Insert(user)
	//  user must be a pointer and Insert will set user's pk field
	Insert(md interface{}) (int64, error)
	InsertWithCtx(ctx context.Context, md 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)
	InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error)
	// insert some models to database
	InsertMulti(bulk int, mds interface{}) (int64, error)
	InsertMultiWithCtx(ctx context.Context, 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 = "bhojpur"
	//	user.Extra.Data = "orm"
	//	num, err = Ormer.Update(&user, "Langs", "Extra")
	Update(md interface{}, cols ...string) (int64, error)
	UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error)
	// delete model in database
	Delete(md interface{}, cols ...string) (int64, error)
	DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error)

	// return a raw query seter for raw sql string.
	// for example:
	//	 ormer.Raw("UPDATE `user` SET `user_name` = ? WHERE `user_name` = ?", "pramila", "testing").Exec()
	//	// update user testing's name to pramila
	Raw(query string, args ...interface{}) RawSetter
	RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSetter
}

Data Manipulation Language

type DQL added in v0.0.4

type DQL 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: "bhojpur", Password: "pass"}
	//	err = Ormer.Read(u, "UserName")
	Read(md interface{}, cols ...string) error
	ReadWithCtx(ctx context.Context, 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
	ReadForUpdateWithCtx(ctx context.Context, 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)
	ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, 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{...}
	// hints.DefaultRelDepth useDefaultRelsDepth ; or depth 0
	// hints.RelDepth loadRelationDepth
	// hints.Limit limit default limit 1000
	// hints.Offset int offset default offset 0
	// hints.OrderBy string order  for example : "-Id"
	// make sure the relation is defined in model struct tags.
	LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error)
	LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (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
	QueryM2MWithCtx(ctx context.Context, md interface{}, name string) QueryM2Mer

	// return a QuerySetter for table operations.
	// table name can be string or struct.
	// e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)),
	QueryTable(ptrStructOrTableName interface{}) QuerySetter
	QueryTableWithCtx(ctx context.Context, ptrStructOrTableName interface{}) QuerySetter

	DBStats() *sql.DBStats
}

Data Query Language

type DateField added in v0.0.4

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 added in v0.0.4

func (e *DateField) FieldType() int

FieldType return enum type Date

func (*DateField) RawValue added in v0.0.4

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

RawValue return Date value

func (*DateField) Set added in v0.0.4

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

Set set the DateField's value

func (*DateField) SetRaw added in v0.0.4

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

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

func (*DateField) String added in v0.0.4

func (e *DateField) String() string

String convert datetime to string

func (DateField) Value added in v0.0.4

func (e DateField) Value() time.Time

Value return the time.Time

type DateTimeField added in v0.0.4

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 added in v0.0.4

func (e *DateTimeField) FieldType() int

FieldType return the enum TypeDateTimeField

func (*DateTimeField) RawValue added in v0.0.4

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

RawValue return the datetime value

func (*DateTimeField) Set added in v0.0.4

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

Set set the time.Time to datetime

func (*DateTimeField) SetRaw added in v0.0.4

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

SetRaw convert the string or time.Time to DateTimeField

func (*DateTimeField) String added in v0.0.4

func (e *DateTimeField) String() string

String return the time's String

func (DateTimeField) Value added in v0.0.4

func (e DateTimeField) Value() time.Time

Value return the datetime value

type DoNothingOrm added in v0.0.4

type DoNothingOrm struct {
}

func (*DoNothingOrm) Begin added in v0.0.4

func (d *DoNothingOrm) Begin() (TxOrmer, error)

func (*DoNothingOrm) BeginWithCtx added in v0.0.4

func (d *DoNothingOrm) BeginWithCtx(ctx context.Context) (TxOrmer, error)

func (*DoNothingOrm) BeginWithCtxAndOpts added in v0.0.4

func (d *DoNothingOrm) BeginWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions) (TxOrmer, error)

func (*DoNothingOrm) BeginWithOpts added in v0.0.4

func (d *DoNothingOrm) BeginWithOpts(opts *sql.TxOptions) (TxOrmer, error)

func (*DoNothingOrm) DBStats added in v0.0.4

func (d *DoNothingOrm) DBStats() *sql.DBStats

func (*DoNothingOrm) Delete added in v0.0.4

func (d *DoNothingOrm) Delete(md interface{}, cols ...string) (int64, error)

func (*DoNothingOrm) DeleteWithCtx added in v0.0.4

func (d *DoNothingOrm) DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error)

func (*DoNothingOrm) DoTx added in v0.0.4

func (d *DoNothingOrm) DoTx(task func(ctx context.Context, txOrm TxOrmer) error) error

func (*DoNothingOrm) DoTxWithCtx added in v0.0.4

func (d *DoNothingOrm) DoTxWithCtx(ctx context.Context, task func(ctx context.Context, txOrm TxOrmer) error) error

func (*DoNothingOrm) DoTxWithCtxAndOpts added in v0.0.4

func (d *DoNothingOrm) DoTxWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error

func (*DoNothingOrm) DoTxWithOpts added in v0.0.4

func (d *DoNothingOrm) DoTxWithOpts(opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error

func (*DoNothingOrm) Driver added in v0.0.4

func (d *DoNothingOrm) Driver() Driver

func (*DoNothingOrm) Insert added in v0.0.4

func (d *DoNothingOrm) Insert(md interface{}) (int64, error)

func (*DoNothingOrm) InsertMulti added in v0.0.4

func (d *DoNothingOrm) InsertMulti(bulk int, mds interface{}) (int64, error)

func (*DoNothingOrm) InsertMultiWithCtx added in v0.0.4

func (d *DoNothingOrm) InsertMultiWithCtx(ctx context.Context, bulk int, mds interface{}) (int64, error)

func (*DoNothingOrm) InsertOrUpdate added in v0.0.4

func (d *DoNothingOrm) InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64, error)

func (*DoNothingOrm) InsertOrUpdateWithCtx added in v0.0.4

func (d *DoNothingOrm) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error)

func (*DoNothingOrm) InsertWithCtx added in v0.0.4

func (d *DoNothingOrm) InsertWithCtx(ctx context.Context, md interface{}) (int64, error)

func (*DoNothingOrm) LoadRelated added in v0.0.4

func (d *DoNothingOrm) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error)

func (*DoNothingOrm) LoadRelatedWithCtx added in v0.0.4

func (d *DoNothingOrm) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error)

func (*DoNothingOrm) QueryM2M added in v0.0.4

func (d *DoNothingOrm) QueryM2M(md interface{}, name string) QueryM2Mer

func (*DoNothingOrm) QueryM2MWithCtx added in v0.0.4

func (d *DoNothingOrm) QueryM2MWithCtx(ctx context.Context, md interface{}, name string) QueryM2Mer

func (*DoNothingOrm) QueryTable added in v0.0.4

func (d *DoNothingOrm) QueryTable(ptrStructOrTableName interface{}) QuerySetter

func (*DoNothingOrm) QueryTableWithCtx added in v0.0.4

func (d *DoNothingOrm) QueryTableWithCtx(ctx context.Context, ptrStructOrTableName interface{}) QuerySetter

func (*DoNothingOrm) Raw added in v0.0.4

func (d *DoNothingOrm) Raw(query string, args ...interface{}) RawSetter

func (*DoNothingOrm) RawWithCtx added in v0.0.4

func (d *DoNothingOrm) RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSetter

func (*DoNothingOrm) Read added in v0.0.4

func (d *DoNothingOrm) Read(md interface{}, cols ...string) error

func (*DoNothingOrm) ReadForUpdate added in v0.0.4

func (d *DoNothingOrm) ReadForUpdate(md interface{}, cols ...string) error

func (*DoNothingOrm) ReadForUpdateWithCtx added in v0.0.4

func (d *DoNothingOrm) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols ...string) error

func (*DoNothingOrm) ReadOrCreate added in v0.0.4

func (d *DoNothingOrm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error)

func (*DoNothingOrm) ReadOrCreateWithCtx added in v0.0.4

func (d *DoNothingOrm) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error)

func (*DoNothingOrm) ReadWithCtx added in v0.0.4

func (d *DoNothingOrm) ReadWithCtx(ctx context.Context, md interface{}, cols ...string) error

func (*DoNothingOrm) Update added in v0.0.4

func (d *DoNothingOrm) Update(md interface{}, cols ...string) (int64, error)

func (*DoNothingOrm) UpdateWithCtx added in v0.0.4

func (d *DoNothingOrm) UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error)

type DoNothingTxOrm added in v0.0.4

type DoNothingTxOrm struct {
	DoNothingOrm
}

DoNothingTxOrm is similar with DoNothingOrm, usually you use it to test

func (*DoNothingTxOrm) Commit added in v0.0.4

func (d *DoNothingTxOrm) Commit() error

func (*DoNothingTxOrm) Rollback added in v0.0.4

func (d *DoNothingTxOrm) Rollback() error

type Driver added in v0.0.4

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

Driver define database driver

type DriverGetter added in v0.0.4

type DriverGetter interface {
	Driver() Driver
}

type DriverType added in v0.0.4

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 added in v0.0.4

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

Fielder define field info

type Filter added in v0.0.4

type Filter func(ctx context.Context, inv *Invocation) []interface{}

Filter's behavior is a little big strange. it's only be called when users call methods of Ormer return value is an array. it's a little bit hard to understand, for example, the Ormer's Read method only return error so the filter processing this method should return an array whose first element is error and, Ormer's ReadOrCreateWithCtx return three values, so the Filter's result should contains three values

type FilterChain added in v0.0.4

type FilterChain func(next Filter) Filter

FilterChain is used to build a Filter don't forget to call next(...) inside your Filter

type FloatField added in v0.0.4

type FloatField float64

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

func (*FloatField) FieldType added in v0.0.4

func (e *FloatField) FieldType() int

FieldType return the enum type

func (*FloatField) RawValue added in v0.0.4

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

RawValue return the FloatField value

func (*FloatField) Set added in v0.0.4

func (e *FloatField) Set(d float64)

Set the Float64

func (*FloatField) SetRaw added in v0.0.4

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

SetRaw converter interface Float64 float32 or string to FloatField

func (*FloatField) String added in v0.0.4

func (e *FloatField) String() string

String return the string

func (FloatField) Value added in v0.0.4

func (e FloatField) Value() float64

Value return the FloatField value

type Inserter added in v0.0.4

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

Inserter insert prepared statement

type IntegerField added in v0.0.4

type IntegerField int32

IntegerField -2147483648 to 2147483647

func (*IntegerField) FieldType added in v0.0.4

func (e *IntegerField) FieldType() int

FieldType return the enum type

func (*IntegerField) RawValue added in v0.0.4

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

RawValue return IntegerField value

func (*IntegerField) Set added in v0.0.4

func (e *IntegerField) Set(d int32)

Set IntegerField value

func (*IntegerField) SetRaw added in v0.0.4

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

SetRaw convert interface int32/string to int32

func (*IntegerField) String added in v0.0.4

func (e *IntegerField) String() string

String convert Int32 to string

func (IntegerField) Value added in v0.0.4

func (e IntegerField) Value() int32

Value return the int32

type Invocation added in v0.0.4

type Invocation struct {
	Method string
	// Md may be nil in some cases. It depends on method
	Md interface{}
	// the args are all arguments except context.Context
	Args []interface{}

	// insideTx indicates whether this is inside a transaction
	InsideTx    bool
	TxStartTime time.Time
	TxName      string
	// contains filtered or unexported fields
}

Invocation represents an "ORM" invocation

func (*Invocation) GetPkFieldName added in v0.0.4

func (inv *Invocation) GetPkFieldName() string

GetPkFieldName return the primary key of this table if not found, "" is returned

func (*Invocation) GetTableName added in v0.0.4

func (inv *Invocation) GetTableName() string

type IsApplicableTableForDB added in v0.0.4

type IsApplicableTableForDB interface {
	IsApplicableTableForDB(db string) bool
}

IsApplicableTableForDB if return false, we won't create table to this db

type JSONField added in v0.0.4

type JSONField string

JSONField postgres json field.

func (*JSONField) FieldType added in v0.0.4

func (j *JSONField) FieldType() int

FieldType return enum type

func (*JSONField) RawValue added in v0.0.4

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

RawValue return JSONField value

func (*JSONField) Set added in v0.0.4

func (j *JSONField) Set(d string)

Set the JSONField value

func (*JSONField) SetRaw added in v0.0.4

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

SetRaw convert interface string to string

func (*JSONField) String added in v0.0.4

func (j *JSONField) String() string

String convert JSONField to string

func (JSONField) Value added in v0.0.4

func (j JSONField) Value() string

Value return JSONField value

type JsonbField added in v0.0.4

type JsonbField string

JsonbField postgres json field.

func (*JsonbField) FieldType added in v0.0.4

func (j *JsonbField) FieldType() int

FieldType return enum type

func (*JsonbField) RawValue added in v0.0.4

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

RawValue return JsonbField value

func (*JsonbField) Set added in v0.0.4

func (j *JsonbField) Set(d string)

Set the JsonbField value

func (*JsonbField) SetRaw added in v0.0.4

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

SetRaw convert interface string to string

func (*JsonbField) String added in v0.0.4

func (j *JsonbField) String() string

String convert JsonbField to string

func (JsonbField) Value added in v0.0.4

func (j JsonbField) Value() string

Value return JsonbField value

type Log added in v0.0.4

type Log struct {
	*log.Logger
}

Log implement the log.Logger

func NewLog added in v0.0.4

func NewLog(out io.Writer) *Log

NewLog set io.Writer to create a Logger.

type MySQLQueryBuilder added in v0.0.4

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

MySQLQueryBuilder is the SQL build

func (*MySQLQueryBuilder) And added in v0.0.4

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

And join the and cond

func (*MySQLQueryBuilder) Asc added in v0.0.4

func (qb *MySQLQueryBuilder) Asc() QueryBuilder

Asc join the asc

func (*MySQLQueryBuilder) Delete added in v0.0.4

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

Delete join the Delete tables

func (*MySQLQueryBuilder) Desc added in v0.0.4

func (qb *MySQLQueryBuilder) Desc() QueryBuilder

Desc join the desc

func (*MySQLQueryBuilder) ForUpdate added in v0.0.4

func (qb *MySQLQueryBuilder) ForUpdate() QueryBuilder

ForUpdate add the FOR UPDATE clause

func (*MySQLQueryBuilder) From added in v0.0.4

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

From join the tables

func (*MySQLQueryBuilder) GroupBy added in v0.0.4

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

GroupBy join the Group by fields

func (*MySQLQueryBuilder) Having added in v0.0.4

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

Having join the Having cond

func (*MySQLQueryBuilder) In added in v0.0.4

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

In join the IN (vals)

func (*MySQLQueryBuilder) InnerJoin added in v0.0.4

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

InnerJoin INNER JOIN the table

func (*MySQLQueryBuilder) InsertInto added in v0.0.4

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

InsertInto join the insert SQL

func (*MySQLQueryBuilder) LeftJoin added in v0.0.4

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

LeftJoin LEFT JOIN the table

func (*MySQLQueryBuilder) Limit added in v0.0.4

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

Limit join the limit num

func (*MySQLQueryBuilder) Offset added in v0.0.4

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

Offset join the offset num

func (*MySQLQueryBuilder) On added in v0.0.4

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

On join with on cond

func (*MySQLQueryBuilder) Or added in v0.0.4

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

Or join the or cond

func (*MySQLQueryBuilder) OrderBy added in v0.0.4

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

OrderBy join the Order by fields

func (*MySQLQueryBuilder) RightJoin added in v0.0.4

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

RightJoin RIGHT JOIN the table

func (*MySQLQueryBuilder) Select added in v0.0.4

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

Select will join the fields

func (*MySQLQueryBuilder) Set added in v0.0.4

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

Set join the set kv

func (*MySQLQueryBuilder) String added in v0.0.4

func (qb *MySQLQueryBuilder) String() string

String join all tokens

func (*MySQLQueryBuilder) Subquery added in v0.0.4

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

Subquery join the sub as alias

func (*MySQLQueryBuilder) Update added in v0.0.4

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

Update join the update table

func (*MySQLQueryBuilder) Values added in v0.0.4

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

Values join the Values(vals)

func (*MySQLQueryBuilder) Where added in v0.0.4

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

Where join the Where cond

type Ormer added in v0.0.4

type Ormer interface {
	TxBeginner
	// contains filtered or unexported methods
}

func NewFilterOrmDecorator added in v0.0.4

func NewFilterOrmDecorator(delegate Ormer, filterChains ...FilterChain) Ormer

func NewOrm added in v0.0.4

func NewOrm() Ormer

NewOrm create new orm

func NewOrmUsingDB added in v0.0.4

func NewOrmUsingDB(aliasName string) Ormer

NewOrmUsingDB create new orm with the name

func NewOrmWithDB added in v0.0.4

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

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

type Params added in v0.0.4

type Params map[string]interface{}

Params stores the Params

type ParamsList added in v0.0.4

type ParamsList []interface{}

ParamsList stores paramslist

type PositiveBigIntegerField added in v0.0.4

type PositiveBigIntegerField uint64

PositiveBigIntegerField 0 to 18446744073709551615

func (*PositiveBigIntegerField) FieldType added in v0.0.4

func (e *PositiveBigIntegerField) FieldType() int

FieldType return enum type

func (*PositiveBigIntegerField) RawValue added in v0.0.4

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

RawValue return PositiveBigIntegerField value

func (*PositiveBigIntegerField) Set added in v0.0.4

func (e *PositiveBigIntegerField) Set(d uint64)

Set PositiveBigIntegerField value

func (*PositiveBigIntegerField) SetRaw added in v0.0.4

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

SetRaw convert interface uint64/string to Uint64

func (*PositiveBigIntegerField) String added in v0.0.4

func (e *PositiveBigIntegerField) String() string

String convert PositiveBigIntegerField to string

func (PositiveBigIntegerField) Value added in v0.0.4

func (e PositiveBigIntegerField) Value() uint64

Value return uint64

type PositiveIntegerField added in v0.0.4

type PositiveIntegerField uint32

PositiveIntegerField 0 to 4294967295

func (*PositiveIntegerField) FieldType added in v0.0.4

func (e *PositiveIntegerField) FieldType() int

FieldType return enum type

func (*PositiveIntegerField) RawValue added in v0.0.4

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

RawValue return the PositiveIntegerField Value

func (*PositiveIntegerField) Set added in v0.0.4

func (e *PositiveIntegerField) Set(d uint32)

Set the PositiveIntegerField value

func (*PositiveIntegerField) SetRaw added in v0.0.4

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

SetRaw convert interface uint32/string to Uint32

func (*PositiveIntegerField) String added in v0.0.4

func (e *PositiveIntegerField) String() string

String convert PositiveIntegerField to string

func (PositiveIntegerField) Value added in v0.0.4

func (e PositiveIntegerField) Value() uint32

Value return PositiveIntegerField value. Uint32

type PositiveSmallIntegerField added in v0.0.4

type PositiveSmallIntegerField uint16

PositiveSmallIntegerField 0 to 65535

func (*PositiveSmallIntegerField) FieldType added in v0.0.4

func (e *PositiveSmallIntegerField) FieldType() int

FieldType return enum type

func (*PositiveSmallIntegerField) RawValue added in v0.0.4

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

RawValue returns PositiveSmallIntegerField value

func (*PositiveSmallIntegerField) Set added in v0.0.4

Set PositiveSmallIntegerField value

func (*PositiveSmallIntegerField) SetRaw added in v0.0.4

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

SetRaw convert Interface uint16/string to uint16

func (*PositiveSmallIntegerField) String added in v0.0.4

func (e *PositiveSmallIntegerField) String() string

String convert uint16 to string

func (PositiveSmallIntegerField) Value added in v0.0.4

Value return uint16

type PostgresQueryBuilder added in v0.0.4

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

PostgresQueryBuilder is the SQL build

func (*PostgresQueryBuilder) And added in v0.0.4

And join the and cond

func (*PostgresQueryBuilder) Asc added in v0.0.4

Asc join the asc

func (*PostgresQueryBuilder) Delete added in v0.0.4

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

Delete join the Delete tables

func (*PostgresQueryBuilder) Desc added in v0.0.4

Desc join the desc

func (*PostgresQueryBuilder) ForUpdate added in v0.0.4

func (qb *PostgresQueryBuilder) ForUpdate() QueryBuilder

ForUpdate add the FOR UPDATE clause

func (*PostgresQueryBuilder) From added in v0.0.4

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

From join the tables

func (*PostgresQueryBuilder) GroupBy added in v0.0.4

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

GroupBy join the Group by fields

func (*PostgresQueryBuilder) Having added in v0.0.4

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

Having join the Having cond

func (*PostgresQueryBuilder) In added in v0.0.4

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

In join the IN (vals)

func (*PostgresQueryBuilder) InnerJoin added in v0.0.4

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

InnerJoin INNER JOIN the table

func (*PostgresQueryBuilder) InsertInto added in v0.0.4

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

InsertInto join the insert SQL

func (*PostgresQueryBuilder) LeftJoin added in v0.0.4

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

LeftJoin LEFT JOIN the table

func (*PostgresQueryBuilder) Limit added in v0.0.4

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

Limit join the limit num

func (*PostgresQueryBuilder) Offset added in v0.0.4

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

Offset join the offset num

func (*PostgresQueryBuilder) On added in v0.0.4

On join with on cond

func (*PostgresQueryBuilder) Or added in v0.0.4

Or join the or cond

func (*PostgresQueryBuilder) OrderBy added in v0.0.4

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

OrderBy join the Order by fields

func (*PostgresQueryBuilder) RightJoin added in v0.0.4

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

RightJoin RIGHT JOIN the table

func (*PostgresQueryBuilder) Select added in v0.0.4

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

Select will join the fields

func (*PostgresQueryBuilder) Set added in v0.0.4

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

Set join the set kv

func (*PostgresQueryBuilder) String added in v0.0.4

func (qb *PostgresQueryBuilder) String() string

String join all tokens

func (*PostgresQueryBuilder) Subquery added in v0.0.4

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

Subquery join the sub as alias

func (*PostgresQueryBuilder) Update added in v0.0.4

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

Update join the update table

func (*PostgresQueryBuilder) Values added in v0.0.4

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

Values join the Values(vals)

func (*PostgresQueryBuilder) Where added in v0.0.4

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

Where join the Where cond

type QueryBuilder added in v0.0.4

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 added in v0.0.4

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

NewQueryBuilder return the QueryBuilder

type QueryM2Mer added in v0.0.4

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 QuerySetter added in v0.0.4

type QuerySetter interface {
	// add condition expression to QuerySeter.
	// for example:
	//	filter by UserName == 'pramila'
	//	qs.Filter("UserName", "pramila")
	//	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{}) QuerySetter
	// 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) QuerySetter
	// add NOT condition to querySeter.
	// have the same usage as Filter
	Exclude(string, ...interface{}) QuerySetter
	// 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) QuerySetter
	// 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{}) QuerySetter
	// add OFFSET value
	// same as Limit function's args[0]
	Offset(offset interface{}) QuerySetter
	// add GROUP BY expression
	// for example:
	//	qs.GroupBy("id")
	GroupBy(exprs ...string) QuerySetter
	// add ORDER expression.
	// "column" means ASC, "-column" means DESC.
	// for example:
	//	qs.OrderBy("-status")
	OrderBy(exprs ...string) QuerySetter
	// add FORCE INDEX expression.
	// for example:
	//	qs.ForceIndex(`idx_name1`,`idx_name2`)
	// ForceIndex, UseIndex , IgnoreIndex are mutually exclusive
	ForceIndex(indexes ...string) QuerySetter
	// add USE INDEX expression.
	// for example:
	//	qs.UseIndex(`idx_name1`,`idx_name2`)
	// ForceIndex, UseIndex , IgnoreIndex are mutually exclusive
	UseIndex(indexes ...string) QuerySetter
	// add IGNORE INDEX expression.
	// for example:
	//	qs.IgnoreIndex(`idx_name1`,`idx_name2`)
	// ForceIndex, UseIndex , IgnoreIndex are mutually exclusive
	IgnoreIndex(indexes ...string) QuerySetter
	// 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{}) QuerySetter
	// Set Distinct
	// for example:
	//  o.QueryTable("policy").Filter("Groups__Group__Users__User", user).
	//    Distinct().
	//    All(&permissions)
	Distinct() QuerySetter
	// set FOR UPDATE to query.
	// for example:
	//  o.QueryTable("user").Filter("uid", uid).ForUpdate().All(&users)
	ForUpdate() QuerySetter
	// 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", "pramila").Update(Params{
	//		"Nums": ColValue(Col_Minus, 50),
	//	}) // user pramila's Nums will minus 50
	//	num, err = qs.Filter("UserName", "pramila").Update(Params{
	//		"user_name": "pramila2"
	//	}) // user pramila's  name will change to pramila2
	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 == "pramila"
	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"]=="pramila"
	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] == "pramila"
	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] == "pramila"
	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)
}

QuerySetter query seter

type RawPreparer added in v0.0.4

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

RawPreparer raw query statement

type RawSetter added in v0.0.4

type RawSetter 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=="pramila"
	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","pramila"}
	QueryRows(containers ...interface{}) (int64, error)
	SetArgs(...interface{}) RawSetter
	// 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)
}

RawSetter 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 added in v0.0.4

type SmallIntegerField int16

SmallIntegerField -32768 to 32767

func (*SmallIntegerField) FieldType added in v0.0.4

func (e *SmallIntegerField) FieldType() int

FieldType return enum type SmallIntegerField

func (*SmallIntegerField) RawValue added in v0.0.4

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

RawValue return smallint value

func (*SmallIntegerField) Set added in v0.0.4

func (e *SmallIntegerField) Set(d int16)

Set the SmallIntegerField value

func (*SmallIntegerField) SetRaw added in v0.0.4

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

SetRaw convert interface int16/string to int16

func (*SmallIntegerField) String added in v0.0.4

func (e *SmallIntegerField) String() string

String convert smallint to string

func (SmallIntegerField) Value added in v0.0.4

func (e SmallIntegerField) Value() int16

Value return int16 value

type StrTo added in v0.0.4

type StrTo string

StrTo is the target string

func (StrTo) Bool added in v0.0.4

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

Bool string to bool

func (*StrTo) Clear added in v0.0.4

func (f *StrTo) Clear()

Clear string

func (StrTo) Exist added in v0.0.4

func (f StrTo) Exist() bool

Exist check string exist

func (StrTo) Float32 added in v0.0.4

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

Float32 string to float32

func (StrTo) Float64 added in v0.0.4

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

Float64 string to float64

func (StrTo) Int added in v0.0.4

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

Int string to int

func (StrTo) Int16 added in v0.0.4

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

Int16 string to int16

func (StrTo) Int32 added in v0.0.4

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

Int32 string to int32

func (StrTo) Int64 added in v0.0.4

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

Int64 string to int64

func (StrTo) Int8 added in v0.0.4

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

Int8 string to int8

func (*StrTo) Set added in v0.0.4

func (f *StrTo) Set(v string)

Set string

func (StrTo) String added in v0.0.4

func (f StrTo) String() string

String string to string

func (StrTo) Uint added in v0.0.4

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

Uint string to uint

func (StrTo) Uint16 added in v0.0.4

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

Uint16 string to uint16

func (StrTo) Uint32 added in v0.0.4

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

Uint32 string to uint32

func (StrTo) Uint64 added in v0.0.4

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

Uint64 string to uint64

func (StrTo) Uint8 added in v0.0.4

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

Uint8 string to uint8

type TableEngineI added in v0.0.4

type TableEngineI interface {
	TableEngine() string
}

TableEngineI is usually used by model when you want to use specific engine, like myisam, you can implement this interface for example:

type User struct {
  ...
}
func (u *User) TableEngine() string {
   return "myisam"
}

type TableIndexI added in v0.0.4

type TableIndexI interface {
	TableIndex() [][]string
}

TableIndexI is usually used by model when you want to create indexes, you can implement this interface for example:

type User struct {
  ...
}
func (u *User) TableIndex() [][]string {
   return [][]string{{"Name"}}
}

type TableNameI added in v0.0.4

type TableNameI interface {
	TableName() string
}

TableNaming is usually used by model when you custom your table name, please implement this interfaces for example:

type User struct {
  ...
}
func (u *User) TableName() string {
   return "USER_TABLE"
}

type TableUniqueI added in v0.0.4

type TableUniqueI interface {
	TableUnique() [][]string
}

TableUniqueI is usually used by model when you want to create unique indexes, you can implement this interface for example:

type User struct {
  ...
}
func (u *User) TableUnique() [][]string {
   return [][]string{{"Email"}}
}

type TextField added in v0.0.4

type TextField string

TextField A large text field.

func (*TextField) FieldType added in v0.0.4

func (e *TextField) FieldType() int

FieldType return enum type

func (*TextField) RawValue added in v0.0.4

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

RawValue return TextField value

func (*TextField) Set added in v0.0.4

func (e *TextField) Set(d string)

Set the TextField value

func (*TextField) SetRaw added in v0.0.4

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

SetRaw convert interface string to string

func (*TextField) String added in v0.0.4

func (e *TextField) String() string

String convert TextField to string

func (TextField) Value added in v0.0.4

func (e TextField) Value() string

Value return TextField value

type TiDBQueryBuilder added in v0.0.4

type TiDBQueryBuilder struct {
	MySQLQueryBuilder
	// contains filtered or unexported fields
}

TiDBQueryBuilder is the SQL build

type TimeField added in v0.0.4

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 added in v0.0.4

func (e *TimeField) FieldType() int

FieldType return enum type Date

func (*TimeField) RawValue added in v0.0.4

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

RawValue return time value

func (*TimeField) Set added in v0.0.4

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

Set set the TimeField's value

func (*TimeField) SetRaw added in v0.0.4

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

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

func (*TimeField) String added in v0.0.4

func (e *TimeField) String() string

String convert time to string

func (TimeField) Value added in v0.0.4

func (e TimeField) Value() time.Time

Value return the time.Time

type TxBeginner added in v0.0.4

type TxBeginner interface {
	//self control transaction
	Begin() (TxOrmer, error)
	BeginWithCtx(ctx context.Context) (TxOrmer, error)
	BeginWithOpts(opts *sql.TxOptions) (TxOrmer, error)
	BeginWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions) (TxOrmer, error)

	//closure control transaction
	DoTx(task func(ctx context.Context, txOrm TxOrmer) error) error
	DoTxWithCtx(ctx context.Context, task func(ctx context.Context, txOrm TxOrmer) error) error
	DoTxWithOpts(opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error
	DoTxWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error
}

type TxCommitter added in v0.0.4

type TxCommitter interface {
	Commit() error
	Rollback() error
}

type TxDB added in v0.0.4

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

func (*TxDB) Commit added in v0.0.4

func (t *TxDB) Commit() error

func (*TxDB) Exec added in v0.0.4

func (t *TxDB) Exec(query string, args ...interface{}) (sql.Result, error)

func (*TxDB) ExecContext added in v0.0.4

func (t *TxDB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*TxDB) Prepare added in v0.0.4

func (t *TxDB) Prepare(query string) (*sql.Stmt, error)

func (*TxDB) PrepareContext added in v0.0.4

func (t *TxDB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

func (*TxDB) Query added in v0.0.4

func (t *TxDB) Query(query string, args ...interface{}) (*sql.Rows, error)

func (*TxDB) QueryContext added in v0.0.4

func (t *TxDB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

func (*TxDB) QueryRow added in v0.0.4

func (t *TxDB) QueryRow(query string, args ...interface{}) *sql.Row

func (*TxDB) QueryRowContext added in v0.0.4

func (t *TxDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*TxDB) Rollback added in v0.0.4

func (t *TxDB) Rollback() error

type TxOrmer added in v0.0.4

type TxOrmer interface {
	TxCommitter
	// contains filtered or unexported methods
}

func NewFilterTxOrmDecorator added in v0.0.4

func NewFilterTxOrmDecorator(delegate TxOrmer, root Filter, txName string) TxOrmer

Directories

Path Synopsis
filter

Jump to

Keyboard shortcuts

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