Skip to content

Commit

Permalink
fix int64 primary key problem
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan committed Sep 30, 2020
1 parent 481895d commit 63f1f39
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/stores/sqlc/cachedsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ func (cc CachedConn) QueryRowIndex(v interface{}, key string, keyer func(primary
indexQuery IndexQueryFn, primaryQuery PrimaryQueryFn) error {
var primaryKey interface{}
var found bool
keyer = floatKeyer(keyer)
if err := cc.cache.TakeWithExpire(&primaryKey, key, func(val interface{}, expire time.Duration) (err error) {
primaryKey, err = indexQuery(cc.db, v)
if err != nil {
Expand Down Expand Up @@ -119,3 +120,16 @@ func (cc CachedConn) SetCache(key string, v interface{}) error {
func (cc CachedConn) Transact(fn func(sqlx.Session) error) error {
return cc.db.Transact(fn)
}

func floatKeyer(fn func(interface{}) string) func(interface{}) string {
return func(primary interface{}) string {
switch v := primary.(type) {
case float32:
return fn(int64(v))
case float64:
return fn(int64(v))
default:
return fn(primary)
}
}
}
43 changes: 43 additions & 0 deletions core/stores/sqlc/cachedsql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,45 @@ func TestCachedConnTransact(t *testing.T) {
assert.True(t, conn.transactValue)
}

func TestQueryRowNoCache(t *testing.T) {
s, err := miniredis.Run()
if err != nil {
t.Error(err)
}

const (
key = "user"
value = "any"
)
var user string
var ran bool
r := redis.NewRedis(s.Addr(), redis.NodeType)
conn := dummySqlConn{queryRow: func(v interface{}, q string, args ...interface{}) error {
user = value
ran = true
return nil
}}
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30))
err = c.QueryRowNoCache(&user, key)
assert.Nil(t, err)
assert.Equal(t, value, user)
assert.True(t, ran)
}

func TestFloatKeyer(t *testing.T) {
primaries := []interface{}{
float32(1),
float64(1),
}

for _, primary := range primaries {
val := floatKeyer(func(i interface{}) string {
return fmt.Sprint(i)
})(primary)
assert.Equal(t, "1", val)
}
}

func resetStats() {
atomic.StoreUint64(&stats.Total, 0)
atomic.StoreUint64(&stats.Hit, 0)
Expand All @@ -454,6 +493,7 @@ func resetStats() {
}

type dummySqlConn struct {
queryRow func(interface{}, string, ...interface{}) error
}

func (d dummySqlConn) Exec(query string, args ...interface{}) (sql.Result, error) {
Expand All @@ -465,6 +505,9 @@ func (d dummySqlConn) Prepare(query string) (sqlx.StmtSession, error) {
}

func (d dummySqlConn) QueryRow(v interface{}, query string, args ...interface{}) error {
if d.queryRow != nil {
return d.queryRow(v, query, args...)
}
return nil
}

Expand Down

0 comments on commit 63f1f39

Please sign in to comment.