Add getter setter for scope

This commit is contained in:
Jinzhu 2014-01-27 11:56:04 +08:00
parent 23feade663
commit eab146a275
1 changed files with 18 additions and 9 deletions

View File

@ -13,17 +13,17 @@ import (
) )
type Scope struct { type Scope struct {
Value interface{} Value interface{}
Search *search Search *search
Sql string Sql string
SqlVars []interface{} SqlVars []interface{}
db *DB db *DB
startedTransaction bool _values map[string]interface{}
} }
func (db *DB) NewScope(value interface{}) *Scope { func (db *DB) NewScope(value interface{}) *Scope {
db.Value = value db.Value = value
return &Scope{db: db, Search: db.search, Value: value} return &Scope{db: db, Search: db.search, Value: value, _values: map[string]interface{}{}}
} }
func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope { func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
@ -271,6 +271,15 @@ func (scope *Scope) Exec() {
} }
} }
func (scope *Scope) Get(name string) (value interface{}, ok bool) {
value, ok = scope._values[name]
return
}
func (scope *Scope) Set(name string, value interface{}) {
scope._values[name] = value
}
func (scope *Scope) Trace(t time.Time) { func (scope *Scope) Trace(t time.Time) {
if len(scope.Sql) > 0 { if len(scope.Sql) > 0 {
scope.db.slog(scope.Sql, t, scope.SqlVars...) scope.db.slog(scope.Sql, t, scope.SqlVars...)
@ -281,14 +290,14 @@ func (scope *Scope) Begin() *Scope {
if db, ok := scope.DB().(sqlDb); ok { if db, ok := scope.DB().(sqlDb); ok {
if tx, err := db.Begin(); err == nil { if tx, err := db.Begin(); err == nil {
scope.db.db = interface{}(tx).(sqlCommon) scope.db.db = interface{}(tx).(sqlCommon)
scope.startedTransaction = true scope.Set("gorm:started_transaction", true)
} }
} }
return scope return scope
} }
func (scope *Scope) CommitOrRollback() *Scope { func (scope *Scope) CommitOrRollback() *Scope {
if scope.startedTransaction { if _, ok := scope.Get("gorm:started_transaction"); ok {
if db, ok := scope.db.db.(sqlTx); ok { if db, ok := scope.db.db.(sqlTx); ok {
if scope.HasError() { if scope.HasError() {
db.Rollback() db.Rollback()