From df33db6ff966ceb3ab036a1d4a8ece600401671e Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 11 Mar 2015 18:33:50 +0800 Subject: [PATCH] Save cached model structs globally --- main.go | 16 +++++++--------- model_struct.go | 12 +++++------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index 17102cde..c00bd810 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,6 @@ type DB struct { Value interface{} Error error RowsAffected int64 - ModelStructs map[reflect.Type]*ModelStruct callback *callback db sqlCommon parent *DB @@ -63,13 +62,12 @@ func Open(dialect string, args ...interface{}) (DB, error) { } db = DB{ - dialect: NewDialect(dialect), - logger: defaultLogger, - callback: DefaultCallback, - source: source, - values: map[string]interface{}{}, - db: dbSql, - ModelStructs: map[reflect.Type]*ModelStruct{}, + dialect: NewDialect(dialect), + logger: defaultLogger, + callback: DefaultCallback, + source: source, + values: map[string]interface{}{}, + db: dbSql, } db.parent = &db } @@ -125,7 +123,7 @@ func (s *DB) LogMode(enable bool) *DB { } func (s *DB) SingularTable(enable bool) { - s.parent.ModelStructs = map[reflect.Type]*ModelStruct{} + modelStructs = map[reflect.Type]*ModelStruct{} s.parent.singularTable = enable } diff --git a/model_struct.go b/model_struct.go index ffd0a522..02e23dfe 100644 --- a/model_struct.go +++ b/model_struct.go @@ -11,6 +11,8 @@ import ( "time" ) +var modelStructs = map[reflect.Type]*ModelStruct{} + type ModelStruct struct { PrimaryFields []*StructField StructFields []*StructField @@ -82,10 +84,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct { scopeType = scopeType.Elem() } - if scope.db != nil { - if value, ok := scope.db.parent.ModelStructs[scopeType]; ok { - return value - } + if value, ok := modelStructs[scopeType]; ok { + return value } modelStruct.ModelType = scopeType @@ -284,9 +284,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct { modelStruct.StructFields = append(modelStruct.StructFields, field) } - if scope.db != nil { - scope.db.parent.ModelStructs[scopeType] = &modelStruct - } + modelStructs[scopeType] = &modelStruct return &modelStruct }