Save cached model structs globally

This commit is contained in:
Jinzhu 2015-03-11 18:33:50 +08:00
parent b0cf9a9e4b
commit df33db6ff9
2 changed files with 12 additions and 16 deletions

View File

@ -23,7 +23,6 @@ type DB struct {
Value interface{} Value interface{}
Error error Error error
RowsAffected int64 RowsAffected int64
ModelStructs map[reflect.Type]*ModelStruct
callback *callback callback *callback
db sqlCommon db sqlCommon
parent *DB parent *DB
@ -69,7 +68,6 @@ func Open(dialect string, args ...interface{}) (DB, error) {
source: source, source: source,
values: map[string]interface{}{}, values: map[string]interface{}{},
db: dbSql, db: dbSql,
ModelStructs: map[reflect.Type]*ModelStruct{},
} }
db.parent = &db db.parent = &db
} }
@ -125,7 +123,7 @@ func (s *DB) LogMode(enable bool) *DB {
} }
func (s *DB) SingularTable(enable bool) { func (s *DB) SingularTable(enable bool) {
s.parent.ModelStructs = map[reflect.Type]*ModelStruct{} modelStructs = map[reflect.Type]*ModelStruct{}
s.parent.singularTable = enable s.parent.singularTable = enable
} }

View File

@ -11,6 +11,8 @@ import (
"time" "time"
) )
var modelStructs = map[reflect.Type]*ModelStruct{}
type ModelStruct struct { type ModelStruct struct {
PrimaryFields []*StructField PrimaryFields []*StructField
StructFields []*StructField StructFields []*StructField
@ -82,11 +84,9 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
scopeType = scopeType.Elem() scopeType = scopeType.Elem()
} }
if scope.db != nil { if value, ok := modelStructs[scopeType]; ok {
if value, ok := scope.db.parent.ModelStructs[scopeType]; ok {
return value return value
} }
}
modelStruct.ModelType = scopeType modelStruct.ModelType = scopeType
if scopeType.Kind() != reflect.Struct { if scopeType.Kind() != reflect.Struct {
@ -284,9 +284,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
modelStruct.StructFields = append(modelStruct.StructFields, field) modelStruct.StructFields = append(modelStruct.StructFields, field)
} }
if scope.db != nil { modelStructs[scopeType] = &modelStruct
scope.db.parent.ModelStructs[scopeType] = &modelStruct
}
return &modelStruct return &modelStruct
} }