Fix expiry issue and add support for multiple primary keys

Additionally correct RowsAffected report
This commit is contained in:
Daniel Sullivan 2019-10-28 11:37:42 +09:00
parent e20251c975
commit 16c9ce395a
2 changed files with 30 additions and 2 deletions

View File

@ -6,6 +6,7 @@ import (
"reflect" "reflect"
"sort" "sort"
"strconv" "strconv"
"strings"
"sync" "sync"
"time" "time"
) )
@ -110,7 +111,7 @@ func (c cache) GetItem(key string, offset int64) (interface{}, error) {
item.dataMutex.RLock() item.dataMutex.RLock()
defer item.dataMutex.RUnlock() defer item.dataMutex.RUnlock()
if (item.created+offset > time.Now().Unix()) || offset == -1 { if (item.created+(offset*1000000000) > time.Now().UnixNano()) || offset == -1 {
fmt.Print("Found \n") fmt.Print("Found \n")
c.mutex.RUnlock() c.mutex.RUnlock()
return item.data, item.err return item.data, item.err
@ -208,5 +209,24 @@ func getID(data interface{}) string {
d := reflect.ValueOf(data) d := reflect.ValueOf(data)
idField := d.FieldByName("ID") idField := d.FieldByName("ID")
if idField.IsValid() {
return fmt.Sprint(idField.Interface()) return fmt.Sprint(idField.Interface())
} }
// We haven't found an id the easy way so instead go through all of the primary key fields
// From those fields, get the value and concat using / as a seperator
idParts := []string{}
intType := reflect.TypeOf(data)
for i := 0; i < intType.NumField(); i++ {
tag := intType.Field(i).Tag
if strings.Contains(tag.Get("gorm"), "primary_key") {
idParts = append(idParts, d.Field(i).String())
}
}
if len(idParts) > 0 {
return strings.Join(idParts, "/")
}
return ""
}

View File

@ -79,6 +79,14 @@ func queryCallback(scope *Scope) {
if cacheResults != nil { if cacheResults != nil {
scope.Err(err) // Add any error if exists scope.Err(err) // Add any error if exists
results.Set(reflect.ValueOf(cacheResults)) results.Set(reflect.ValueOf(cacheResults))
switch reflect.ValueOf(cacheResults).Type().Kind() {
case reflect.Struct:
scope.db.RowsAffected = 1
case reflect.Slice:
scope.db.RowsAffected = int64(reflect.ValueOf(cacheResults).Len())
}
fmt.Println("Cache HIT") fmt.Println("Cache HIT")
readFromDB = false readFromDB = false
} else { } else {