Documentation
¶
Overview ¶
Package xorm is a simple and powerful ORM for Go.
Installation ¶
Make sure you have installed Go 1.11+ and then:
go get e.coding.net/dengjq/go/xorm
Create Engine ¶
Firstly, we should create an engine for a database
engine, err := xorm.NewEngine(driverName, dataSourceName)
Method NewEngine's parameters are the same as sql.Open which depend drivers' implementation. Generally, one engine for an application is enough. You can define it as a package variable.
Raw Methods ¶
XORM supports raw SQL execution:
1. query with a SQL string, the returned results is []map[string][]byte
results, err := engine.Query("select * from user")
2. query with a SQL string, the returned results is []map[string]string
results, err := engine.QueryString("select * from user")
3. query with a SQL string, the returned results is []map[string]interface{}
results, err := engine.QueryInterface("select * from user")
4. execute with a SQL string, the returned results
affected, err := engine.Exec("update user set .... where ...")
ORM Methods ¶
There are 8 major ORM methods and many helpful methods to use to operate database.
1. Insert one or multiple records to database
affected, err := engine.Insert(&struct) // INSERT INTO struct () values () affected, err := engine.Insert(&struct1, &struct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values () affected, err := engine.Insert(&sliceOfStruct) // INSERT INTO struct () values (),(),() affected, err := engine.Insert(&struct1, &sliceOfStruct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values (),(),()
2. Query one record or one variable from database
has, err := engine.Get(&user) // SELECT * FROM user LIMIT 1 var id int64 has, err := engine.Table("user").Where("name = ?", name).Get(&id) // SELECT id FROM user WHERE name = ? LIMIT 1 var id int64 var name string has, err := engine.Table(&user).Cols("id", "name").Get(&id, &name) // SELECT id, name FROM user LIMIT 1
3. Query multiple records from database
var sliceOfStructs []Struct err := engine.Find(&sliceOfStructs) // SELECT * FROM user var mapOfStructs = make(map[int64]Struct) err := engine.Find(&mapOfStructs) // SELECT * FROM user var int64s []int64 err := engine.Table("user").Cols("id").Find(&int64s) // SELECT id FROM user
4. Query multiple records and record by record handle, there two methods, one is Iterate, another is Rows
err := engine.Iterate(new(User), func(i int, bean interface{}) error { // do something }) // SELECT * FROM user rows, err := engine.Rows(...) // SELECT * FROM user defer rows.Close() bean := new(Struct) for rows.Next() { err = rows.Scan(bean) }
or
rows, err := engine.Cols("name", "age").Rows(...) // SELECT * FROM user defer rows.Close() for rows.Next() { var name string var age int err = rows.Scan(&name, &age) }
5. Update one or more records
affected, err := engine.ID(...).Update(&user) // UPDATE user SET ...
6. Delete one or more records, Delete MUST has condition
affected, err := engine.Where(...).Delete(&user) // DELETE FROM user Where ...
7. Count records
counts, err := engine.Count(&user) // SELECT count(*) AS total FROM user counts, err := engine.SQL("select count(*) FROM user").Count() // select count(*) FROM user
8. Sum records
sumFloat64, err := engine.Sum(&user, "id") // SELECT sum(id) from user sumFloat64s, err := engine.Sums(&user, "id1", "id2") // SELECT sum(id1), sum(id2) from user sumInt64s, err := engine.SumsInt(&user, "id1", "id2") // SELECT sum(id1), sum(id2) from user
Conditions ¶
The above 8 methods could use with condition methods chainable. Notice: the above 8 methods should be the last chainable method.
1. ID, In
engine.ID(1).Get(&user) // for single primary key // SELECT * FROM user WHERE id = 1 engine.ID(schemas.PK{1, 2}).Get(&user) // for composite primary keys // SELECT * FROM user WHERE id1 = 1 AND id2 = 2 engine.In("id", 1, 2, 3).Find(&users) // SELECT * FROM user WHERE id IN (1, 2, 3) engine.In("id", []int{1, 2, 3}).Find(&users) // SELECT * FROM user WHERE id IN (1, 2, 3)
2. Where, And, Or
engine.Where().And().Or().Find() // SELECT * FROM user WHERE (.. AND ..) OR ...
3. OrderBy, Asc, Desc
engine.Asc().Desc().Find() // SELECT * FROM user ORDER BY .. ASC, .. DESC engine.OrderBy().Find() // SELECT * FROM user ORDER BY ..
4. Limit, Top
engine.Limit().Find() // SELECT * FROM user LIMIT .. OFFSET .. engine.Top(5).Find() // SELECT TOP 5 * FROM user // for mssql // SELECT * FROM user LIMIT .. OFFSET 0 //for other databases
5. SQL, let you custom SQL
var users []User engine.SQL("select * from user").Find(&users)
6. Cols, Omit, Distinct
var users []*User engine.Cols("col1, col2").Find(&users) // SELECT col1, col2 FROM user engine.Cols("col1", "col2").Where().Update(user) // UPDATE user set col1 = ?, col2 = ? Where ... engine.Omit("col1").Find(&users) // SELECT col2, col3 FROM user engine.Omit("col1").Insert(&user) // INSERT INTO table (non-col1) VALUES () engine.Distinct("col1").Find(&users) // SELECT DISTINCT col1 FROM user
7. Join, GroupBy, Having
engine.GroupBy("name").Having("name='xlw'").Find(&users) //SELECT * FROM user GROUP BY name HAVING name='xlw' engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find(&users) //SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id
Builder ¶
xorm could work with xorm.io/builder directly.
1. With Where
var cond = builder.Eq{"a":1, "b":2} engine.Where(cond).Find(&users)
2. With In
var subQuery = builder.Select("name").From("group") engine.In("group_name", subQuery).Find(&users)
3. With Join
var subQuery = builder.Select("name").From("group") engine.Join("INNER", subQuery, "group.id = user.group_id").Find(&users)
4. With SetExprs
var subQuery = builder.Select("name").From("group") engine.ID(1).SetExprs("name", subQuery).Update(new(User))
5. With SQL
var query = builder.Select("name").From("group") results, err := engine.SQL(query).Find(&groups)
6. With Query
var query = builder.Select("name").From("group") results, err := engine.Query(query) results, err := engine.QueryString(query) results, err := engine.QueryInterface(query)
7. With Exec
var query = builder.Insert("a, b").Into("table1").Select("b, c").From("table2") results, err := engine.Exec(query)
More usage, please visit http://xorm.io/docs
Index ¶
- Variables
- func SetDefaultJSONHandler(jsonHandler json.Interface)
- type AfterDeleteProcessor
- type AfterInsertProcessor
- type AfterLoadProcessor
- type AfterLoadSessionProcessor
- type AfterSetProcessor
- type AfterUpdateProcessor
- type BeforeDeleteProcessor
- type BeforeInsertProcessor
- type BeforeSetProcessor
- type BeforeUpdateProcessor
- type Cell
- type ColumnsSchema
- type Engine
- func NewEngine(driverName string, dataSourceName string) (*Engine, error)
- func NewEngineWithDB(driverName string, dataSourceName string, db *core.DB) (*Engine, error)
- func NewEngineWithDialectAndDB(driverName, dataSourceName string, dialect dialects.Dialect, db *core.DB) (*Engine, error)
- func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error)
- func (engine *Engine) AddHook(hook contexts.Hook)
- func (engine *Engine) After(closures func(interface{})) *Session
- func (engine *Engine) Alias(alias string) *Session
- func (engine *Engine) AllCols() *Session
- func (engine *Engine) Asc(colNames ...string) *Session
- func (engine *Engine) Before(closures func(interface{})) *Session
- func (engine *Engine) BufferSize(size int) *Session
- func (engine *Engine) Cascade(trueOrFalse ...bool) *Session
- func (engine *Engine) Charset(charset string) *Session
- func (engine *Engine) ClearCache(beans ...interface{}) error
- func (engine *Engine) ClearCacheBean(bean interface{}, id string) error
- func (engine *Engine) Close() error
- func (engine *Engine) Cols(columns ...string) *Session
- func (engine *Engine) Context(ctx context.Context) *Session
- func (engine *Engine) Count(bean ...interface{}) (int64, error)
- func (engine *Engine) CreateIndexes(bean interface{}) error
- func (engine *Engine) CreateTables(beans ...interface{}) error
- func (engine *Engine) CreateUniques(bean interface{}) error
- func (engine *Engine) DB() *core.DB
- func (engine *Engine) DBMetas() ([]*schemas.Table, error)
- func (engine *Engine) DBVersion() (*schemas.Version, error)
- func (engine *Engine) DataSourceName() string
- func (engine *Engine) Decr(column string, arg ...interface{}) *Session
- func (engine *Engine) Delete(beans ...interface{}) (int64, error)
- func (engine *Engine) Desc(colNames ...string) *Session
- func (engine *Engine) Dialect() dialects.Dialect
- func (engine *Engine) Distinct(columns ...string) *Session
- func (engine *Engine) DriverName() string
- func (engine *Engine) DropIndexes(bean interface{}) error
- func (engine *Engine) DropTables(beans ...interface{}) error
- func (engine *Engine) DumpAll(w io.Writer, tp ...schemas.DBType) error
- func (engine *Engine) DumpAllToFile(fp string, tp ...schemas.DBType) error
- func (engine *Engine) DumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) error
- func (engine *Engine) DumpTablesToFile(tables []*schemas.Table, fp string, tp ...schemas.DBType) error
- func (engine *Engine) EnableSessionID(enable bool)
- func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error)
- func (engine *Engine) Exist(bean ...interface{}) (bool, error)
- func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error
- func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
- func (engine *Engine) Get(beans ...interface{}) (bool, error)
- func (engine *Engine) GetCacher(tableName string) caches.Cacher
- func (engine *Engine) GetColumnMapper() names.Mapper
- func (engine *Engine) GetDefaultCacher() caches.Cacher
- func (engine *Engine) GetTZDatabase() *time.Location
- func (engine *Engine) GetTZLocation() *time.Location
- func (engine *Engine) GetTableMapper() names.Mapper
- func (engine *Engine) GroupBy(keys string) *Session
- func (engine *Engine) Having(conditions string) *Session
- func (engine *Engine) ID(id interface{}) *Session
- func (engine *Engine) Import(r io.Reader) ([]sql.Result, error)
- func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error)
- func (engine *Engine) In(column string, args ...interface{}) *Session
- func (engine *Engine) Incr(column string, arg ...interface{}) *Session
- func (engine *Engine) Insert(beans ...interface{}) (int64, error)
- func (engine *Engine) InsertOne(bean interface{}) (int64, error)
- func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error)
- func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error)
- func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error
- func (engine *Engine) Join(joinOperator string, tablename interface{}, condition interface{}, ...) *Session
- func (engine *Engine) Limit(limit int, start ...int) *Session
- func (engine *Engine) Logger() log.ContextLogger
- func (engine *Engine) MapCacher(bean interface{}, cacher caches.Cacher) error
- func (engine *Engine) MustCols(columns ...string) *Session
- func (engine *Engine) NewDB() (*core.DB, error)
- func (engine *Engine) NewSession() *Session
- func (engine *Engine) NoAutoCondition(no ...bool) *Session
- func (engine *Engine) NoAutoTime() *Session
- func (engine *Engine) NoCache() *Session
- func (engine *Engine) NoCascade() *Session
- func (engine *Engine) NotIn(column string, args ...interface{}) *Session
- func (engine *Engine) Nullable(columns ...string) *Session
- func (engine *Engine) Omit(columns ...string) *Session
- func (engine *Engine) OrderBy(order interface{}, args ...interface{}) *Session
- func (engine *Engine) Ping() error
- func (engine *Engine) PingContext(ctx context.Context) error
- func (engine *Engine) Prepare() *Session
- func (engine *Engine) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
- func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- func (engine *Engine) Quote(value string) string
- func (engine *Engine) QuoteTo(buf *strings.Builder, value string)
- func (engine *Engine) Rows(bean interface{}) (*Rows, error)
- func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session
- func (engine *Engine) SQLType(c *schemas.Column) string
- func (engine *Engine) ScanInterfaceMap(rows *core.Rows) (map[string]interface{}, error)
- func (engine *Engine) ScanInterfaceMaps(rows *core.Rows) (resultsSlice []map[string]interface{}, err error)
- func (engine *Engine) ScanStringMap(rows *core.Rows) (map[string]string, error)
- func (engine *Engine) ScanStringMaps(rows *core.Rows) (resultsSlice []map[string]string, err error)
- func (engine *Engine) ScanStringSlice(rows *core.Rows) ([]string, error)
- func (engine *Engine) ScanStringSlices(rows *core.Rows) (resultsSlice [][]string, err error)
- func (engine *Engine) Select(str string) *Session
- func (engine *Engine) SetCacher(tableName string, cacher caches.Cacher)
- func (engine *Engine) SetColumnMapper(mapper names.Mapper)
- func (engine *Engine) SetConnMaxIdleTime(d time.Duration)
- func (engine *Engine) SetConnMaxLifetime(d time.Duration)
- func (engine *Engine) SetDefaultCacher(cacher caches.Cacher)
- func (engine *Engine) SetDefaultContext(ctx context.Context)
- func (engine *Engine) SetDisableGlobalCache(disable bool)
- func (engine *Engine) SetExpr(column string, expression interface{}) *Session
- func (engine *Engine) SetLogLevel(level log.LogLevel)
- func (engine *Engine) SetLogger(logger interface{})
- func (engine *Engine) SetMapper(mapper names.Mapper)
- func (engine *Engine) SetMaxIdleConns(conns int)
- func (engine *Engine) SetMaxOpenConns(conns int)
- func (engine *Engine) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
- func (engine *Engine) SetSchema(schema string)
- func (engine *Engine) SetTZDatabase(tz *time.Location)
- func (engine *Engine) SetTZLocation(tz *time.Location)
- func (engine *Engine) SetTableMapper(mapper names.Mapper)
- func (engine *Engine) SetTagIdentifier(tagIdentifier string)
- func (engine *Engine) ShowSQL(show ...bool)
- func (engine *Engine) StoreEngine(storeEngine string) *Session
- func (engine *Engine) Sum(bean interface{}, colName string) (float64, error)
- func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error)
- func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error)
- func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error)
- func (engine *Engine) Sync(beans ...interface{}) error
- func (engine *Engine) Sync2(beans ...interface{}) error
- func (engine *Engine) SyncWithOptions(opts SyncOptions, beans ...interface{}) (*SyncResult, error)
- func (engine *Engine) Table(tableNameOrBean interface{}) *Session
- func (engine *Engine) TableInfo(bean interface{}) (*schemas.Table, error)
- func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string
- func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error)
- func (engine *Engine) Truncate(beans ...interface{}) (int64, error)
- func (engine *Engine) UnMapType(t reflect.Type)
- func (engine *Engine) Unscoped() *Session
- func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error)
- func (engine *Engine) UseBool(columns ...string) *Session
- func (engine *Engine) Where(query interface{}, args ...interface{}) *Session
- type EngineGroup
- func (eg *EngineGroup) AddHook(hook contexts.Hook)
- func (eg *EngineGroup) Close() error
- func (eg *EngineGroup) Context(ctx context.Context) *Session
- func (eg *EngineGroup) Master() *Engine
- func (eg *EngineGroup) NewSession() *Session
- func (eg *EngineGroup) Ping() error
- func (eg *EngineGroup) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
- func (eg *EngineGroup) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- func (eg *EngineGroup) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- func (eg *EngineGroup) Rows(bean interface{}) (*Rows, error)
- func (eg *EngineGroup) SetColumnMapper(mapper names.Mapper)
- func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration)
- func (eg *EngineGroup) SetDefaultCacher(cacher caches.Cacher)
- func (eg *EngineGroup) SetLogLevel(level log.LogLevel)
- func (eg *EngineGroup) SetLogger(logger interface{})
- func (eg *EngineGroup) SetMapper(mapper names.Mapper)
- func (eg *EngineGroup) SetMaxIdleConns(conns int)
- func (eg *EngineGroup) SetMaxOpenConns(conns int)
- func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup
- func (eg *EngineGroup) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
- func (eg *EngineGroup) SetTableMapper(mapper names.Mapper)
- func (eg *EngineGroup) SetTagIdentifier(tagIdentifier string)
- func (eg *EngineGroup) ShowSQL(show ...bool)
- func (eg *EngineGroup) Slave() *Engine
- func (eg *EngineGroup) Slaves() []*Engine
- type EngineInterface
- type ErrFieldIsNotExist
- type ErrFieldIsNotValid
- type GroupPolicy
- type GroupPolicyHandler
- type Interface
- type IterFunc
- type QueryedField
- type Rows
- type Session
- func (session *Session) After(closures func(interface{})) *Session
- func (session *Session) Alias(alias string) *Session
- func (session *Session) AllCols() *Session
- func (session *Session) And(query interface{}, args ...interface{}) *Session
- func (session *Session) Asc(colNames ...string) *Session
- func (session *Session) Before(closures func(interface{})) *Session
- func (session *Session) Begin() error
- func (session *Session) BufferSize(size int) *Session
- func (session *Session) Cascade(trueOrFalse ...bool) *Session
- func (session *Session) Charset(charset string) *Session
- func (session *Session) Close() error
- func (session *Session) Cols(columns ...string) *Session
- func (session *Session) Commit() error
- func (session *Session) Conds() builder.Cond
- func (session *Session) Context(ctx context.Context) *Session
- func (session *Session) ContextCache(context contexts.ContextCache) *Session
- func (session *Session) Count(bean ...interface{}) (int64, error)
- func (session *Session) CreateIndexes(bean interface{}) error
- func (session *Session) CreateTable(bean interface{}) error
- func (session *Session) CreateUniques(bean interface{}) error
- func (session *Session) DB() *core.DB
- func (session *Session) Decr(column string, arg ...interface{}) *Session
- func (session *Session) Delete(beans ...interface{}) (int64, error)
- func (session *Session) Desc(colNames ...string) *Session
- func (session *Session) Distinct(columns ...string) *Session
- func (session *Session) DropIndexes(bean interface{}) error
- func (session *Session) DropTable(beanOrTableName interface{}) error
- func (session *Session) Engine() *Engine
- func (session *Session) Exec(sqlOrArgs ...interface{}) (sql.Result, error)
- func (session *Session) Exist(bean ...interface{}) (bool, error)
- func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error
- func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
- func (session *Session) ForUpdate() *Session
- func (session *Session) Get(beans ...interface{}) (bool, error)
- func (session *Session) GroupBy(keys string) *Session
- func (session *Session) Having(conditions string) *Session
- func (session *Session) ID(id interface{}) *Session
- func (session *Session) Import(r io.Reader) ([]sql.Result, error)
- func (session *Session) ImportFile(ddlPath string) ([]sql.Result, error)
- func (session *Session) In(column string, args ...interface{}) *Session
- func (session *Session) Incr(column string, arg ...interface{}) *Session
- func (session *Session) Insert(beans ...interface{}) (int64, error)
- func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error)
- func (session *Session) InsertOne(bean interface{}) (int64, error)
- func (session *Session) IsClosed() bool
- func (session *Session) IsInTx() bool
- func (session *Session) IsTableEmpty(bean interface{}) (bool, error)
- func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error)
- func (session *Session) Iterate(bean interface{}, fun IterFunc) error
- func (session *Session) Join(joinOperator string, tablename interface{}, condition interface{}, ...) *Session
- func (session *Session) LastSQL() (string, []interface{})
- func (session *Session) Limit(limit int, start ...int) *Session
- func (session *Session) MustCols(columns ...string) *Session
- func (session *Session) MustLogSQL(logs ...bool) *Session
- func (session *Session) NoAutoCondition(no ...bool) *Session
- func (session *Session) NoAutoTime() *Session
- func (session *Session) NoCache() *Session
- func (session *Session) NoCascade() *Session
- func (session *Session) NoVersionCheck() *Session
- func (session *Session) NotIn(column string, args ...interface{}) *Session
- func (session *Session) Nullable(columns ...string) *Session
- func (session *Session) Omit(columns ...string) *Session
- func (session *Session) Or(query interface{}, args ...interface{}) *Session
- func (session *Session) OrderBy(order interface{}, args ...interface{}) *Session
- func (session *Session) Ping() error
- func (session *Session) PingContext(ctx context.Context) error
- func (session *Session) Prepare() *Session
- func (session *Session) Query(sqlOrArgs ...interface{}) ([]map[string][]byte, error)
- func (session *Session) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- func (session *Session) QuerySliceString(sqlOrArgs ...interface{}) ([][]string, error)
- func (session *Session) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- func (session *Session) Rollback() error
- func (session *Session) Rows(bean interface{}) (*Rows, error)
- func (session *Session) SQL(query interface{}, args ...interface{}) *Session
- func (session *Session) Select(str string) *Session
- func (session *Session) SetExpr(column string, expression interface{}) *Session
- func (session *Session) StoreEngine(storeEngine string) *Session
- func (session *Session) Sum(bean interface{}, columnName string) (res float64, err error)
- func (session *Session) SumInt(bean interface{}, columnName string) (res int64, err error)
- func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error)
- func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error)
- func (session *Session) Sync(beans ...interface{}) error
- func (session *Session) Sync2(beans ...interface{}) error
- func (session *Session) SyncWithOptions(opts SyncOptions, beans ...interface{}) (*SyncResult, error)
- func (session *Session) Table(tableNameOrBean interface{}) *Session
- func (session *Session) Truncate(beans ...interface{}) (int64, error)
- func (session *Session) Tx() *core.Tx
- func (session *Session) Unscoped() *Session
- func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error)
- func (session *Session) UseBool(columns ...string) *Session
- func (session *Session) Where(query interface{}, args ...interface{}) *Session
- type SyncOptions
- type SyncResult
Constants ¶
This section is empty.
Variables ¶
var ( // ErrPtrSliceType represents a type error ErrPtrSliceType = errors.New("A point to a slice is needed") // ErrParamsType params error ErrParamsType = errors.New("Params type error") // ErrTableNotFound table not found error ErrTableNotFound = errors.New("Table not found") // ErrUnSupportedType unsupported error ErrUnSupportedType = errors.New("Unsupported type error") // ErrNotExist record does not exist error ErrNotExist = errors.New("Record does not exist") // ErrCacheFailed cache failed error ErrCacheFailed = errors.New("Cache failed") // ErrConditionType condition type unsupported ErrConditionType = errors.New("Unsupported condition type") )
ErrNeedDeletedCond delete needs less one condition error
var (
ErrNoColumnsTobeUpdated = statements.ErrNoColumnsTobeUpdated
)
enumerated all errors
ErrNoElementsOnSlice represents an error there is no element when insert
Functions ¶
Types ¶
type AfterDeleteProcessor ¶
type AfterDeleteProcessor interface {
AfterDelete()
}
AfterDeleteProcessor executed after an object has been deleted
type AfterInsertProcessor ¶
type AfterInsertProcessor interface {
AfterInsert()
}
AfterInsertProcessor executed after an object is persisted to the database
type AfterLoadProcessor ¶
type AfterLoadProcessor interface {
AfterLoad()
}
AfterLoadProcessor executed after an ojbect has been loaded from database
type AfterLoadSessionProcessor ¶
type AfterLoadSessionProcessor interface {
AfterLoad(*Session)
}
AfterLoadSessionProcessor executed after an ojbect has been loaded from database with session parameter
type AfterSetProcessor ¶
AfterSetProcessor executed after data set to the struct fields
type AfterUpdateProcessor ¶
type AfterUpdateProcessor interface {
AfterUpdate()
}
AfterUpdateProcessor executed after an object has been updated
type BeforeDeleteProcessor ¶
type BeforeDeleteProcessor interface {
BeforeDelete()
}
BeforeDeleteProcessor executed before an object is deleted
type BeforeInsertProcessor ¶
type BeforeInsertProcessor interface {
BeforeInsert()
}
BeforeInsertProcessor executed before an object is initially persisted to the database
type BeforeSetProcessor ¶
BeforeSetProcessor executed before data set to the struct fields
type BeforeUpdateProcessor ¶
type BeforeUpdateProcessor interface {
BeforeUpdate()
}
BeforeUpdateProcessor executed before an object is updated
type ColumnsSchema ¶
type ColumnsSchema struct { Fields []*QueryedField FieldNames []string Types []*sql.ColumnType }
func ParseColumnsSchema ¶
func ParseColumnsSchema(fieldNames []string, types []*sql.ColumnType, table *schemas.Table) *ColumnsSchema
func (*ColumnsSchema) ParseTableSchema ¶
func (columnsSchema *ColumnsSchema) ParseTableSchema(table *schemas.Table)
type Engine ¶
type Engine struct { TZLocation *time.Location // The timezone of the application DatabaseTZ *time.Location // The timezone of the database // contains filtered or unexported fields }
Engine is the major struct of xorm, it means a database manager. Commonly, an application only need one engine
func NewEngine ¶
NewEngine new a db manager according to the parameter. Currently support four drivers
func NewEngineWithDB ¶
NewEngineWithDB new a db manager with db. The params will be passed to db.
func NewEngineWithDialectAndDB ¶
func NewEngineWithDialectAndDB(driverName, dataSourceName string, dialect dialects.Dialect, db *core.DB) (*Engine, error)
NewEngineWithDialectAndDB new a db manager according to the parameter. If you do not want to use your own dialect or db, please use NewEngine. For creating dialect, you can call dialects.OpenDialect. And, for creating db, you can call core.Open or core.FromDB.
func NewEngineWithParams ¶
func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error)
NewEngineWithParams new a db manager with params. The params will be passed to dialects.
func (*Engine) AddHook ¶
AddHook adds a context Hook
func (*Engine) After ¶
After apply after insert Processor, affected bean is passed to closure arg
func (*Engine) AllCols ¶
AllCols indicates that all columns should be use
func (*Engine) Asc ¶
Asc will generate "ORDER BY column1,column2 Asc" This method can chainable use.
engine.Desc("name").Asc("age").Find(&users) // SELECT * FROM user ORDER BY name DESC, age ASC
func (*Engine) Before ¶
Before apply before Processor, affected bean is passed to closure arg
func (*Engine) BufferSize ¶
BufferSize sets buffer size for iterate
func (*Engine) Cascade ¶
Cascade use cascade or not
func (*Engine) Charset ¶
Charset set charset when create table, only support mysql now
func (*Engine) ClearCache ¶
ClearCache if enabled cache, clear some tables' cache
func (*Engine) ClearCacheBean ¶
ClearCacheBean if enabled cache, clear the cache bean
func (*Engine) Cols ¶
Cols only use the parameters as select or update columns
func (*Engine) Context ¶
Context creates a session with the context
func (*Engine) Count ¶
Count counts the records. bean's non-empty fields are conditions.
func (*Engine) CreateIndexes ¶
CreateIndexes create indexes
func (*Engine) CreateTables ¶
CreateTables create tabls according bean
func (*Engine) CreateUniques ¶
CreateUniques create uniques
func (*Engine) DBMetas ¶
DBMetas Retrieve all tables, columns, indexes' informations from database.
func (*Engine) DBVersion ¶
DBVersion returns the database version
func (*Engine) DataSourceName ¶
DataSourceName return the current connection string
func (*Engine) Decr ¶
Decr provides a update string like "column = column - ?"
func (*Engine) Delete ¶
Delete records, bean's non-empty fields are conditions At least one condition must be set.
func (*Engine) Desc ¶
Desc will generate "ORDER BY column1 DESC, column2 DESC"
func (*Engine) Dialect ¶
Dialect return database dialect
func (*Engine) Distinct ¶
Distinct use for distinct columns. Caution: when you are using cache, distinct will not be cached because cache system need id, but distinct will not provide id
func (*Engine) DriverName ¶
DriverName return the current sql driver's name
func (*Engine) DropIndexes ¶
DropIndexes drop indexes of a table
func (*Engine) DropTables ¶
DropTables drop specify tables
func (*Engine) DumpAll ¶
DumpAll dump database all table structs and data to w
func (*Engine) DumpAllToFile ¶
DumpAllToFile dump database all table structs and data to a file
func (*Engine) DumpTables ¶
DumpTables dump specify tables to io.Writer
func (*Engine) DumpTablesToFile ¶
func (engine *Engine) DumpTablesToFile(tables []*schemas.Table, fp string, tp ...schemas.DBType) error
DumpTablesToFile dump specified tables to SQL file.
func (*Engine) EnableSessionID ¶
EnableSessionID if enable session id
func (*Engine) Exec ¶
Exec raw sql
func (*Engine) Exist ¶
Exist returns true if the record exist otherwise return false
func (*Engine) Find ¶
Find retrieve records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct
func (*Engine) FindAndCount ¶
func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
FindAndCount find the results and also return the counts
func (*Engine) Get ¶
Get retrieve one record from table, bean's non-empty fields are conditions
func (*Engine) GetCacher ¶
GetCacher returns the cachher of the special table
func (*Engine) GetColumnMapper ¶
GetColumnMapper returns the column name mapper
func (*Engine) GetDefaultCacher ¶
GetDefaultCacher returns the default cacher
func (*Engine) GetTZDatabase ¶
GetTZDatabase returns time zone of the database
func (*Engine) GetTZLocation ¶
GetTZLocation returns time zone of the application
func (*Engine) GetTableMapper ¶
GetTableMapper returns the table name mapper
func (*Engine) GroupBy ¶
GroupBy generate group by statement
func (*Engine) Having ¶
Having generate having statement
func (*Engine) ID ¶
ID method provoide a condition as (id) = ?
func (*Engine) Import ¶
Import SQL DDL from io.Reader
func (*Engine) ImportFile ¶
ImportFile SQL DDL file
func (*Engine) In ¶
In will generate "column IN (?, ?)"
func (*Engine) Incr ¶
Incr provides a update string like "column = column + ?"
func (*Engine) Insert ¶
Insert one or more records
func (*Engine) InsertOne ¶
InsertOne insert only one record
func (*Engine) IsTableEmpty ¶
IsTableEmpty if a table has any reocrd
func (*Engine) IsTableExist ¶
IsTableExist if a table is exist
func (*Engine) Iterate ¶
Iterate record by record handle records from table, bean's non-empty fields are conditions.
func (*Engine) Join ¶
func (engine *Engine) Join(joinOperator string, tablename interface{}, condition interface{}, args ...interface{}) *Session
Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (*Engine) Limit ¶
Limit will generate "LIMIT start, limit"
func (*Engine) Logger ¶
func (engine *Engine) Logger() log.ContextLogger
Logger return the logger interface
func (*Engine) MapCacher ¶
MapCacher Set a table use a special cacher
func (*Engine) MustCols ¶
MustCols specify some columns must use even if they are empty
func (*Engine) NewDB ¶
NewDB provides an interface to operate database directly
func (*Engine) NoAutoCondition ¶
NoAutoCondition disable auto generate Where condition from bean or not
func (*Engine) NoAutoTime ¶
NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields will automatically be filled with current time when Insert or Update invoked. Call NoAutoTime if you dont' want to fill automatically.
func (*Engine) NoCache ¶
NoCache If you has set default cacher, and you want temporilly stop use cache, you can use NoCache()
func (*Engine) NoCascade ¶
NoCascade If you do not want to auto cascade load object
func (*Engine) NotIn ¶
NotIn will generate "column NOT IN (?, ?)"
func (*Engine) Nullable ¶
Nullable set null when column is zero-value and nullable for update
func (*Engine) Omit ¶
Omit only not use the parameters as select or update columns
func (*Engine) OrderBy ¶
OrderBy will generate "ORDER BY order"
func (*Engine) PingContext ¶
PingContext tests if database is alive
func (*Engine) Query ¶
Query a raw sql and return records as []map[string][]byte
func (*Engine) QueryInterface ¶
QueryInterface runs a raw sql and return records as []map[string]interface{}
func (*Engine) QueryString ¶
QueryString runs a raw sql and return records as []map[string]string
func (*Engine) Quote ¶
Quote Use QuoteStr quote the string sql
func (*Engine) QuoteTo ¶
QuoteTo quotes string and writes into the buffer
func (*Engine) Rows ¶
Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields are conditions.
func (*Engine) SQL ¶
SQL method let's you manually write raw SQL and operate For example:
engine.SQL("select * from user").Find(&users)
This code will execute "select * from user" and set the records to users
func (*Engine) SQLType ¶
SQLType A simple wrapper to dialect's core.SqlType method
func (*Engine) ScanInterfaceMap ¶
ScanInterfaceMap scan result from *core.Rows and return a map
func (*Engine) ScanInterfaceMaps ¶
func (engine *Engine) ScanInterfaceMaps(rows *core.Rows) (resultsSlice []map[string]interface{}, err error)
ScanInterfaceMaps scan results from *core.Rows and return a slice of map
func (*Engine) ScanStringMap ¶
ScanStringMap scan results from *core.Rows and return a map
func (*Engine) ScanStringMaps ¶
ScanStringMaps scan results from *core.Rows and return a slice of map
func (*Engine) ScanStringSlice ¶
ScanStringSlice scan results from *core.Rows and return a slice of one row
func (*Engine) ScanStringSlices ¶
ScanStringSlices scan results from *core.Rows and return a slice of all rows
func (*Engine) Select ¶
Select customerize your select columns or contents
func (*Engine) SetCacher ¶
SetCacher sets cacher for the table
func (*Engine) SetColumnMapper ¶
SetColumnMapper set the column name mapping rule
func (*Engine) SetConnMaxIdleTime ¶
SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
func (*Engine) SetConnMaxLifetime ¶
SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func (*Engine) SetDefaultCacher ¶
SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
func (*Engine) SetDefaultContext ¶
SetDefaultContext set the default context
func (*Engine) SetDisableGlobalCache ¶
SetDisableGlobalCache disable global cache or not
func (*Engine) SetExpr ¶
SetExpr provides a update string like "column = {expression}"
func (*Engine) SetLogLevel ¶
SetLogLevel sets the logger level
func (*Engine) SetLogger ¶
func (engine *Engine) SetLogger(logger interface{})
SetLogger set the new logger
func (*Engine) SetMapper ¶
SetMapper set the name mapping rules
func (*Engine) SetMaxIdleConns ¶
SetMaxIdleConns set the max idle connections on pool, default is 2
func (*Engine) SetMaxOpenConns ¶
SetMaxOpenConns is only available for go 1.2+
func (*Engine) SetQuotePolicy ¶
func (engine *Engine) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
SetQuotePolicy sets the special quote policy
func (*Engine) SetSchema ¶
SetSchema sets the schema of database
func (*Engine) SetTZDatabase ¶
SetTZDatabase sets time zone of the database
func (*Engine) SetTZLocation ¶
SetTZLocation sets time zone of the application
func (*Engine) SetTableMapper ¶
SetTableMapper set the table name mapping rule
func (*Engine) SetTagIdentifier ¶
SetTagIdentifier set the tag identifier
func (*Engine) ShowSQL ¶
ShowSQL show SQL statement or not on logger if log level is great than INFO
func (*Engine) StoreEngine ¶
StoreEngine set store engine when create table, only support mysql now
func (*Engine) Sum ¶
Sum sum the records by some column. bean's non-empty fields are conditions.
func (*Engine) SumInt ¶
SumInt sum the records by some column. bean's non-empty fields are conditions.
func (*Engine) Sums ¶
Sums sum the records by some columns. bean's non-empty fields are conditions.
func (*Engine) SumsInt ¶
SumsInt like Sums but return slice of int64 instead of float64.
func (*Engine) Sync ¶
Sync the new struct changes to database, this method will automatically add table, column, index, unique. but will not delete or change anything. If you change some field, you should change the database manually.
func (*Engine) Sync2 ¶
Sync2 synchronize structs to database tables Depricated
func (*Engine) SyncWithOptions ¶
func (engine *Engine) SyncWithOptions(opts SyncOptions, beans ...interface{}) (*SyncResult, error)
SyncWithOptions sync the database schemas according options and table structs
func (*Engine) Table ¶
Table temporarily change the Get, Find, Update's table
func (*Engine) TableInfo ¶
TableInfo get table info according to bean's content
func (*Engine) TableName ¶
TableName returns table name with schema prefix if has
func (*Engine) Transaction ¶
Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
func (*Engine) Truncate ¶
Truncate records, bean's non-empty fields are conditions In contrast to Delete this method allows deletes without conditions.
func (*Engine) UnMapType ¶
UnMapType remove table from tables cache
func (*Engine) Unscoped ¶
Unscoped always disable struct tag "deleted"
func (*Engine) Update ¶
Update records, bean's non-empty fields are updated contents, condiBean' non-empty filds are conditions CAUTION:
1.bool will defaultly be updated content nor conditions You should call UseBool if you have bool to use. 2.float32 & float64 may be not inexact as conditions
func (*Engine) UseBool ¶
UseBool xorm automatically retrieve condition according struct, but if struct has bool field, it will ignore them. So use UseBool to tell system to do not ignore them. If no parameters, it will use all the bool field of struct, or it will use parameters's columns
type EngineGroup ¶
type EngineGroup struct { *Engine // contains filtered or unexported fields }
EngineGroup defines an engine group
func NewEngineGroup ¶
func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error)
NewEngineGroup creates a new engine group
func (*EngineGroup) Context ¶
func (eg *EngineGroup) Context(ctx context.Context) *Session
Context returned a group session
func (*EngineGroup) Master ¶
func (eg *EngineGroup) Master() *Engine
Master returns the master engine
func (*EngineGroup) NewSession ¶
func (eg *EngineGroup) NewSession() *Session
NewSession returned a group session
func (*EngineGroup) Query ¶
func (eg *EngineGroup) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
Query execcute a select SQL and return the result
func (*EngineGroup) QueryInterface ¶
func (eg *EngineGroup) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
QueryInterface execcute a select SQL and return the result
func (*EngineGroup) QueryString ¶
func (eg *EngineGroup) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
QueryString execcute a select SQL and return the result
func (*EngineGroup) Rows ¶
func (eg *EngineGroup) Rows(bean interface{}) (*Rows, error)
Rows execcute a select SQL and return the result
func (*EngineGroup) SetColumnMapper ¶
func (eg *EngineGroup) SetColumnMapper(mapper names.Mapper)
SetColumnMapper set the column name mapping rule
func (*EngineGroup) SetConnMaxLifetime ¶
func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration)
SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func (*EngineGroup) SetDefaultCacher ¶
func (eg *EngineGroup) SetDefaultCacher(cacher caches.Cacher)
SetDefaultCacher set the default cacher
func (*EngineGroup) SetLogLevel ¶
func (eg *EngineGroup) SetLogLevel(level log.LogLevel)
SetLogLevel sets the logger level
func (*EngineGroup) SetLogger ¶
func (eg *EngineGroup) SetLogger(logger interface{})
SetLogger set the new logger
func (*EngineGroup) SetMapper ¶
func (eg *EngineGroup) SetMapper(mapper names.Mapper)
SetMapper set the name mapping rules
func (*EngineGroup) SetMaxIdleConns ¶
func (eg *EngineGroup) SetMaxIdleConns(conns int)
SetMaxIdleConns set the max idle connections on pool, default is 2
func (*EngineGroup) SetMaxOpenConns ¶
func (eg *EngineGroup) SetMaxOpenConns(conns int)
SetMaxOpenConns is only available for go 1.2+
func (*EngineGroup) SetPolicy ¶
func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup
SetPolicy set the group policy
func (*EngineGroup) SetQuotePolicy ¶
func (eg *EngineGroup) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
SetQuotePolicy sets the special quote policy
func (*EngineGroup) SetTableMapper ¶
func (eg *EngineGroup) SetTableMapper(mapper names.Mapper)
SetTableMapper set the table name mapping rule
func (*EngineGroup) SetTagIdentifier ¶
func (eg *EngineGroup) SetTagIdentifier(tagIdentifier string)
SetTagIdentifier set the tag identifier
func (*EngineGroup) ShowSQL ¶
func (eg *EngineGroup) ShowSQL(show ...bool)
ShowSQL show SQL statement or not on logger if log level is great than INFO
func (*EngineGroup) Slave ¶
func (eg *EngineGroup) Slave() *Engine
Slave returns one of the physical databases which is a slave according the policy
func (*EngineGroup) Slaves ¶
func (eg *EngineGroup) Slaves() []*Engine
Slaves returns all the slaves
type EngineInterface ¶
type EngineInterface interface { Interface Before(func(interface{})) *Session Charset(charset string) *Session ClearCache(...interface{}) error Context(context.Context) *Session CreateTables(...interface{}) error DBMetas() ([]*schemas.Table, error) DBVersion() (*schemas.Version, error) Dialect() dialects.Dialect DriverName() string DropTables(...interface{}) error DumpAllToFile(fp string, tp ...schemas.DBType) error GetCacher(string) caches.Cacher GetColumnMapper() names.Mapper GetDefaultCacher() caches.Cacher GetTableMapper() names.Mapper GetTZDatabase() *time.Location GetTZLocation() *time.Location ImportFile(fp string) ([]sql.Result, error) MapCacher(interface{}, caches.Cacher) error NewSession() *Session NoAutoTime() *Session Prepare() *Session Quote(string) string SetCacher(string, caches.Cacher) SetConnMaxLifetime(time.Duration) SetColumnMapper(names.Mapper) SetTagIdentifier(string) SetDefaultCacher(caches.Cacher) SetLogger(logger interface{}) SetLogLevel(log.LogLevel) SetMapper(names.Mapper) SetMaxOpenConns(int) SetMaxIdleConns(int) SetQuotePolicy(dialects.QuotePolicy) SetSchema(string) SetTableMapper(names.Mapper) SetTZDatabase(tz *time.Location) SetTZLocation(tz *time.Location) AddHook(hook contexts.Hook) ShowSQL(show ...bool) Sync(...interface{}) error Sync2(...interface{}) error SyncWithOptions(SyncOptions, ...interface{}) (*SyncResult, error) StoreEngine(storeEngine string) *Session TableInfo(bean interface{}) (*schemas.Table, error) TableName(interface{}, ...bool) string UnMapType(reflect.Type) EnableSessionID(bool) }
EngineInterface defines the interface which Engine, EngineGroup will implementate.
type ErrFieldIsNotExist ¶
ErrFieldIsNotExist columns does not exist
func (ErrFieldIsNotExist) Error ¶
func (e ErrFieldIsNotExist) Error() string
type ErrFieldIsNotValid ¶
ErrFieldIsNotValid is not valid
func (ErrFieldIsNotValid) Error ¶
func (e ErrFieldIsNotValid) Error() string
type GroupPolicy ¶
type GroupPolicy interface {
Slave(*EngineGroup) *Engine
}
GroupPolicy is be used by chosing the current slave from slaves
type GroupPolicyHandler ¶
type GroupPolicyHandler func(*EngineGroup) *Engine
GroupPolicyHandler should be used when a function is a GroupPolicy
func LeastConnPolicy ¶
func LeastConnPolicy() GroupPolicyHandler
LeastConnPolicy implements GroupPolicy, every time will get the least connections slave
func RandomPolicy ¶
func RandomPolicy() GroupPolicyHandler
RandomPolicy implmentes randomly chose the slave of slaves
func RoundRobinPolicy ¶
func RoundRobinPolicy() GroupPolicyHandler
RoundRobinPolicy returns a group policy handler
func WeightRandomPolicy ¶
func WeightRandomPolicy(weights []int) GroupPolicyHandler
WeightRandomPolicy implmentes randomly chose the slave of slaves
func WeightRoundRobinPolicy ¶
func WeightRoundRobinPolicy(weights []int) GroupPolicyHandler
WeightRoundRobinPolicy returns a group policy handler
func (GroupPolicyHandler) Slave ¶
func (h GroupPolicyHandler) Slave(eg *EngineGroup) *Engine
Slave implements the chosen of slaves
type Interface ¶
type Interface interface { AllCols() *Session Alias(alias string) *Session Asc(colNames ...string) *Session BufferSize(size int) *Session Cols(columns ...string) *Session Count(...interface{}) (int64, error) CreateIndexes(bean interface{}) error CreateUniques(bean interface{}) error Decr(column string, arg ...interface{}) *Session Desc(...string) *Session Delete(...interface{}) (int64, error) Truncate(...interface{}) (int64, error) Distinct(columns ...string) *Session DropIndexes(bean interface{}) error Exec(sqlOrArgs ...interface{}) (sql.Result, error) Exist(bean ...interface{}) (bool, error) Find(interface{}, ...interface{}) error FindAndCount(interface{}, ...interface{}) (int64, error) Get(...interface{}) (bool, error) GroupBy(keys string) *Session ID(interface{}) *Session In(string, ...interface{}) *Session Incr(column string, arg ...interface{}) *Session Insert(...interface{}) (int64, error) InsertOne(interface{}) (int64, error) IsTableEmpty(bean interface{}) (bool, error) IsTableExist(beanOrTableName interface{}) (bool, error) Iterate(interface{}, IterFunc) error Limit(int, ...int) *Session MustCols(columns ...string) *Session NoAutoCondition(...bool) *Session NotIn(string, ...interface{}) *Session Nullable(...string) *Session Join(joinOperator string, tablename interface{}, condition interface{}, args ...interface{}) *Session Omit(columns ...string) *Session OrderBy(order interface{}, args ...interface{}) *Session Ping() error Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) Rows(bean interface{}) (*Rows, error) SetExpr(string, interface{}) *Session Select(string) *Session SQL(interface{}, ...interface{}) *Session Sum(bean interface{}, colName string) (float64, error) SumInt(bean interface{}, colName string) (int64, error) Sums(bean interface{}, colNames ...string) ([]float64, error) SumsInt(bean interface{}, colNames ...string) ([]int64, error) Table(tableNameOrBean interface{}) *Session Unscoped() *Session Update(bean interface{}, condiBeans ...interface{}) (int64, error) UseBool(...string) *Session Where(interface{}, ...interface{}) *Session }
Interface defines the interface which Engine, EngineGroup and Session will implementate.
type QueryedField ¶
type Rows ¶
type Rows struct {
// contains filtered or unexported fields
}
Rows rows wrapper a rows to
func (*Rows) Close ¶
Close session if session.IsAutoClose is true, and claimed any opened resources
func (*Rows) Err ¶
Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
func (*Rows) Next ¶
Next move cursor to next record, return false if end has reached
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session keep a pointer to sql.DB and provides all execution of all kind of database operations.
func (*Session) After ¶
After Apply after Processor, affected bean is passed to closure arg
func (*Session) Alias ¶
Alias set the table alias
func (*Session) And ¶
And provides custom query condition.
func (*Session) Asc ¶
Asc provide asc order by query condition, the input parameters are columns.
func (*Session) Before ¶
Before Apply before Processor, affected bean is passed to closure arg
func (*Session) BufferSize ¶
BufferSize sets the buffersize for iterate
func (*Session) Cascade ¶
Cascade indicates if loading sub Struct
func (*Session) Charset ¶
Charset is only avialble mysql dialect currently
func (*Session) Close ¶
Close release the connection from pool
func (*Session) Cols ¶
Cols provides some columns to special
func (*Session) Commit ¶
Commit When using transaction, Commit will commit all operations.
func (*Session) Conds ¶
Conds returns session query conditions except auto bean conditions
func (*Session) Context ¶
Context sets the context on this session
func (*Session) ContextCache ¶
func (session *Session) ContextCache(context contexts.ContextCache) *Session
ContextCache enable context cache or not
func (*Session) Count ¶
Count counts the records. bean's non-empty fields are conditions.
func (*Session) CreateIndexes ¶
CreateIndexes create indexes
func (*Session) CreateTable ¶
CreateTable create a table according a bean
func (*Session) CreateUniques ¶
CreateUniques create uniques
func (*Session) Decr ¶
Decr provides a query string like "count = count - 1"
func (*Session) Delete ¶
Delete records, bean's non-empty fields are conditions At least one condition must be set.
func (*Session) Desc ¶
Desc provide desc order by query condition, the input parameters are columns.
func (*Session) Distinct ¶
Distinct use for distinct columns. Caution: when you are using cache, distinct will not be cached because cache system need id, but distinct will not provide id
func (*Session) DropIndexes ¶
DropIndexes drop indexes
func (*Session) DropTable ¶
DropTable drop table will drop table if exist, if drop failed, it will return error
func (*Session) Exec ¶
Exec raw sql
func (*Session) Exist ¶
Exist returns true if the record exist otherwise return false
func (*Session) Find ¶
Find retrieve records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct
func (*Session) FindAndCount ¶
func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
FindAndCount find the results and also return the counts
func (*Session) ForUpdate ¶
ForUpdate Set Read/Write locking for UPDATE
func (*Session) Get ¶
Get retrieve one record from database, bean's non-empty fields will be as conditions
func (*Session) GroupBy ¶
GroupBy Generate Group By statement
func (*Session) Having ¶
Having Generate Having statement
func (*Session) ID ¶
ID provides converting id as a query condition
func (*Session) Import ¶
Import SQL DDL from io.Reader
func (*Session) ImportFile ¶
ImportFile SQL DDL file
func (*Session) In ¶
In provides a query string like "id in (1, 2, 3)"
func (*Session) Incr ¶
Incr provides a query string like "count = count + 1"
func (*Session) Insert ¶
Insert insert one or more beans
func (*Session) InsertMulti ¶
InsertMulti insert multiple records
func (*Session) InsertOne ¶
InsertOne insert only one struct into database as a record. The in parameter bean must a struct or a point to struct. The return parameter is inserted and error Deprecated: Please use Insert directly
func (*Session) IsClosed ¶
IsClosed returns if session is closed
func (*Session) IsInTx ¶
IsInTx if current session is in a transaction
func (*Session) IsTableEmpty ¶
IsTableEmpty if table have any records
func (*Session) IsTableExist ¶
IsTableExist if a table is exist
func (*Session) Iterate ¶
Iterate record by record handle records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct
func (*Session) Join ¶
func (session *Session) Join(joinOperator string, tablename interface{}, condition interface{}, args ...interface{}) *Session
Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (*Session) LastSQL ¶
LastSQL returns last query information
func (*Session) Limit ¶
Limit provide limit and offset query condition
func (*Session) MustCols ¶
MustCols specify some columns must use even if they are empty
func (*Session) MustLogSQL ¶
MustLogSQL means record SQL or not and don't follow engine's setting
func (*Session) NoAutoCondition ¶
NoAutoCondition disable generate SQL condition from beans
func (*Session) NoAutoTime ¶
NoAutoTime means do not automatically give created field and updated field the current time on the current session temporarily
func (*Session) NoCache ¶
NoCache ask this session do not retrieve data from cache system and get data from database directly.
func (*Session) NoCascade ¶
NoCascade indicate that no cascade load child object
func (*Session) NoVersionCheck ¶
disable version check
func (*Session) NotIn ¶
NotIn provides a query string like "id in (1, 2, 3)"
func (*Session) Nullable ¶
Nullable Set null when column is zero-value and nullable for update
func (*Session) Omit ¶
Omit Only not use the parameters as select or update columns
func (*Session) Or ¶
Or provides custom query condition.
func (*Session) OrderBy ¶
OrderBy provide order by query condition, the input parameter is the content after order by on a sql statement.
func (*Session) PingContext ¶
PingContext test if database is ok
func (*Session) Prepare ¶
Prepare set a flag to session that should be prepare statement before execute query
func (*Session) Query ¶
Query runs a raw sql and return records as []map[string][]byte
func (*Session) QueryInterface ¶
QueryInterface runs a raw sql and return records as []map[string]interface{}
func (*Session) QuerySliceString ¶
QuerySliceString runs a raw sql and return records as [][]string
func (*Session) QueryString ¶
QueryString runs a raw sql and return records as []map[string]string
func (*Session) Rollback ¶
Rollback When using transaction, you can rollback if any error
func (*Session) Rows ¶
Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields are conditions.
func (*Session) SQL ¶
SQL provides raw sql input parameter. When you have a complex SQL statement and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
func (*Session) Select ¶
Select provides some columns to special
func (*Session) SetExpr ¶
SetExpr provides a query string like "column = {expression}"
func (*Session) StoreEngine ¶
StoreEngine is only avialble mysql dialect currently
func (*Session) Sum ¶
Sum call sum some column. bean's non-empty fields are conditions.
func (*Session) SumInt ¶
SumInt call sum some column. bean's non-empty fields are conditions.
func (*Session) Sums ¶
Sums call sum some columns. bean's non-empty fields are conditions.
func (*Session) SumsInt ¶
SumsInt sum specify columns and return as []int64 instead of []float64
func (*Session) Sync ¶
Sync synchronize structs to database tables
func (*Session) Sync2 ¶
Sync2 synchronize structs to database tables Depricated
func (*Session) SyncWithOptions ¶
func (session *Session) SyncWithOptions(opts SyncOptions, beans ...interface{}) (*SyncResult, error)
func (*Session) Table ¶
Table can input a string or pointer to struct for special a table to operate.
func (*Session) Truncate ¶
Truncate records, bean's non-empty fields are conditions In contrast to Delete this method allows deletes without conditions.
func (*Session) Unscoped ¶
Unscoped always disable struct tag "deleted"
func (*Session) Update ¶
Update records, bean's non-empty fields are updated contents, condiBean' non-empty filds are conditions CAUTION:
1.bool will defaultly be updated content nor conditions You should call UseBool if you have bool to use. 2.float32 & float64 may be not inexact as conditions
func (*Session) UseBool ¶
UseBool automatically retrieve condition according struct, but if struct has bool field, it will ignore them. So use UseBool to tell system to do not ignore them. If no parameters, it will use all the bool field of struct, or it will use parameters's columns
type SyncOptions ¶
type SyncResult ¶
type SyncResult struct{}
Source Files
¶
- doc.go
- engine.go
- engine_group.go
- engine_group_policy.go
- error.go
- interface.go
- processors.go
- rows.go
- scan.go
- session.go
- session_cols.go
- session_cond.go
- session_delete.go
- session_exist.go
- session_find.go
- session_get.go
- session_insert.go
- session_iterate.go
- session_raw.go
- session_schema.go
- session_stats.go
- session_tx.go
- session_update.go
- sync.go