diff --git a/cache/query.go b/cache/query.go index 7338b19..12998f3 100644 --- a/cache/query.go +++ b/cache/query.go @@ -224,6 +224,16 @@ func (h *queryHandler) AfterQuery() func(db *gorm.DB) { } if db.Error == nil { + destValue := reflect.Indirect(reflect.ValueOf(db.Statement.Dest)) + // 如果是结构体应该能提主键出来 + // 如果是数组需要判断内部元素是不是结构体,不是结构体的都提不了主键 + if destValue.Kind() == reflect.Slice || destValue.Kind() == reflect.Array { + if (destValue.Type().Elem().Kind() == reflect.Pointer && destValue.Type().Elem().Elem().Kind() != reflect.Struct) || + (destValue.Type().Elem().Kind() != reflect.Pointer && destValue.Type().Elem().Kind() != reflect.Struct) { + return + } + } + // error is nil -> cache not hit, we cache newly retrieved data primaryKeys, objects := getObjectsAfterLoad(db) @@ -311,7 +321,7 @@ func (h *queryHandler) AfterQuery() func(db *gorm.DB) { h.fillCallAfterQuery(db) // 下面处理命中了缓存的情况 - // 有以下几种err是专门用来传状态的:正常的cachehit 这种情况不存在error + // 有以下几种err是专门用来传状态的:正常的cacheHit 这种情况不存在error // RecordNotFoundCacheHit 这种情况只会在notfound之后出现 // SingleFlightHit 这种情况下error中除了SingleFlightHit还可能会存在其他error来自gorm的error // 且遇到任何一种hit我们都可以认为是命中了缓存 同时只可能命中至多两个hit(single+其他 diff --git a/test/functionality_test.go b/test/functionality_test.go index 9e1dc48..d568cc0 100644 --- a/test/functionality_test.go +++ b/test/functionality_test.go @@ -14,6 +14,8 @@ func TestPrimaryCacheFunctionality(t *testing.T) { testPrimaryFind(primaryCache, primaryDB) + testPluck(primaryCache, primaryDB) + testPrimaryUpdate(primaryCache, primaryDB) testPrimaryDelete(primaryCache, primaryDB) diff --git a/test/model.go b/test/model.go index 7db7e54..a479420 100644 --- a/test/model.go +++ b/test/model.go @@ -10,6 +10,7 @@ type TestModel struct { Value6 int64 `gorm:"column:value6"` Value7 int64 `gorm:"column:value7"` Value8 int64 `gorm:"column:value8"` + Value9 string `gorm:"column:value9"` PtrValue1 *int64 `gorm:"column:ptr_value1"` } diff --git a/test/plunk_test.go b/test/plunk_test.go new file mode 100644 index 0000000..e733947 --- /dev/null +++ b/test/plunk_test.go @@ -0,0 +1,16 @@ +package test + +import ( + . "github.com/smartystreets/goconvey/convey" + + "github.com/asjdf/gorm-cache/cache" + "gorm.io/gorm" +) + +func testPluck(cache cache.Cache, db *gorm.DB) { + var value9 []string + result := db.Model(&TestModel{}).Pluck("value9", &value9) + So(result.Error, ShouldBeNil) + So(len(value9), ShouldEqual, testSize) + So(value9[0], ShouldEqual, "1") +} diff --git a/test/prepare_test.go b/test/prepare_test.go index c7c095a..4de59e0 100644 --- a/test/prepare_test.go +++ b/test/prepare_test.go @@ -1,6 +1,9 @@ package test -import "gorm.io/gorm" +import ( + "gorm.io/gorm" + "strconv" +) func PrepareTableAndData(db *gorm.DB) error { err := db.AutoMigrate(&TestModel{}) @@ -21,6 +24,7 @@ func PrepareTableAndData(db *gorm.DB) error { Value6: int64(i), Value7: int64(i), Value8: int64(i), + Value9: strconv.Itoa(i), PtrValue1: &_pValue, } models = append(models, model)