@ -19,6 +19,7 @@ import (
"sync"
"sync"
"time"
"time"
"github.com/go-xorm/builder"
"github.com/go-xorm/core"
"github.com/go-xorm/core"
)
)
@ -46,6 +47,23 @@ type Engine struct {
disableGlobalCache bool
disableGlobalCache bool
tagHandlers map [ string ] tagHandler
tagHandlers map [ string ] tagHandler
engineGroup * EngineGroup
}
// BufferSize sets buffer size for iterate
func ( engine * Engine ) BufferSize ( size int ) * Session {
session := engine . NewSession ( )
session . isAutoClose = true
return session . BufferSize ( size )
}
// CondDeleted returns the conditions whether a record is soft deleted.
func ( engine * Engine ) CondDeleted ( colName string ) builder . Cond {
if engine . dialect . DBType ( ) == core . MSSQL {
return builder . IsNull { colName }
}
return builder . IsNull { colName } . Or ( builder . Eq { colName : zeroTime1 } )
}
}
// ShowSQL show SQL statement or not on logger if log level is great than INFO
// ShowSQL show SQL statement or not on logger if log level is great than INFO
@ -78,6 +96,11 @@ func (engine *Engine) SetLogger(logger core.ILogger) {
engine . dialect . SetLogger ( logger )
engine . dialect . SetLogger ( logger )
}
}
// SetLogLevel sets the logger level
func ( engine * Engine ) SetLogLevel ( level core . LogLevel ) {
engine . logger . SetLevel ( level )
}
// SetDisableGlobalCache disable global cache or not
// SetDisableGlobalCache disable global cache or not
func ( engine * Engine ) SetDisableGlobalCache ( disable bool ) {
func ( engine * Engine ) SetDisableGlobalCache ( disable bool ) {
if engine . disableGlobalCache != disable {
if engine . disableGlobalCache != disable {
@ -168,7 +191,7 @@ func (engine *Engine) quote(sql string) string {
return engine . dialect . QuoteStr ( ) + sql + engine . dialect . QuoteStr ( )
return engine . dialect . QuoteStr ( ) + sql + engine . dialect . QuoteStr ( )
}
}
// SqlType will be depra cated, please use SQLType instead
// SqlType will be depre cated, please use SQLType instead
//
//
// Deprecated: use SQLType instead
// Deprecated: use SQLType instead
func ( engine * Engine ) SqlType ( c * core . Column ) string {
func ( engine * Engine ) SqlType ( c * core . Column ) string {
@ -195,28 +218,28 @@ func (engine *Engine) SetMaxIdleConns(conns int) {
engine . db . SetMaxIdleConns ( conns )
engine . db . SetMaxIdleConns ( conns )
}
}
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func ( engine * Engine ) SetConnMaxLifetime ( d time . Duration ) {
engine . db . SetConnMaxLifetime ( d )
}
// SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
// SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
func ( engine * Engine ) SetDefaultCacher ( cacher core . Cacher ) {
func ( engine * Engine ) SetDefaultCacher ( cacher core . Cacher ) {
engine . Cacher = cacher
engine . Cacher = cacher
}
}
// GetDefaultCacher returns the default cacher
func ( engine * Engine ) GetDefaultCacher ( ) core . Cacher {
return engine . Cacher
}
// NoCache If you has set default cacher, and you want temporilly stop use cache,
// NoCache If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
// you can use NoCache()
func ( engine * Engine ) NoCache ( ) * Session {
func ( engine * Engine ) NoCache ( ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . IsAutoClose = true
session . i sAutoClose = true
return session . NoCache ( )
return session . NoCache ( )
}
}
// NoCascade If you do not want to auto cascade load object
// NoCascade If you do not want to auto cascade load object
func ( engine * Engine ) NoCascade ( ) * Session {
func ( engine * Engine ) NoCascade ( ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . NoCascade ( )
return session . NoCascade ( )
}
}
@ -249,7 +272,7 @@ func (engine *Engine) Dialect() core.Dialect {
// NewSession New a session
// NewSession New a session
func ( engine * Engine ) NewSession ( ) * Session {
func ( engine * Engine ) NewSession ( ) * Session {
session := & Session { E ngine: engine }
session := & Session { e ngine: engine }
session . Init ( )
session . Init ( )
return session
return session
}
}
@ -263,7 +286,6 @@ func (engine *Engine) Close() error {
func ( engine * Engine ) Ping ( ) error {
func ( engine * Engine ) Ping ( ) error {
session := engine . NewSession ( )
session := engine . NewSession ( )
defer session . Close ( )
defer session . Close ( )
engine . logger . Infof ( "PING DATABASE %v" , engine . DriverName ( ) )
return session . Ping ( )
return session . Ping ( )
}
}
@ -271,43 +293,13 @@ func (engine *Engine) Ping() error {
func ( engine * Engine ) logSQL ( sqlStr string , sqlArgs ... interface { } ) {
func ( engine * Engine ) logSQL ( sqlStr string , sqlArgs ... interface { } ) {
if engine . showSQL && ! engine . showExecTime {
if engine . showSQL && ! engine . showExecTime {
if len ( sqlArgs ) > 0 {
if len ( sqlArgs ) > 0 {
engine . logger . Infof ( "[SQL] %v %v" , sqlStr , sqlArgs )
engine . logger . Infof ( "[SQL] %v %# v" , sqlStr , sqlArgs )
} else {
} else {
engine . logger . Infof ( "[SQL] %v" , sqlStr )
engine . logger . Infof ( "[SQL] %v" , sqlStr )
}
}
}
}
}
}
func ( engine * Engine ) logSQLQueryTime ( sqlStr string , args [ ] interface { } , executionBlock func ( ) ( * core . Stmt , * core . Rows , error ) ) ( * core . Stmt , * core . Rows , error ) {
if engine . showSQL && engine . showExecTime {
b4ExecTime := time . Now ( )
stmt , res , err := executionBlock ( )
execDuration := time . Since ( b4ExecTime )
if len ( args ) > 0 {
engine . logger . Infof ( "[SQL] %s %v - took: %v" , sqlStr , args , execDuration )
} else {
engine . logger . Infof ( "[SQL] %s - took: %v" , sqlStr , execDuration )
}
return stmt , res , err
}
return executionBlock ( )
}
func ( engine * Engine ) logSQLExecutionTime ( sqlStr string , args [ ] interface { } , executionBlock func ( ) ( sql . Result , error ) ) ( sql . Result , error ) {
if engine . showSQL && engine . showExecTime {
b4ExecTime := time . Now ( )
res , err := executionBlock ( )
execDuration := time . Since ( b4ExecTime )
if len ( args ) > 0 {
engine . logger . Infof ( "[sql] %s [args] %v - took: %v" , sqlStr , args , execDuration )
} else {
engine . logger . Infof ( "[sql] %s - took: %v" , sqlStr , execDuration )
}
return res , err
}
return executionBlock ( )
}
// Sql provides raw sql input parameter. When you have a complex SQL statement
// 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.
// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
//
//
@ -324,7 +316,7 @@ func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
// This code will execute "select * from user" and set the records to users
// This code will execute "select * from user" and set the records to users
func ( engine * Engine ) SQL ( query interface { } , args ... interface { } ) * Session {
func ( engine * Engine ) SQL ( query interface { } , args ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . SQL ( query , args ... )
return session . SQL ( query , args ... )
}
}
@ -333,14 +325,14 @@ func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session {
// invoked. Call NoAutoTime if you dont' want to fill automatically.
// invoked. Call NoAutoTime if you dont' want to fill automatically.
func ( engine * Engine ) NoAutoTime ( ) * Session {
func ( engine * Engine ) NoAutoTime ( ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . NoAutoTime ( )
return session . NoAutoTime ( )
}
}
// NoAutoCondition disable auto generate Where condition from bean or not
// NoAutoCondition disable auto generate Where condition from bean or not
func ( engine * Engine ) NoAutoCondition ( no ... bool ) * Session {
func ( engine * Engine ) NoAutoCondition ( no ... bool ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . NoAutoCondition ( no ... )
return session . NoAutoCondition ( no ... )
}
}
@ -574,56 +566,56 @@ func (engine *Engine) tbName(v reflect.Value) string {
// Cascade use cascade or not
// Cascade use cascade or not
func ( engine * Engine ) Cascade ( trueOrFalse ... bool ) * Session {
func ( engine * Engine ) Cascade ( trueOrFalse ... bool ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Cascade ( trueOrFalse ... )
return session . Cascade ( trueOrFalse ... )
}
}
// Where method provide a condition query
// Where method provide a condition query
func ( engine * Engine ) Where ( query interface { } , args ... interface { } ) * Session {
func ( engine * Engine ) Where ( query interface { } , args ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Where ( query , args ... )
return session . Where ( query , args ... )
}
}
// Id will be depra cated, please use ID instead
// Id will be depre cated, please use ID instead
func ( engine * Engine ) Id ( id interface { } ) * Session {
func ( engine * Engine ) Id ( id interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Id ( id )
return session . Id ( id )
}
}
// ID method provoide a condition as (id) = ?
// ID method provoide a condition as (id) = ?
func ( engine * Engine ) ID ( id interface { } ) * Session {
func ( engine * Engine ) ID ( id interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . ID ( id )
return session . ID ( id )
}
}
// Before apply before Processor, affected bean is passed to closure arg
// Before apply before Processor, affected bean is passed to closure arg
func ( engine * Engine ) Before ( closures func ( interface { } ) ) * Session {
func ( engine * Engine ) Before ( closures func ( interface { } ) ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Before ( closures )
return session . Before ( closures )
}
}
// After apply after insert Processor, affected bean is passed to closure arg
// After apply after insert Processor, affected bean is passed to closure arg
func ( engine * Engine ) After ( closures func ( interface { } ) ) * Session {
func ( engine * Engine ) After ( closures func ( interface { } ) ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . After ( closures )
return session . After ( closures )
}
}
// Charset set charset when create table, only support mysql now
// Charset set charset when create table, only support mysql now
func ( engine * Engine ) Charset ( charset string ) * Session {
func ( engine * Engine ) Charset ( charset string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Charset ( charset )
return session . Charset ( charset )
}
}
// StoreEngine set store engine when create table, only support mysql now
// StoreEngine set store engine when create table, only support mysql now
func ( engine * Engine ) StoreEngine ( storeEngine string ) * Session {
func ( engine * Engine ) StoreEngine ( storeEngine string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . StoreEngine ( storeEngine )
return session . StoreEngine ( storeEngine )
}
}
@ -632,35 +624,35 @@ func (engine *Engine) StoreEngine(storeEngine string) *Session {
// but distinct will not provide id
// but distinct will not provide id
func ( engine * Engine ) Distinct ( columns ... string ) * Session {
func ( engine * Engine ) Distinct ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Distinct ( columns ... )
return session . Distinct ( columns ... )
}
}
// Select customerize your select columns or contents
// Select customerize your select columns or contents
func ( engine * Engine ) Select ( str string ) * Session {
func ( engine * Engine ) Select ( str string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Select ( str )
return session . Select ( str )
}
}
// Cols only use the parameters as select or update columns
// Cols only use the parameters as select or update columns
func ( engine * Engine ) Cols ( columns ... string ) * Session {
func ( engine * Engine ) Cols ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Cols ( columns ... )
return session . Cols ( columns ... )
}
}
// AllCols indicates that all columns should be use
// AllCols indicates that all columns should be use
func ( engine * Engine ) AllCols ( ) * Session {
func ( engine * Engine ) AllCols ( ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . AllCols ( )
return session . AllCols ( )
}
}
// MustCols specify some columns must use even if they are empty
// MustCols specify some columns must use even if they are empty
func ( engine * Engine ) MustCols ( columns ... string ) * Session {
func ( engine * Engine ) MustCols ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . MustCols ( columns ... )
return session . MustCols ( columns ... )
}
}
@ -671,77 +663,84 @@ func (engine *Engine) MustCols(columns ...string) *Session {
// it will use parameters's columns
// it will use parameters's columns
func ( engine * Engine ) UseBool ( columns ... string ) * Session {
func ( engine * Engine ) UseBool ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . UseBool ( columns ... )
return session . UseBool ( columns ... )
}
}
// Omit only not use the parameters as select or update columns
// Omit only not use the parameters as select or update columns
func ( engine * Engine ) Omit ( columns ... string ) * Session {
func ( engine * Engine ) Omit ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Omit ( columns ... )
return session . Omit ( columns ... )
}
}
// Nullable set null when column is zero-value and nullable for update
// Nullable set null when column is zero-value and nullable for update
func ( engine * Engine ) Nullable ( columns ... string ) * Session {
func ( engine * Engine ) Nullable ( columns ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Nullable ( columns ... )
return session . Nullable ( columns ... )
}
}
// In will generate "column IN (?, ?)"
// In will generate "column IN (?, ?)"
func ( engine * Engine ) In ( column string , args ... interface { } ) * Session {
func ( engine * Engine ) In ( column string , args ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . In ( column , args ... )
return session . In ( column , args ... )
}
}
// NotIn will generate "column NOT IN (?, ?)"
func ( engine * Engine ) NotIn ( column string , args ... interface { } ) * Session {
session := engine . NewSession ( )
session . isAutoClose = true
return session . NotIn ( column , args ... )
}
// Incr provides a update string like "column = column + ?"
// Incr provides a update string like "column = column + ?"
func ( engine * Engine ) Incr ( column string , arg ... interface { } ) * Session {
func ( engine * Engine ) Incr ( column string , arg ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . IsAutoClose = true
session . i sAutoClose = true
return session . Incr ( column , arg ... )
return session . Incr ( column , arg ... )
}
}
// Decr provides a update string like "column = column - ?"
// Decr provides a update string like "column = column - ?"
func ( engine * Engine ) Decr ( column string , arg ... interface { } ) * Session {
func ( engine * Engine ) Decr ( column string , arg ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Decr ( column , arg ... )
return session . Decr ( column , arg ... )
}
}
// SetExpr provides a update string like "column = {expression}"
// SetExpr provides a update string like "column = {expression}"
func ( engine * Engine ) SetExpr ( column string , expression string ) * Session {
func ( engine * Engine ) SetExpr ( column string , expression string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . SetExpr ( column , expression )
return session . SetExpr ( column , expression )
}
}
// Table temporarily change the Get, Find, Update's table
// Table temporarily change the Get, Find, Update's table
func ( engine * Engine ) Table ( tableNameOrBean interface { } ) * Session {
func ( engine * Engine ) Table ( tableNameOrBean interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Table ( tableNameOrBean )
return session . Table ( tableNameOrBean )
}
}
// Alias set the table alias
// Alias set the table alias
func ( engine * Engine ) Alias ( alias string ) * Session {
func ( engine * Engine ) Alias ( alias string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Alias ( alias )
return session . Alias ( alias )
}
}
// Limit will generate "LIMIT start, limit"
// Limit will generate "LIMIT start, limit"
func ( engine * Engine ) Limit ( limit int , start ... int ) * Session {
func ( engine * Engine ) Limit ( limit int , start ... int ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Limit ( limit , start ... )
return session . Limit ( limit , start ... )
}
}
// Desc will generate "ORDER BY column1 DESC, column2 DESC"
// Desc will generate "ORDER BY column1 DESC, column2 DESC"
func ( engine * Engine ) Desc ( colNames ... string ) * Session {
func ( engine * Engine ) Desc ( colNames ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Desc ( colNames ... )
return session . Desc ( colNames ... )
}
}
@ -753,39 +752,47 @@ func (engine *Engine) Desc(colNames ...string) *Session {
//
//
func ( engine * Engine ) Asc ( colNames ... string ) * Session {
func ( engine * Engine ) Asc ( colNames ... string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Asc ( colNames ... )
return session . Asc ( colNames ... )
}
}
// OrderBy will generate "ORDER BY order"
// OrderBy will generate "ORDER BY order"
func ( engine * Engine ) OrderBy ( order string ) * Session {
func ( engine * Engine ) OrderBy ( order string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . OrderBy ( order )
return session . OrderBy ( order )
}
}
// Prepare enables prepare statement
func ( engine * Engine ) Prepare ( ) * Session {
session := engine . NewSession ( )
session . isAutoClose = true
return session . Prepare ( )
}
// Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
// Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func ( engine * Engine ) Join ( joinOperator string , tablename interface { } , condition string , args ... interface { } ) * Session {
func ( engine * Engine ) Join ( joinOperator string , tablename interface { } , condition string , args ... interface { } ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . IsAutoClose = true
session . i sAutoClose = true
return session . Join ( joinOperator , tablename , condition , args ... )
return session . Join ( joinOperator , tablename , condition , args ... )
}
}
// GroupBy generate group by statement
// GroupBy generate group by statement
func ( engine * Engine ) GroupBy ( keys string ) * Session {
func ( engine * Engine ) GroupBy ( keys string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . GroupBy ( keys )
return session . GroupBy ( keys )
}
}
// Having generate having statement
// Having generate having statement
func ( engine * Engine ) Having ( conditions string ) * Session {
func ( engine * Engine ) Having ( conditions string ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . I sAutoClose = true
session . i sAutoClose = true
return session . Having ( conditions )
return session . Having ( conditions )
}
}
func ( engine * Engine ) unMapType ( t reflect . Type ) {
// UnMapType removes the datbase mapper of a type
func ( engine * Engine ) UnMapType ( t reflect . Type ) {
engine . mutex . Lock ( )
engine . mutex . Lock ( )
defer engine . mutex . Unlock ( )
defer engine . mutex . Unlock ( )
delete ( engine . Tables , t )
delete ( engine . Tables , t )
@ -942,7 +949,7 @@ func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
}
}
if pStart > - 1 {
if pStart > - 1 {
if ! strings . HasSuffix ( k , ")" ) {
if ! strings . HasSuffix ( k , ")" ) {
return nil , errors . New ( "cannot match ) charactor" )
return nil , fmt . Errorf ( "field %s tag %s cannot match ) charactor" , col . FieldName , key )
}
}
ctx . tagName = k [ : pStart ]
ctx . tagName = k [ : pStart ]
@ -1108,19 +1115,39 @@ func (engine *Engine) idOfV(rv reflect.Value) (core.PK, error) {
pk := make ( [ ] interface { } , len ( table . PrimaryKeys ) )
pk := make ( [ ] interface { } , len ( table . PrimaryKeys ) )
for i , col := range table . PKColumns ( ) {
for i , col := range table . PKColumns ( ) {
var err error
pkField := v . FieldByName ( col . FieldName )
pkField := v . FieldByName ( col . FieldName )
switch pkField . Kind ( ) {
switch pkField . Kind ( ) {
case reflect . String :
case reflect . String :
pk [ i ] = pkField . String ( )
pk [ i ] , err = engine . idTypeAssertion ( col , pkField . String ( ) )
case reflect . Int , reflect . Int8 , reflect . Int16 , reflect . Int32 , reflect . Int64 :
case reflect . Int , reflect . Int8 , reflect . Int16 , reflect . Int32 , reflect . Int64 :
pk [ i ] = pkField . Int ( )
pk [ i ] , err = engine . idTypeAssertion ( col , strconv . FormatInt ( pkField . Int ( ) , 10 ) )
case reflect . Uint , reflect . Uint8 , reflect . Uint16 , reflect . Uint32 , reflect . Uint64 :
case reflect . Uint , reflect . Uint8 , reflect . Uint16 , reflect . Uint32 , reflect . Uint64 :
pk [ i ] = pkField . Uint ( )
// id of uint will be converted to int64
pk [ i ] , err = engine . idTypeAssertion ( col , strconv . FormatUint ( pkField . Uint ( ) , 10 ) )
}
if err != nil {
return nil , err
}
}
}
}
return core . PK ( pk ) , nil
return core . PK ( pk ) , nil
}
}
func ( engine * Engine ) idTypeAssertion ( col * core . Column , sid string ) ( interface { } , error ) {
if col . SQLType . IsNumeric ( ) {
n , err := strconv . ParseInt ( sid , 10 , 64 )
if err != nil {
return nil , err
}
return n , nil
} else if col . SQLType . IsText ( ) {
return sid , nil
} else {
return nil , errors . New ( "not supported" )
}
}
// CreateIndexes create indexes
// CreateIndexes create indexes
func ( engine * Engine ) CreateIndexes ( bean interface { } ) error {
func ( engine * Engine ) CreateIndexes ( bean interface { } ) error {
session := engine . NewSession ( )
session := engine . NewSession ( )
@ -1192,6 +1219,9 @@ func (engine *Engine) ClearCache(beans ...interface{}) error {
// table, column, index, unique. but will not delete or change anything.
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
// If you change some field, you should change the database manually.
func ( engine * Engine ) Sync ( beans ... interface { } ) error {
func ( engine * Engine ) Sync ( beans ... interface { } ) error {
session := engine . NewSession ( )
defer session . Close ( )
for _ , bean := range beans {
for _ , bean := range beans {
v := rValue ( bean )
v := rValue ( bean )
tableName := engine . tbName ( v )
tableName := engine . tbName ( v )
@ -1200,14 +1230,12 @@ func (engine *Engine) Sync(beans ...interface{}) error {
return err
return err
}
}
s := engine . NewSession ( )
isExist , err := session . Table ( bean ) . isTableExist ( tableName )
defer s . Close ( )
isExist , err := s . Table ( bean ) . isTableExist ( tableName )
if err != nil {
if err != nil {
return err
return err
}
}
if ! isExist {
if ! isExist {
err = engine . CreateTables ( bean )
err = session . createTable ( bean )
if err != nil {
if err != nil {
return err
return err
}
}
@ -1218,11 +1246,11 @@ func (engine *Engine) Sync(beans ...interface{}) error {
} * /
} * /
var isEmpty bool
var isEmpty bool
if isEmpty {
if isEmpty {
err = engine . DropTables ( bean )
err = session . dropTable ( bean )
if err != nil {
if err != nil {
return err
return err
}
}
err = engine . CreateTables ( bean )
err = session . createTable ( bean )
if err != nil {
if err != nil {
return err
return err
}
}
@ -1233,9 +1261,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
return err
return err
}
}
if ! isExist {
if ! isExist {
session := engine . NewSession ( )
if err := session . statement . setRefValue ( v ) ; err != nil {
defer session . Close ( )
if err := session . Statement . setRefValue ( v ) ; err != nil {
return err
return err
}
}
err = session . addColumn ( col . Name )
err = session . addColumn ( col . Name )
@ -1246,9 +1272,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
}
}
for name , index := range table . Indexes {
for name , index := range table . Indexes {
session := engine . NewSession ( )
if err := session . statement . setRefValue ( v ) ; err != nil {
defer session . Close ( )
if err := session . Statement . setRefValue ( v ) ; err != nil {
return err
return err
}
}
if index . Type == core . UniqueType {
if index . Type == core . UniqueType {
@ -1257,9 +1281,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
return err
return err
}
}
if ! isExist {
if ! isExist {
session := engine . NewSession ( )
if err := session . statement . setRefValue ( v ) ; err != nil {
defer session . Close ( )
if err := session . Statement . setRefValue ( v ) ; err != nil {
return err
return err
}
}
@ -1274,9 +1296,7 @@ func (engine *Engine) Sync(beans ...interface{}) error {
return err
return err
}
}
if ! isExist {
if ! isExist {
session := engine . NewSession ( )
if err := session . statement . setRefValue ( v ) ; err != nil {
defer session . Close ( )
if err := session . Statement . setRefValue ( v ) ; err != nil {
return err
return err
}
}
@ -1312,7 +1332,7 @@ func (engine *Engine) CreateTables(beans ...interface{}) error {
}
}
for _ , bean := range beans {
for _ , bean := range beans {
err = session . C reateTable( bean )
err = session . c reateTable( bean )
if err != nil {
if err != nil {
session . Rollback ( )
session . Rollback ( )
return err
return err
@ -1332,7 +1352,7 @@ func (engine *Engine) DropTables(beans ...interface{}) error {
}
}
for _ , bean := range beans {
for _ , bean := range beans {
err = session . D ropTable( bean )
err = session . d ropTable( bean )
if err != nil {
if err != nil {
session . Rollback ( )
session . Rollback ( )
return err
return err
@ -1356,17 +1376,24 @@ func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error)
}
}
// Query a raw sql and return records as []map[string][]byte
// Query a raw sql and return records as []map[string][]byte
func ( engine * Engine ) Query ( sql string , paramStr ... interface { } ) ( resultsSlice [ ] map [ string ] [ ] byte , err error ) {
func ( engine * Engine ) Query ( sqlorArgs ... interface { } ) ( resultsSlice [ ] map [ string ] [ ] byte , err error ) {
session := engine . NewSession ( )
session := engine . NewSession ( )
defer session . Close ( )
defer session . Close ( )
return session . Query ( sql , paramStr ... )
return session . Query ( sqlorArgs ... )
}
}
// QueryString runs a raw sql and return records as []map[string]string
// QueryString runs a raw sql and return records as []map[string]string
func ( engine * Engine ) QueryString ( sqlStr string , args ... interface { } ) ( [ ] map [ string ] string , error ) {
func ( engine * Engine ) QueryString ( sqlorArgs ... interface { } ) ( [ ] map [ string ] string , error ) {
session := engine . NewSession ( )
defer session . Close ( )
return session . QueryString ( sqlorArgs ... )
}
// QueryInterface runs a raw sql and return records as []map[string]interface{}
func ( engine * Engine ) QueryInterface ( sqlorArgs ... interface { } ) ( [ ] map [ string ] interface { } , error ) {
session := engine . NewSession ( )
session := engine . NewSession ( )
defer session . Close ( )
defer session . Close ( )
return session . QueryString ( sqlStr , args ... )
return session . QueryInterface ( sqlorA rgs ... )
}
}
// Insert one or more records
// Insert one or more records
@ -1410,6 +1437,13 @@ func (engine *Engine) Get(bean interface{}) (bool, error) {
return session . Get ( bean )
return session . Get ( bean )
}
}
// Exist returns true if the record exist otherwise return false
func ( engine * Engine ) Exist ( bean ... interface { } ) ( bool , error ) {
session := engine . NewSession ( )
defer session . Close ( )
return session . Exist ( bean ... )
}
// Find retrieve records from table, condiBeans's non-empty fields
// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
// map[int64]*Struct
@ -1419,6 +1453,13 @@ func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
return session . Find ( beans , condiBeans ... )
return session . Find ( beans , condiBeans ... )
}
}
// FindAndCount find the results and also return the counts
func ( engine * Engine ) FindAndCount ( rowsSlicePtr interface { } , condiBean ... interface { } ) ( int64 , error ) {
session := engine . NewSession ( )
defer session . Close ( )
return session . FindAndCount ( rowsSlicePtr , condiBean ... )
}
// Iterate record by record handle records from table, bean's non-empty fields
// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.
// are conditions.
func ( engine * Engine ) Iterate ( bean interface { } , fun IterFunc ) error {
func ( engine * Engine ) Iterate ( bean interface { } , fun IterFunc ) error {
@ -1435,10 +1476,10 @@ func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
}
}
// Count counts the records. bean's non-empty fields are conditions.
// Count counts the records. bean's non-empty fields are conditions.
func ( engine * Engine ) Count ( bean interface { } ) ( int64 , error ) {
func ( engine * Engine ) Count ( bean ... interface { } ) ( int64 , error ) {
session := engine . NewSession ( )
session := engine . NewSession ( )
defer session . Close ( )
defer session . Close ( )
return session . Count ( bean )
return session . Count ( bean ... )
}
}
// Sum sum the records by some column. bean's non-empty fields are conditions.
// Sum sum the records by some column. bean's non-empty fields are conditions.
@ -1448,6 +1489,13 @@ func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
return session . Sum ( bean , colName )
return session . Sum ( bean , colName )
}
}
// SumInt sum the records by some column. bean's non-empty fields are conditions.
func ( engine * Engine ) SumInt ( bean interface { } , colName string ) ( int64 , error ) {
session := engine . NewSession ( )
defer session . Close ( )
return session . SumInt ( bean , colName )
}
// Sums sum the records by some columns. bean's non-empty fields are conditions.
// Sums sum the records by some columns. bean's non-empty fields are conditions.
func ( engine * Engine ) Sums ( bean interface { } , colNames ... string ) ( [ ] float64 , error ) {
func ( engine * Engine ) Sums ( bean interface { } , colNames ... string ) ( [ ] float64 , error ) {
session := engine . NewSession ( )
session := engine . NewSession ( )
@ -1510,10 +1558,14 @@ func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
return results , lastError
return results , lastError
}
}
// NowTime2 return current time
// nowTime return current time
func ( engine * Engine ) NowTime2 ( sqlTypeName string ) ( interface { } , time . Time ) {
func ( engine * Engine ) nowTime ( col * core . Column ) ( interface { } , time . Time ) {
t := time . Now ( )
t := time . Now ( )
return engine . formatTime ( sqlTypeName , t . In ( engine . DatabaseTZ ) ) , t . In ( engine . TZLocation )
var tz = engine . DatabaseTZ
if ! col . DisableTimeZone && col . TimeZone != nil {
tz = col . TimeZone
}
return engine . formatTime ( col . SQLType . Name , t . In ( tz ) ) , t . In ( engine . TZLocation )
}
}
func ( engine * Engine ) formatColTime ( col * core . Column , t time . Time ) ( v interface { } ) {
func ( engine * Engine ) formatColTime ( col * core . Column , t time . Time ) ( v interface { } ) {
@ -1554,9 +1606,39 @@ func (engine *Engine) formatTime(sqlTypeName string, t time.Time) (v interface{}
return
return
}
}
// GetColumnMapper returns the column name mapper
func ( engine * Engine ) GetColumnMapper ( ) core . IMapper {
return engine . ColumnMapper
}
// GetTableMapper returns the table name mapper
func ( engine * Engine ) GetTableMapper ( ) core . IMapper {
return engine . TableMapper
}
// GetTZLocation returns time zone of the application
func ( engine * Engine ) GetTZLocation ( ) * time . Location {
return engine . TZLocation
}
// SetTZLocation sets time zone of the application
func ( engine * Engine ) SetTZLocation ( tz * time . Location ) {
engine . TZLocation = tz
}
// GetTZDatabase returns time zone of the database
func ( engine * Engine ) GetTZDatabase ( ) * time . Location {
return engine . DatabaseTZ
}
// SetTZDatabase sets time zone of the database
func ( engine * Engine ) SetTZDatabase ( tz * time . Location ) {
engine . DatabaseTZ = tz
}
// Unscoped always disable struct tag "deleted"
// Unscoped always disable struct tag "deleted"
func ( engine * Engine ) Unscoped ( ) * Session {
func ( engine * Engine ) Unscoped ( ) * Session {
session := engine . NewSession ( )
session := engine . NewSession ( )
session . IsAutoClose = true
session . i sAutoClose = true
return session . Unscoped ( )
return session . Unscoped ( )
}
}