Skip to content

Commit

Permalink
修复没有缓存RowsAffected导致Count得到0的问题 (#5)
Browse files Browse the repository at this point in the history
* fix count
  • Loading branch information
FourLeafTec authored Sep 21, 2022
1 parent f670a16 commit 00b422b
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions cache/after_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package cache
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"

"github.com/Pacific73/gorm-cache/config"
"github.com/Pacific73/gorm-cache/util"
"gorm.io/gorm"
Expand Down Expand Up @@ -48,7 +51,7 @@ func AfterQuery(cache *Gorm2Cache) func(db *gorm.DB) {
return
}
cache.Logger.CtxInfo(ctx, "[AfterQuery] set cache: %v", string(cacheBytes))
err = cache.SetSearchCache(ctx, string(cacheBytes), tableName, sql, vars...)
err = cache.SetSearchCache(ctx, fmt.Sprintf("%d|", db.RowsAffected)+string(cacheBytes), tableName, sql, vars...)
if err != nil {
cache.Logger.CtxError(ctx, "[AfterQuery] set search cache for sql: %s error: %v", sql, err)
return
Expand Down Expand Up @@ -102,7 +105,14 @@ func AfterQuery(cache *Gorm2Cache) func(db *gorm.DB) {
return
}
cache.Logger.CtxInfo(ctx, "[AfterQuery] get value: %s", cacheValue)
err = json.Unmarshal([]byte(cacheValue), db.Statement.Dest)
rowsAffectedPos := strings.Index(cacheValue, "|")
db.RowsAffected, err = strconv.ParseInt(cacheValue[:rowsAffectedPos], 10, 64)
if err != nil {
cache.Logger.CtxError(ctx, "[AfterQuery] unmarshal rows affected cache error: %v", err)
db.Error = util.ErrCacheUnmarshal
return
}
err = json.Unmarshal([]byte(cacheValue[rowsAffectedPos+1:]), db.Statement.Dest)
if err != nil {
cache.Logger.CtxError(ctx, "[AfterQuery] unmarshal search cache error: %v", err)
db.Error = util.ErrCacheUnmarshal
Expand Down

0 comments on commit 00b422b

Please sign in to comment.