diff --git a/Makefile b/Makefile index 6ca7c14..c40536a 100644 --- a/Makefile +++ b/Makefile @@ -1,2 +1,2 @@ all: - go test ./v2 + go test gopkg.in/redis.v1 diff --git a/README.md b/README.md index 1d1372b..d3f6d7d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,45 @@ -New version -=========== +Redis client for Golang [![Build Status](https://travis-ci.org/vmihailenco/redis.png?branch=master)](https://travis-ci.org/go-redis/redis) +======================= -Make sure to check new version of the client that got better API and timeout support: https://github.com/vmihailenco/redis/tree/master/v2 +Supports: + +- Redis 2.8 commands except QUIT, MONITOR, SLOWLOG and SYNC. +- Pub/sub. +- Transactions. +- Pipelining. +- Connection pool. +- TLS connections. +- Thread safety. +- Timeouts. + +API docs: http://godoc.org/gopkg.in/redis.v1. +Examples: http://godoc.org/gopkg.in/redis.v1#pkg-examples. + +Installation +------------ + +Install: + + go get gopkg.in/redis.v1 + +Look and feel +------------- + +Some corner cases: + + SORT list LIMIT 0 2 ASC + vals, err := client.Sort("list", redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result() + + ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2 + vals, err := client.ZRangeByScoreWithScores("zset", redis.ZRangeByScore{ + Min: "-inf", + Max: "+inf", + Offset: 0, + Count: 2, + }).Result() + + ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM + vals, err := client.ZInterStore("out", redis.ZStore{Weights: []int64{2, 3}}, "zset1", "zset2").Result() + + EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello" + vals, err := client.Eval("return {KEYS[1],ARGV[1]}", []string{"key"}, []string{"hello"}).Result() diff --git a/v2/command.go b/command.go similarity index 100% rename from v2/command.go rename to command.go diff --git a/commands.go b/commands.go index 4c03583..c94adc1 100644 --- a/commands.go +++ b/commands.go @@ -2,83 +2,91 @@ package redis import ( "strconv" + "time" ) func formatFloat(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) } +func readTimeout(sec int64) time.Duration { + if sec == 0 { + return 0 + } + return time.Duration(sec+1) * time.Second +} + //------------------------------------------------------------------------------ -func (c *Client) Auth(password string) *StatusReq { - req := NewStatusReq("AUTH", password) +func (c *Client) Auth(password string) *StatusCmd { + req := NewStatusCmd("AUTH", password) c.Process(req) return req } -func (c *Client) Echo(message string) *StringReq { - req := NewStringReq("ECHO", message) +func (c *Client) Echo(message string) *StringCmd { + req := NewStringCmd("ECHO", message) c.Process(req) return req } -func (c *Client) Ping() *StatusReq { - req := NewStatusReq("PING") +func (c *Client) Ping() *StatusCmd { + req := NewStatusCmd("PING") c.Process(req) return req } -func (c *Client) Quit() *StatusReq { +func (c *Client) Quit() *StatusCmd { panic("not implemented") } -func (c *Client) Select(index int64) *StatusReq { - req := NewStatusReq("SELECT", strconv.FormatInt(index, 10)) +func (c *Client) Select(index int64) *StatusCmd { + req := NewStatusCmd("SELECT", strconv.FormatInt(index, 10)) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) Del(keys ...string) *IntReq { +func (c *Client) Del(keys ...string) *IntCmd { args := append([]string{"DEL"}, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) Dump(key string) *StringReq { - req := NewStringReq("DUMP", key) +func (c *Client) Dump(key string) *StringCmd { + req := NewStringCmd("DUMP", key) c.Process(req) return req } -func (c *Client) Exists(key string) *BoolReq { - req := NewBoolReq("EXISTS", key) +func (c *Client) Exists(key string) *BoolCmd { + req := NewBoolCmd("EXISTS", key) c.Process(req) return req } -func (c *Client) Expire(key string, seconds int64) *BoolReq { - req := NewBoolReq("EXPIRE", key, strconv.FormatInt(seconds, 10)) +func (c *Client) Expire(key string, dur time.Duration) *BoolCmd { + req := NewBoolCmd("EXPIRE", key, strconv.FormatInt(int64(dur/time.Second), 10)) c.Process(req) return req } -func (c *Client) ExpireAt(key string, timestamp int64) *BoolReq { - req := NewBoolReq("EXPIREAT", key, strconv.FormatInt(timestamp, 10)) +func (c *Client) ExpireAt(key string, tm time.Time) *BoolCmd { + req := NewBoolCmd("EXPIREAT", key, strconv.FormatInt(tm.Unix(), 10)) c.Process(req) return req } -func (c *Client) Keys(pattern string) *StringSliceReq { - req := NewStringSliceReq("KEYS", pattern) +func (c *Client) Keys(pattern string) *StringSliceCmd { + req := NewStringSliceCmd("KEYS", pattern) c.Process(req) return req } -func (c *Client) Migrate(host, port, key string, db, timeout int64) *StatusReq { - req := NewStatusReq( +func (c *Client) Migrate(host, port, key string, db, timeout int64) *StatusCmd { + req := NewStatusCmd( "MIGRATE", host, port, @@ -86,81 +94,86 @@ func (c *Client) Migrate(host, port, key string, db, timeout int64) *StatusReq { strconv.FormatInt(db, 10), strconv.FormatInt(timeout, 10), ) + req.setReadTimeout(readTimeout(timeout)) c.Process(req) return req } -func (c *Client) Move(key string, db int64) *BoolReq { - req := NewBoolReq("MOVE", key, strconv.FormatInt(db, 10)) +func (c *Client) Move(key string, db int64) *BoolCmd { + req := NewBoolCmd("MOVE", key, strconv.FormatInt(db, 10)) c.Process(req) return req } -func (c *Client) ObjectRefCount(keys ...string) *IntReq { +func (c *Client) ObjectRefCount(keys ...string) *IntCmd { args := append([]string{"OBJECT", "REFCOUNT"}, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) ObjectEncoding(keys ...string) *StringReq { +func (c *Client) ObjectEncoding(keys ...string) *StringCmd { args := append([]string{"OBJECT", "ENCODING"}, keys...) - req := NewStringReq(args...) + req := NewStringCmd(args...) c.Process(req) return req } -func (c *Client) ObjectIdleTime(keys ...string) *IntReq { +func (c *Client) ObjectIdleTime(keys ...string) *DurationCmd { args := append([]string{"OBJECT", "IDLETIME"}, keys...) - req := NewIntReq(args...) + req := NewDurationCmd(time.Second, args...) c.Process(req) return req } -func (c *Client) Persist(key string) *BoolReq { - req := NewBoolReq("PERSIST", key) +func (c *Client) Persist(key string) *BoolCmd { + req := NewBoolCmd("PERSIST", key) c.Process(req) return req } -func (c *Client) PExpire(key string, milliseconds int64) *BoolReq { - req := NewBoolReq("PEXPIRE", key, strconv.FormatInt(milliseconds, 10)) +func (c *Client) PExpire(key string, dur time.Duration) *BoolCmd { + req := NewBoolCmd("PEXPIRE", key, strconv.FormatInt(int64(dur/time.Millisecond), 10)) c.Process(req) return req } -func (c *Client) PExpireAt(key string, milliseconds int64) *BoolReq { - req := NewBoolReq("PEXPIREAT", key, strconv.FormatInt(milliseconds, 10)) +func (c *Client) PExpireAt(key string, tm time.Time) *BoolCmd { + req := NewBoolCmd( + "PEXPIREAT", + key, + strconv.FormatInt(tm.UnixNano()/int64(time.Millisecond), 10), + ) c.Process(req) return req } -func (c *Client) PTTL(key string) *IntReq { - req := NewIntReq("PTTL", key) +func (c *Client) PTTL(key string) *DurationCmd { + req := NewDurationCmd(time.Millisecond, "PTTL", key) c.Process(req) return req } -func (c *Client) RandomKey() *StringReq { - req := NewStringReq("RANDOMKEY") +func (c *Client) RandomKey() *StringCmd { + req := NewStringCmd("RANDOMKEY") c.Process(req) return req } -func (c *Client) Rename(key, newkey string) *StatusReq { - req := NewStatusReq("RENAME", key, newkey) +func (c *Client) Rename(key, newkey string) *StatusCmd { + req := NewStatusCmd("RENAME", key, newkey) c.Process(req) return req } -func (c *Client) RenameNX(key, newkey string) *BoolReq { - req := NewBoolReq("RENAMENX", key, newkey) +func (c *Client) RenameNX(key, newkey string) *BoolCmd { + req := NewBoolCmd("RENAMENX", key, newkey) c.Process(req) return req } -func (c *Client) Restore(key string, ttl int64, value string) *StatusReq { - req := NewStatusReq( +func (c *Client) Restore(key string, ttl int64, value string) *StatusCmd { + req := NewStatusCmd( "RESTORE", key, strconv.FormatInt(ttl, 10), @@ -179,7 +192,7 @@ type Sort struct { Store string } -func (c *Client) Sort(key string, sort Sort) *StringSliceReq { +func (c *Client) Sort(key string, sort Sort) *StringSliceCmd { args := []string{"SORT", key} if sort.By != "" { args = append(args, sort.By) @@ -199,27 +212,79 @@ func (c *Client) Sort(key string, sort Sort) *StringSliceReq { if sort.Store != "" { args = append(args, "STORE", sort.Store) } - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) TTL(key string) *IntReq { - req := NewIntReq("TTL", key) +func (c *Client) TTL(key string) *DurationCmd { + req := NewDurationCmd(time.Second, "TTL", key) c.Process(req) return req } -func (c *Client) Type(key string) *StatusReq { - req := NewStatusReq("TYPE", key) +func (c *Client) Type(key string) *StatusCmd { + req := NewStatusCmd("TYPE", key) + c.Process(req) + return req +} + +func (c *Client) Scan(cursor int64, match string, count int64) *ScanCmd { + args := []string{"SCAN", strconv.FormatInt(cursor, 10)} + if match != "" { + args = append(args, "MATCH", match) + } + if count > 0 { + args = append(args, "COUNT", strconv.FormatInt(count, 10)) + } + req := NewScanCmd(args...) + c.Process(req) + return req +} + +func (c *Client) SScan(key string, cursor int64, match string, count int64) *ScanCmd { + args := []string{"SSCAN", key, strconv.FormatInt(cursor, 10)} + if match != "" { + args = append(args, "MATCH", match) + } + if count > 0 { + args = append(args, "COUNT", strconv.FormatInt(count, 10)) + } + req := NewScanCmd(args...) + c.Process(req) + return req +} + +func (c *Client) HScan(key string, cursor int64, match string, count int64) *ScanCmd { + args := []string{"HSCAN", key, strconv.FormatInt(cursor, 10)} + if match != "" { + args = append(args, "MATCH", match) + } + if count > 0 { + args = append(args, "COUNT", strconv.FormatInt(count, 10)) + } + req := NewScanCmd(args...) + c.Process(req) + return req +} + +func (c *Client) ZScan(key string, cursor int64, match string, count int64) *ScanCmd { + args := []string{"ZSCAN", key, strconv.FormatInt(cursor, 10)} + if match != "" { + args = append(args, "MATCH", match) + } + if count > 0 { + args = append(args, "COUNT", strconv.FormatInt(count, 10)) + } + req := NewScanCmd(args...) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) Append(key, value string) *IntReq { - req := NewIntReq("APPEND", key, value) +func (c *Client) Append(key, value string) *IntCmd { + req := NewIntCmd("APPEND", key, value) c.Process(req) return req } @@ -228,7 +293,7 @@ type BitCount struct { Start, End int64 } -func (c *Client) BitCount(key string, bitCount *BitCount) *IntReq { +func (c *Client) BitCount(key string, bitCount *BitCount) *IntCmd { args := []string{"BITCOUNT", key} if bitCount != nil { args = append( @@ -237,61 +302,61 @@ func (c *Client) BitCount(key string, bitCount *BitCount) *IntReq { strconv.FormatInt(bitCount.End, 10), ) } - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) bitOp(op, destKey string, keys ...string) *IntReq { +func (c *Client) bitOp(op, destKey string, keys ...string) *IntCmd { args := []string{"BITOP", op, destKey} args = append(args, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) BitOpAnd(destKey string, keys ...string) *IntReq { +func (c *Client) BitOpAnd(destKey string, keys ...string) *IntCmd { return c.bitOp("AND", destKey, keys...) } -func (c *Client) BitOpOr(destKey string, keys ...string) *IntReq { +func (c *Client) BitOpOr(destKey string, keys ...string) *IntCmd { return c.bitOp("OR", destKey, keys...) } -func (c *Client) BitOpXor(destKey string, keys ...string) *IntReq { +func (c *Client) BitOpXor(destKey string, keys ...string) *IntCmd { return c.bitOp("XOR", destKey, keys...) } -func (c *Client) BitOpNot(destKey string, key string) *IntReq { +func (c *Client) BitOpNot(destKey string, key string) *IntCmd { return c.bitOp("NOT", destKey, key) } -func (c *Client) Decr(key string) *IntReq { - req := NewIntReq("DECR", key) +func (c *Client) Decr(key string) *IntCmd { + req := NewIntCmd("DECR", key) c.Process(req) return req } -func (c *Client) DecrBy(key string, decrement int64) *IntReq { - req := NewIntReq("DECRBY", key, strconv.FormatInt(decrement, 10)) +func (c *Client) DecrBy(key string, decrement int64) *IntCmd { + req := NewIntCmd("DECRBY", key, strconv.FormatInt(decrement, 10)) c.Process(req) return req } -func (c *Client) Get(key string) *StringReq { - req := NewStringReq("GET", key) +func (c *Client) Get(key string) *StringCmd { + req := NewStringCmd("GET", key) c.Process(req) return req } -func (c *Client) GetBit(key string, offset int64) *IntReq { - req := NewIntReq("GETBIT", key, strconv.FormatInt(offset, 10)) +func (c *Client) GetBit(key string, offset int64) *IntCmd { + req := NewIntCmd("GETBIT", key, strconv.FormatInt(offset, 10)) c.Process(req) return req } -func (c *Client) GetRange(key string, start, end int64) *StringReq { - req := NewStringReq( +func (c *Client) GetRange(key string, start, end int64) *StringCmd { + req := NewStringCmd( "GETRANGE", key, strconv.FormatInt(start, 10), @@ -301,70 +366,70 @@ func (c *Client) GetRange(key string, start, end int64) *StringReq { return req } -func (c *Client) GetSet(key, value string) *StringReq { - req := NewStringReq("GETSET", key, value) +func (c *Client) GetSet(key, value string) *StringCmd { + req := NewStringCmd("GETSET", key, value) c.Process(req) return req } -func (c *Client) Incr(key string) *IntReq { - req := NewIntReq("INCR", key) +func (c *Client) Incr(key string) *IntCmd { + req := NewIntCmd("INCR", key) c.Process(req) return req } -func (c *Client) IncrBy(key string, value int64) *IntReq { - req := NewIntReq("INCRBY", key, strconv.FormatInt(value, 10)) +func (c *Client) IncrBy(key string, value int64) *IntCmd { + req := NewIntCmd("INCRBY", key, strconv.FormatInt(value, 10)) c.Process(req) return req } -func (c *Client) IncrByFloat(key string, value float64) *FloatReq { - req := NewFloatReq("INCRBYFLOAT", key, formatFloat(value)) +func (c *Client) IncrByFloat(key string, value float64) *FloatCmd { + req := NewFloatCmd("INCRBYFLOAT", key, formatFloat(value)) c.Process(req) return req } -func (c *Client) MGet(keys ...string) *IfaceSliceReq { +func (c *Client) MGet(keys ...string) *SliceCmd { args := append([]string{"MGET"}, keys...) - req := NewIfaceSliceReq(args...) + req := NewSliceCmd(args...) c.Process(req) return req } -func (c *Client) MSet(pairs ...string) *StatusReq { +func (c *Client) MSet(pairs ...string) *StatusCmd { args := append([]string{"MSET"}, pairs...) - req := NewStatusReq(args...) + req := NewStatusCmd(args...) c.Process(req) return req } -func (c *Client) MSetNX(pairs ...string) *BoolReq { +func (c *Client) MSetNX(pairs ...string) *BoolCmd { args := append([]string{"MSETNX"}, pairs...) - req := NewBoolReq(args...) + req := NewBoolCmd(args...) c.Process(req) return req } -func (c *Client) PSetEx(key string, milliseconds int64, value string) *StatusReq { - req := NewStatusReq( +func (c *Client) PSetEx(key string, dur time.Duration, value string) *StatusCmd { + req := NewStatusCmd( "PSETEX", key, - strconv.FormatInt(milliseconds, 10), + strconv.FormatInt(int64(dur/time.Millisecond), 10), value, ) c.Process(req) return req } -func (c *Client) Set(key, value string) *StatusReq { - req := NewStatusReq("SET", key, value) +func (c *Client) Set(key, value string) *StatusCmd { + req := NewStatusCmd("SET", key, value) c.Process(req) return req } -func (c *Client) SetBit(key string, offset int64, value int) *IntReq { - req := NewIntReq( +func (c *Client) SetBit(key string, offset int64, value int) *IntCmd { + req := NewIntCmd( "SETBIT", key, strconv.FormatInt(offset, 10), @@ -374,187 +439,190 @@ func (c *Client) SetBit(key string, offset int64, value int) *IntReq { return req } -func (c *Client) SetEx(key string, seconds int64, value string) *StatusReq { - req := NewStatusReq("SETEX", key, strconv.FormatInt(seconds, 10), value) +func (c *Client) SetEx(key string, dur time.Duration, value string) *StatusCmd { + req := NewStatusCmd("SETEX", key, strconv.FormatInt(int64(dur/time.Second), 10), value) c.Process(req) return req } -func (c *Client) SetNX(key, value string) *BoolReq { - req := NewBoolReq("SETNX", key, value) +func (c *Client) SetNX(key, value string) *BoolCmd { + req := NewBoolCmd("SETNX", key, value) c.Process(req) return req } -func (c *Client) SetRange(key string, offset int64, value string) *IntReq { - req := NewIntReq("SETRANGE", key, strconv.FormatInt(offset, 10), value) +func (c *Client) SetRange(key string, offset int64, value string) *IntCmd { + req := NewIntCmd("SETRANGE", key, strconv.FormatInt(offset, 10), value) c.Process(req) return req } -func (c *Client) StrLen(key string) *IntReq { - req := NewIntReq("STRLEN", key) +func (c *Client) StrLen(key string) *IntCmd { + req := NewIntCmd("STRLEN", key) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) HDel(key string, fields ...string) *IntReq { +func (c *Client) HDel(key string, fields ...string) *IntCmd { args := append([]string{"HDEL", key}, fields...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) HExists(key, field string) *BoolReq { - req := NewBoolReq("HEXISTS", key, field) +func (c *Client) HExists(key, field string) *BoolCmd { + req := NewBoolCmd("HEXISTS", key, field) c.Process(req) return req } -func (c *Client) HGet(key, field string) *StringReq { - req := NewStringReq("HGET", key, field) +func (c *Client) HGet(key, field string) *StringCmd { + req := NewStringCmd("HGET", key, field) c.Process(req) return req } -func (c *Client) HGetAll(key string) *StringSliceReq { - req := NewStringSliceReq("HGETALL", key) +func (c *Client) HGetAll(key string) *StringSliceCmd { + req := NewStringSliceCmd("HGETALL", key) c.Process(req) return req } -func (c *Client) HGetAllMap(key string) *StringStringMapReq { - req := NewStringStringMapReq("HGETALL", key) +func (c *Client) HGetAllMap(key string) *StringStringMapCmd { + req := NewStringStringMapCmd("HGETALL", key) c.Process(req) return req } -func (c *Client) HIncrBy(key, field string, incr int64) *IntReq { - req := NewIntReq("HINCRBY", key, field, strconv.FormatInt(incr, 10)) +func (c *Client) HIncrBy(key, field string, incr int64) *IntCmd { + req := NewIntCmd("HINCRBY", key, field, strconv.FormatInt(incr, 10)) c.Process(req) return req } -func (c *Client) HIncrByFloat(key, field string, incr float64) *FloatReq { - req := NewFloatReq("HINCRBYFLOAT", key, field, formatFloat(incr)) +func (c *Client) HIncrByFloat(key, field string, incr float64) *FloatCmd { + req := NewFloatCmd("HINCRBYFLOAT", key, field, formatFloat(incr)) c.Process(req) return req } -func (c *Client) HKeys(key string) *StringSliceReq { - req := NewStringSliceReq("HKEYS", key) +func (c *Client) HKeys(key string) *StringSliceCmd { + req := NewStringSliceCmd("HKEYS", key) c.Process(req) return req } -func (c *Client) HLen(key string) *IntReq { - req := NewIntReq("HLEN", key) +func (c *Client) HLen(key string) *IntCmd { + req := NewIntCmd("HLEN", key) c.Process(req) return req } -func (c *Client) HMGet(key string, fields ...string) *IfaceSliceReq { +func (c *Client) HMGet(key string, fields ...string) *SliceCmd { args := append([]string{"HMGET", key}, fields...) - req := NewIfaceSliceReq(args...) + req := NewSliceCmd(args...) c.Process(req) return req } -func (c *Client) HMSet(key, field, value string, pairs ...string) *StatusReq { +func (c *Client) HMSet(key, field, value string, pairs ...string) *StatusCmd { args := append([]string{"HMSET", key, field, value}, pairs...) - req := NewStatusReq(args...) + req := NewStatusCmd(args...) c.Process(req) return req } -func (c *Client) HSet(key, field, value string) *BoolReq { - req := NewBoolReq("HSET", key, field, value) +func (c *Client) HSet(key, field, value string) *BoolCmd { + req := NewBoolCmd("HSET", key, field, value) c.Process(req) return req } -func (c *Client) HSetNX(key, field, value string) *BoolReq { - req := NewBoolReq("HSETNX", key, field, value) +func (c *Client) HSetNX(key, field, value string) *BoolCmd { + req := NewBoolCmd("HSETNX", key, field, value) c.Process(req) return req } -func (c *Client) HVals(key string) *StringSliceReq { - req := NewStringSliceReq("HVALS", key) +func (c *Client) HVals(key string) *StringSliceCmd { + req := NewStringSliceCmd("HVALS", key) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) BLPop(timeout int64, keys ...string) *StringSliceReq { +func (c *Client) BLPop(timeout int64, keys ...string) *StringSliceCmd { args := append([]string{"BLPOP"}, keys...) args = append(args, strconv.FormatInt(timeout, 10)) - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) + req.setReadTimeout(readTimeout(timeout)) c.Process(req) return req } -func (c *Client) BRPop(timeout int64, keys ...string) *StringSliceReq { +func (c *Client) BRPop(timeout int64, keys ...string) *StringSliceCmd { args := append([]string{"BRPOP"}, keys...) args = append(args, strconv.FormatInt(timeout, 10)) - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) + req.setReadTimeout(readTimeout(timeout)) c.Process(req) return req } -func (c *Client) BRPopLPush(source, destination string, timeout int64) *StringReq { - req := NewStringReq( +func (c *Client) BRPopLPush(source, destination string, timeout int64) *StringCmd { + req := NewStringCmd( "BRPOPLPUSH", source, destination, strconv.FormatInt(timeout, 10), ) + req.setReadTimeout(readTimeout(timeout)) c.Process(req) return req } -func (c *Client) LIndex(key string, index int64) *StringReq { - req := NewStringReq("LINDEX", key, strconv.FormatInt(index, 10)) +func (c *Client) LIndex(key string, index int64) *StringCmd { + req := NewStringCmd("LINDEX", key, strconv.FormatInt(index, 10)) c.Process(req) return req } -func (c *Client) LInsert(key, op, pivot, value string) *IntReq { - req := NewIntReq("LINSERT", key, op, pivot, value) +func (c *Client) LInsert(key, op, pivot, value string) *IntCmd { + req := NewIntCmd("LINSERT", key, op, pivot, value) c.Process(req) return req } -func (c *Client) LLen(key string) *IntReq { - req := NewIntReq("LLEN", key) +func (c *Client) LLen(key string) *IntCmd { + req := NewIntCmd("LLEN", key) c.Process(req) return req } -func (c *Client) LPop(key string) *StringReq { - req := NewStringReq("LPOP", key) +func (c *Client) LPop(key string) *StringCmd { + req := NewStringCmd("LPOP", key) c.Process(req) return req } -func (c *Client) LPush(key string, values ...string) *IntReq { +func (c *Client) LPush(key string, values ...string) *IntCmd { args := append([]string{"LPUSH", key}, values...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) LPushX(key, value string) *IntReq { - req := NewIntReq("LPUSHX", key, value) +func (c *Client) LPushX(key, value string) *IntCmd { + req := NewIntCmd("LPUSHX", key, value) c.Process(req) return req } -func (c *Client) LRange(key string, start, stop int64) *StringSliceReq { - req := NewStringSliceReq( +func (c *Client) LRange(key string, start, stop int64) *StringSliceCmd { + req := NewStringSliceCmd( "LRANGE", key, strconv.FormatInt(start, 10), @@ -564,20 +632,20 @@ func (c *Client) LRange(key string, start, stop int64) *StringSliceReq { return req } -func (c *Client) LRem(key string, count int64, value string) *IntReq { - req := NewIntReq("LREM", key, strconv.FormatInt(count, 10), value) +func (c *Client) LRem(key string, count int64, value string) *IntCmd { + req := NewIntCmd("LREM", key, strconv.FormatInt(count, 10), value) c.Process(req) return req } -func (c *Client) LSet(key string, index int64, value string) *StatusReq { - req := NewStatusReq("LSET", key, strconv.FormatInt(index, 10), value) +func (c *Client) LSet(key string, index int64, value string) *StatusCmd { + req := NewStatusCmd("LSET", key, strconv.FormatInt(index, 10), value) c.Process(req) return req } -func (c *Client) LTrim(key string, start, stop int64) *StatusReq { - req := NewStatusReq( +func (c *Client) LTrim(key string, start, stop int64) *StatusCmd { + req := NewStatusCmd( "LTRIM", key, strconv.FormatInt(start, 10), @@ -587,121 +655,121 @@ func (c *Client) LTrim(key string, start, stop int64) *StatusReq { return req } -func (c *Client) RPop(key string) *StringReq { - req := NewStringReq("RPOP", key) +func (c *Client) RPop(key string) *StringCmd { + req := NewStringCmd("RPOP", key) c.Process(req) return req } -func (c *Client) RPopLPush(source, destination string) *StringReq { - req := NewStringReq("RPOPLPUSH", source, destination) +func (c *Client) RPopLPush(source, destination string) *StringCmd { + req := NewStringCmd("RPOPLPUSH", source, destination) c.Process(req) return req } -func (c *Client) RPush(key string, values ...string) *IntReq { +func (c *Client) RPush(key string, values ...string) *IntCmd { args := append([]string{"RPUSH", key}, values...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) RPushX(key string, value string) *IntReq { - req := NewIntReq("RPUSHX", key, value) +func (c *Client) RPushX(key string, value string) *IntCmd { + req := NewIntCmd("RPUSHX", key, value) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) SAdd(key string, members ...string) *IntReq { +func (c *Client) SAdd(key string, members ...string) *IntCmd { args := append([]string{"SADD", key}, members...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) SCard(key string) *IntReq { - req := NewIntReq("SCARD", key) +func (c *Client) SCard(key string) *IntCmd { + req := NewIntCmd("SCARD", key) c.Process(req) return req } -func (c *Client) SDiff(keys ...string) *StringSliceReq { +func (c *Client) SDiff(keys ...string) *StringSliceCmd { args := append([]string{"SDIFF"}, keys...) - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) SDiffStore(destination string, keys ...string) *IntReq { +func (c *Client) SDiffStore(destination string, keys ...string) *IntCmd { args := append([]string{"SDIFFSTORE", destination}, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) SInter(keys ...string) *StringSliceReq { +func (c *Client) SInter(keys ...string) *StringSliceCmd { args := append([]string{"SINTER"}, keys...) - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) SInterStore(destination string, keys ...string) *IntReq { +func (c *Client) SInterStore(destination string, keys ...string) *IntCmd { args := append([]string{"SINTERSTORE", destination}, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) SIsMember(key, member string) *BoolReq { - req := NewBoolReq("SISMEMBER", key, member) +func (c *Client) SIsMember(key, member string) *BoolCmd { + req := NewBoolCmd("SISMEMBER", key, member) c.Process(req) return req } -func (c *Client) SMembers(key string) *StringSliceReq { - req := NewStringSliceReq("SMEMBERS", key) +func (c *Client) SMembers(key string) *StringSliceCmd { + req := NewStringSliceCmd("SMEMBERS", key) c.Process(req) return req } -func (c *Client) SMove(source, destination, member string) *BoolReq { - req := NewBoolReq("SMOVE", source, destination, member) +func (c *Client) SMove(source, destination, member string) *BoolCmd { + req := NewBoolCmd("SMOVE", source, destination, member) c.Process(req) return req } -func (c *Client) SPop(key string) *StringReq { - req := NewStringReq("SPOP", key) +func (c *Client) SPop(key string) *StringCmd { + req := NewStringCmd("SPOP", key) c.Process(req) return req } -func (c *Client) SRandMember(key string) *StringReq { - req := NewStringReq("SRANDMEMBER", key) +func (c *Client) SRandMember(key string) *StringCmd { + req := NewStringCmd("SRANDMEMBER", key) c.Process(req) return req } -func (c *Client) SRem(key string, members ...string) *IntReq { +func (c *Client) SRem(key string, members ...string) *IntCmd { args := append([]string{"SREM", key}, members...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) SUnion(keys ...string) *StringSliceReq { +func (c *Client) SUnion(keys ...string) *StringSliceCmd { args := append([]string{"SUNION"}, keys...) - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) SUnionStore(destination string, keys ...string) *IntReq { +func (c *Client) SUnionStore(destination string, keys ...string) *IntCmd { args := append([]string{"SUNIONSTORE", destination}, keys...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } @@ -718,30 +786,30 @@ type ZStore struct { Aggregate string } -func (c *Client) ZAdd(key string, members ...Z) *IntReq { +func (c *Client) ZAdd(key string, members ...Z) *IntCmd { args := []string{"ZADD", key} for _, m := range members { args = append(args, formatFloat(m.Score), m.Member) } - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) ZCard(key string) *IntReq { - req := NewIntReq("ZCARD", key) +func (c *Client) ZCard(key string) *IntCmd { + req := NewIntCmd("ZCARD", key) c.Process(req) return req } -func (c *Client) ZCount(key, min, max string) *IntReq { - req := NewIntReq("ZCOUNT", key, min, max) +func (c *Client) ZCount(key, min, max string) *IntCmd { + req := NewIntCmd("ZCOUNT", key, min, max) c.Process(req) return req } -func (c *Client) ZIncrBy(key string, increment float64, member string) *FloatReq { - req := NewFloatReq("ZINCRBY", key, formatFloat(increment), member) +func (c *Client) ZIncrBy(key string, increment float64, member string) *FloatCmd { + req := NewFloatCmd("ZINCRBY", key, formatFloat(increment), member) c.Process(req) return req } @@ -750,7 +818,7 @@ func (c *Client) ZInterStore( destination string, store ZStore, keys ...string, -) *IntReq { +) *IntCmd { args := []string{"ZINTERSTORE", destination, strconv.FormatInt(int64(len(keys)), 10)} args = append(args, keys...) if len(store.Weights) > 0 { @@ -762,12 +830,12 @@ func (c *Client) ZInterStore( if store.Aggregate != "" { args = append(args, "AGGREGATE", store.Aggregate) } - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) zRange(key string, start, stop int64, withScores bool) *StringSliceReq { +func (c *Client) zRange(key string, start, stop int64, withScores bool) *StringSliceCmd { args := []string{ "ZRANGE", key, @@ -777,20 +845,20 @@ func (c *Client) zRange(key string, start, stop int64, withScores bool) *StringS if withScores { args = append(args, "WITHSCORES") } - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) ZRange(key string, start, stop int64) *StringSliceReq { +func (c *Client) ZRange(key string, start, stop int64) *StringSliceCmd { return c.zRange(key, start, stop, false) } -func (c *Client) ZRangeWithScores(key string, start, stop int64) *StringSliceReq { +func (c *Client) ZRangeWithScores(key string, start, stop int64) *StringSliceCmd { return c.zRange(key, start, stop, true) } -func (c *Client) ZRangeWithScoresMap(key string, start, stop int64) *StringFloatMapReq { +func (c *Client) ZRangeWithScoresMap(key string, start, stop int64) *StringFloatMapCmd { args := []string{ "ZRANGE", key, @@ -798,73 +866,73 @@ func (c *Client) ZRangeWithScoresMap(key string, start, stop int64) *StringFloat strconv.FormatInt(stop, 10), "WITHSCORES", } - req := NewStringFloatMapReq(args...) + req := NewStringFloatMapCmd(args...) c.Process(req) return req } -func (c *Client) zRangeByScore( - key string, - min, max string, - withScores bool, - offset, count int64, -) *StringSliceReq { - args := []string{"ZRANGEBYSCORE", key, min, max} +type ZRangeByScore struct { + Min, Max string + + Offset, Count int64 +} + +func (c *Client) zRangeByScore(key string, opt ZRangeByScore, withScores bool) *StringSliceCmd { + args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max} if withScores { args = append(args, "WITHSCORES") } - if offset != 0 || count != 0 { + if opt.Offset != 0 || opt.Count != 0 { args = append( args, "LIMIT", - strconv.FormatInt(offset, 10), - strconv.FormatInt(count, 10), + strconv.FormatInt(opt.Offset, 10), + strconv.FormatInt(opt.Count, 10), ) } - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) ZRangeByScore(key string, min, max string, offset, count int64) *StringSliceReq { - return c.zRangeByScore(key, min, max, false, offset, count) +func (c *Client) ZRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd { + return c.zRangeByScore(key, opt, false) } -func (c *Client) ZRangeByScoreWithScores(key, min, max string, offset, count int64) *StringSliceReq { - return c.zRangeByScore(key, min, max, true, offset, count) +func (c *Client) ZRangeByScoreWithScores(key string, opt ZRangeByScore) *StringSliceCmd { + return c.zRangeByScore(key, opt, true) } -func (c *Client) ZRangeByScoreWithScoresMap( - key string, min, max string, offset, count int64) *StringFloatMapReq { - args := []string{"ZRANGEBYSCORE", key, min, max, "WITHSCORES"} - if offset != 0 || count != 0 { +func (c *Client) ZRangeByScoreWithScoresMap(key string, opt ZRangeByScore) *StringFloatMapCmd { + args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max, "WITHSCORES"} + if opt.Offset != 0 || opt.Count != 0 { args = append( args, "LIMIT", - strconv.FormatInt(offset, 10), - strconv.FormatInt(count, 10), + strconv.FormatInt(opt.Offset, 10), + strconv.FormatInt(opt.Count, 10), ) } - req := NewStringFloatMapReq(args...) + req := NewStringFloatMapCmd(args...) c.Process(req) return req } -func (c *Client) ZRank(key, member string) *IntReq { - req := NewIntReq("ZRANK", key, member) +func (c *Client) ZRank(key, member string) *IntCmd { + req := NewIntCmd("ZRANK", key, member) c.Process(req) return req } -func (c *Client) ZRem(key string, members ...string) *IntReq { +func (c *Client) ZRem(key string, members ...string) *IntCmd { args := append([]string{"ZREM", key}, members...) - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } -func (c *Client) ZRemRangeByRank(key string, start, stop int64) *IntReq { - req := NewIntReq( +func (c *Client) ZRemRangeByRank(key string, start, stop int64) *IntCmd { + req := NewIntCmd( "ZREMRANGEBYRANK", key, strconv.FormatInt(start, 10), @@ -874,87 +942,86 @@ func (c *Client) ZRemRangeByRank(key string, start, stop int64) *IntReq { return req } -func (c *Client) ZRemRangeByScore(key, min, max string) *IntReq { - req := NewIntReq("ZREMRANGEBYSCORE", key, min, max) +func (c *Client) ZRemRangeByScore(key, min, max string) *IntCmd { + req := NewIntCmd("ZREMRANGEBYSCORE", key, min, max) c.Process(req) return req } -func (c *Client) zRevRange(key, start, stop string, withScores bool) *StringSliceReq { +func (c *Client) zRevRange(key, start, stop string, withScores bool) *StringSliceCmd { args := []string{"ZREVRANGE", key, start, stop} if withScores { args = append(args, "WITHSCORES") } - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) ZRevRange(key, start, stop string) *StringSliceReq { +func (c *Client) ZRevRange(key, start, stop string) *StringSliceCmd { return c.zRevRange(key, start, stop, false) } -func (c *Client) ZRevRangeWithScores(key, start, stop string) *StringSliceReq { +func (c *Client) ZRevRangeWithScores(key, start, stop string) *StringSliceCmd { return c.zRevRange(key, start, stop, true) } -func (c *Client) ZRevRangeWithScoresMap(key, start, stop string) *StringFloatMapReq { +func (c *Client) ZRevRangeWithScoresMap(key, start, stop string) *StringFloatMapCmd { args := []string{"ZREVRANGE", key, start, stop, "WITHSCORES"} - req := NewStringFloatMapReq(args...) + req := NewStringFloatMapCmd(args...) c.Process(req) return req } -func (c *Client) zRevRangeByScore(key, start, stop string, withScores bool, offset, count int64) *StringSliceReq { - args := []string{"ZREVRANGEBYSCORE", key, start, stop} +func (c *Client) zRevRangeByScore(key string, opt ZRangeByScore, withScores bool) *StringSliceCmd { + args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min} if withScores { args = append(args, "WITHSCORES") } - if offset != 0 || count != 0 { + if opt.Offset != 0 || opt.Count != 0 { args = append( args, "LIMIT", - strconv.FormatInt(offset, 10), - strconv.FormatInt(count, 10), + strconv.FormatInt(opt.Offset, 10), + strconv.FormatInt(opt.Count, 10), ) } - req := NewStringSliceReq(args...) + req := NewStringSliceCmd(args...) c.Process(req) return req } -func (c *Client) ZRevRangeByScore(key, start, stop string, offset, count int64) *StringSliceReq { - return c.zRevRangeByScore(key, start, stop, false, offset, count) +func (c *Client) ZRevRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd { + return c.zRevRangeByScore(key, opt, false) } -func (c *Client) ZRevRangeByScoreWithScores(key, start, stop string, offset, count int64) *StringSliceReq { - return c.zRevRangeByScore(key, start, stop, true, offset, count) +func (c *Client) ZRevRangeByScoreWithScores(key string, opt ZRangeByScore) *StringSliceCmd { + return c.zRevRangeByScore(key, opt, true) } -func (c *Client) ZRevRangeByScoreWithScoresMap( - key, start, stop string, offset, count int64) *StringFloatMapReq { - args := []string{"ZREVRANGEBYSCORE", key, start, stop, "WITHSCORES"} - if offset != 0 || count != 0 { +func (c *Client) ZRevRangeByScoreWithScoresMap(key string, opt ZRangeByScore) *StringFloatMapCmd { + args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min, "WITHSCORES"} + if opt.Offset != 0 || opt.Count != 0 { args = append( args, "LIMIT", - strconv.FormatInt(offset, 10), - strconv.FormatInt(count, 10), + strconv.FormatInt(opt.Offset, 10), + strconv.FormatInt(opt.Count, 10), ) } - req := NewStringFloatMapReq(args...) + req := NewStringFloatMapCmd(args...) c.Process(req) return req } -func (c *Client) ZRevRank(key, member string) *IntReq { - req := NewIntReq("ZREVRANK", key, member) +func (c *Client) ZRevRank(key, member string) *IntCmd { + req := NewIntCmd("ZREVRANK", key, member) c.Process(req) return req } -func (c *Client) ZScore(key, member string) *FloatReq { - req := NewFloatReq("ZSCORE", key, member) +func (c *Client) ZScore(key, member string) *FloatCmd { + req := NewFloatCmd("ZSCORE", key, member) c.Process(req) return req } @@ -963,7 +1030,7 @@ func (c *Client) ZUnionStore( destination string, store ZStore, keys ...string, -) *IntReq { +) *IntCmd { args := []string{"ZUNIONSTORE", destination, strconv.FormatInt(int64(len(keys)), 10)} args = append(args, keys...) if len(store.Weights) > 0 { @@ -975,122 +1042,118 @@ func (c *Client) ZUnionStore( if store.Aggregate != "" { args = append(args, "AGGREGATE", store.Aggregate) } - req := NewIntReq(args...) + req := NewIntCmd(args...) c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) BgRewriteAOF() *StatusReq { - req := NewStatusReq("BGREWRITEAOF") +func (c *Client) BgRewriteAOF() *StatusCmd { + req := NewStatusCmd("BGREWRITEAOF") c.Process(req) return req } -func (c *Client) BgSave() *StatusReq { - req := NewStatusReq("BGSAVE") +func (c *Client) BgSave() *StatusCmd { + req := NewStatusCmd("BGSAVE") c.Process(req) return req } -func (c *Client) ClientKill(ipPort string) *StatusReq { - req := NewStatusReq("CLIENT", "KILL", ipPort) +func (c *Client) ClientKill(ipPort string) *StatusCmd { + req := NewStatusCmd("CLIENT", "KILL", ipPort) c.Process(req) return req } -func (c *Client) ClientList() *StringReq { - req := NewStringReq("CLIENT", "LIST") +func (c *Client) ClientList() *StringCmd { + req := NewStringCmd("CLIENT", "LIST") c.Process(req) return req } -func (c *Client) ConfigGet(parameter string) *IfaceSliceReq { - req := NewIfaceSliceReq("CONFIG", "GET", parameter) +func (c *Client) ConfigGet(parameter string) *SliceCmd { + req := NewSliceCmd("CONFIG", "GET", parameter) c.Process(req) return req } -func (c *Client) ConfigResetStat() *StatusReq { - req := NewStatusReq("CONFIG", "RESETSTAT") +func (c *Client) ConfigResetStat() *StatusCmd { + req := NewStatusCmd("CONFIG", "RESETSTAT") c.Process(req) return req } -func (c *Client) ConfigSet(parameter, value string) *StatusReq { - req := NewStatusReq("CONFIG", "SET", parameter, value) +func (c *Client) ConfigSet(parameter, value string) *StatusCmd { + req := NewStatusCmd("CONFIG", "SET", parameter, value) c.Process(req) return req } -func (c *Client) DbSize() *IntReq { - req := NewIntReq("DBSIZE") +func (c *Client) DbSize() *IntCmd { + req := NewIntCmd("DBSIZE") c.Process(req) return req } -func (c *Client) FlushAll() *StatusReq { - req := NewStatusReq("FLUSHALL") +func (c *Client) FlushAll() *StatusCmd { + req := NewStatusCmd("FLUSHALL") c.Process(req) return req } -func (c *Client) FlushDb() *StatusReq { - req := NewStatusReq("FLUSHDB") +func (c *Client) FlushDb() *StatusCmd { + req := NewStatusCmd("FLUSHDB") c.Process(req) return req } -func (c *Client) Info() *StringReq { - req := NewStringReq("INFO") +func (c *Client) Info() *StringCmd { + req := NewStringCmd("INFO") c.Process(req) return req } -func (c *Client) LastSave() *IntReq { - req := NewIntReq("LASTSAVE") +func (c *Client) LastSave() *IntCmd { + req := NewIntCmd("LASTSAVE") c.Process(req) return req } -func (c *Client) Monitor() { - panic("not implemented") -} - -func (c *Client) Save() *StatusReq { - req := NewStatusReq("SAVE") +func (c *Client) Save() *StatusCmd { + req := NewStatusCmd("SAVE") c.Process(req) return req } -func (c *Client) shutdown(modifier string) *StatusReq { +func (c *Client) shutdown(modifier string) *StatusCmd { var args []string if modifier == "" { args = []string{"SHUTDOWN"} } else { args = []string{"SHUTDOWN", modifier} } - req := NewStatusReq(args...) + req := NewStatusCmd(args...) c.Process(req) c.Close() return req } -func (c *Client) Shutdown() *StatusReq { +func (c *Client) Shutdown() *StatusCmd { return c.shutdown("") } -func (c *Client) ShutdownSave() *StatusReq { +func (c *Client) ShutdownSave() *StatusCmd { return c.shutdown("SAVE") } -func (c *Client) ShutdownNoSave() *StatusReq { +func (c *Client) ShutdownNoSave() *StatusCmd { return c.shutdown("NOSAVE") } -func (c *Client) SlaveOf(host, port string) *StatusReq { - req := NewStatusReq("SLAVEOF", host, port) +func (c *Client) SlaveOf(host, port string) *StatusCmd { + req := NewStatusCmd("SLAVEOF", host, port) c.Process(req) return req } @@ -1103,53 +1166,61 @@ func (c *Client) Sync() { panic("not implemented") } -func (c *Client) Time() *StringSliceReq { - req := NewStringSliceReq("TIME") +func (c *Client) Time() *StringSliceCmd { + req := NewStringSliceCmd("TIME") c.Process(req) return req } //------------------------------------------------------------------------------ -func (c *Client) Eval(script string, keys []string, args []string) *IfaceReq { +func (c *Client) Eval(script string, keys []string, args []string) *Cmd { reqArgs := []string{"EVAL", script, strconv.FormatInt(int64(len(keys)), 10)} reqArgs = append(reqArgs, keys...) reqArgs = append(reqArgs, args...) - req := NewIfaceReq(reqArgs...) + req := NewCmd(reqArgs...) c.Process(req) return req } -func (c *Client) EvalSha(sha1 string, keys []string, args []string) *IfaceReq { +func (c *Client) EvalSha(sha1 string, keys []string, args []string) *Cmd { reqArgs := []string{"EVALSHA", sha1, strconv.FormatInt(int64(len(keys)), 10)} reqArgs = append(reqArgs, keys...) reqArgs = append(reqArgs, args...) - req := NewIfaceReq(reqArgs...) + req := NewCmd(reqArgs...) c.Process(req) return req } -func (c *Client) ScriptExists(scripts ...string) *BoolSliceReq { +func (c *Client) ScriptExists(scripts ...string) *BoolSliceCmd { args := append([]string{"SCRIPT", "EXISTS"}, scripts...) - req := NewBoolSliceReq(args...) + req := NewBoolSliceCmd(args...) c.Process(req) return req } -func (c *Client) ScriptFlush() *StatusReq { - req := NewStatusReq("SCRIPT", "FLUSH") +func (c *Client) ScriptFlush() *StatusCmd { + req := NewStatusCmd("SCRIPT", "FLUSH") c.Process(req) return req } -func (c *Client) ScriptKill() *StatusReq { - req := NewStatusReq("SCRIPT", "KILL") +func (c *Client) ScriptKill() *StatusCmd { + req := NewStatusCmd("SCRIPT", "KILL") c.Process(req) return req } -func (c *Client) ScriptLoad(script string) *StringReq { - req := NewStringReq("SCRIPT", "LOAD", script) +func (c *Client) ScriptLoad(script string) *StringCmd { + req := NewStringCmd("SCRIPT", "LOAD", script) + c.Process(req) + return req +} + +//------------------------------------------------------------------------------ + +func (c *Client) DebugObject(key string) *StringCmd { + req := NewStringCmd("DEBUG", "OBJECT", key) c.Process(req) return req } diff --git a/connpool.go b/connpool.go deleted file mode 100644 index 15154c6..0000000 --- a/connpool.go +++ /dev/null @@ -1,197 +0,0 @@ -package redis - -import ( - "log" - "net" - "os" - "sync" - - "github.com/vmihailenco/bufio" -) - -type Conn struct { - RW net.Conn - Rd reader -} - -func NewConn(rw net.Conn) *Conn { - return &Conn{ - RW: rw, - Rd: bufio.NewReaderSize(rw, 1024), - } -} - -type ConnPool interface { - Get() (*Conn, bool, error) - Add(*Conn) error - Remove(*Conn) error - Len() int - Close() error -} - -//------------------------------------------------------------------------------ - -type MultiConnPool struct { - Logger *log.Logger - cond *sync.Cond - conns []*Conn - OpenConn OpenConnFunc - CloseConn CloseConnFunc - cap, MaxCap int -} - -func NewMultiConnPool(openConn OpenConnFunc, closeConn CloseConnFunc, maxCap int) *MultiConnPool { - logger := log.New( - os.Stdout, - "redis.connpool: ", - log.Ldate|log.Ltime|log.Lshortfile, - ) - return &MultiConnPool{ - cond: sync.NewCond(&sync.Mutex{}), - Logger: logger, - conns: make([]*Conn, 0), - OpenConn: openConn, - CloseConn: closeConn, - MaxCap: maxCap, - } -} - -func (p *MultiConnPool) Get() (*Conn, bool, error) { - p.cond.L.Lock() - defer p.cond.L.Unlock() - - for len(p.conns) == 0 && p.cap >= p.MaxCap { - p.cond.Wait() - } - - if len(p.conns) == 0 { - rw, err := p.OpenConn() - if err != nil { - return nil, false, err - } - - p.cap++ - return NewConn(rw), true, nil - } - - last := len(p.conns) - 1 - conn := p.conns[last] - p.conns[last] = nil - p.conns = p.conns[:last] - - return conn, false, nil -} - -func (p *MultiConnPool) Add(conn *Conn) error { - p.cond.L.Lock() - defer p.cond.L.Unlock() - p.conns = append(p.conns, conn) - p.cond.Signal() - return nil -} - -func (p *MultiConnPool) Remove(conn *Conn) error { - defer func() { - p.cond.L.Lock() - p.cap-- - p.cond.Signal() - p.cond.L.Unlock() - }() - if conn == nil { - return nil - } - return p.closeConn(conn) -} - -func (p *MultiConnPool) Len() int { - return len(p.conns) -} - -func (p *MultiConnPool) Close() error { - p.cond.L.Lock() - defer p.cond.L.Unlock() - for _, conn := range p.conns { - err := p.closeConn(conn) - if err != nil { - return err - } - } - p.conns = make([]*Conn, 0) - p.cap = 0 - return nil -} - -func (p *MultiConnPool) closeConn(conn *Conn) error { - if p.CloseConn != nil { - err := p.CloseConn(conn.RW) - if err != nil { - return err - } - } - return conn.RW.Close() -} - -//------------------------------------------------------------------------------ - -type SingleConnPool struct { - mtx sync.Mutex - pool ConnPool - conn *Conn - isReusable bool -} - -func NewSingleConnPoolConn(pool ConnPool, conn *Conn, isReusable bool) *SingleConnPool { - return &SingleConnPool{ - pool: pool, - conn: conn, - isReusable: isReusable, - } -} - -func NewSingleConnPool(pool ConnPool, isReusable bool) *SingleConnPool { - return NewSingleConnPoolConn(pool, nil, isReusable) -} - -func (p *SingleConnPool) Get() (*Conn, bool, error) { - p.mtx.Lock() - defer p.mtx.Unlock() - if p.conn != nil { - return p.conn, false, nil - } - conn, isNew, err := p.pool.Get() - if err != nil { - return nil, false, err - } - p.conn = conn - return p.conn, isNew, nil -} - -func (p *SingleConnPool) Add(conn *Conn) error { - return nil -} - -func (p *SingleConnPool) Remove(conn *Conn) error { - return nil -} - -func (p *SingleConnPool) Len() int { - return 1 -} - -func (p *SingleConnPool) Close() error { - p.mtx.Lock() - defer p.mtx.Unlock() - - if p.conn == nil { - return nil - } - - var err error - if p.isReusable { - err = p.pool.Add(p.conn) - } else { - err = p.pool.Remove(p.conn) - } - p.conn = nil - return err -} diff --git a/doc.go b/doc.go index ea9ac6c..437f421 100644 --- a/doc.go +++ b/doc.go @@ -1,133 +1,4 @@ /* -Package github.com/vmihailenco/redis implements a Redis client. - -Let's start with connecting to Redis using TCP: - - password := "" // no password set - db := int64(-1) // use default DB - client := redis.NewTCPClient("localhost:6379", password, db) - defer client.Close() - - ping := client.Ping() - fmt.Println(ping.Err(), ping.Val()) - // Output: PONG - -or using Unix socket: - - client := redis.NewUnixClient("/tmp/redis.sock", "", -1) - defer client.Close() - - ping := client.Ping() - fmt.Println(ping.Err(), ping.Val()) - // Output: PONG - -Then we can start sending commands: - - set := client.Set("foo", "bar") - fmt.Println(set.Err(), set.Val()) - - get := client.Get("foo") - fmt.Println(get.Err(), get.Val()) - - // Output: OK - // bar - -We can also pipeline two commands together: - - var set *redis.StatusReq - var get *redis.StringReq - reqs, err := client.Pipelined(func(c *redis.PipelineClient) { - set = c.Set("key1", "hello1") - get = c.Get("key2") - }) - fmt.Println(err, reqs) - fmt.Println(set) - fmt.Println(get) - // Output: [SET key1 hello1: OK GET key2: (nil)] - // SET key1 hello1: OK - // GET key2: (nil) - -or: - - var set *redis.StatusReq - var get *redis.StringReq - reqs, err := client.Pipelined(func(c *redis.PipelineClient) { - set = c.Set("key1", "hello1") - get = c.Get("key2") - }) - fmt.Println(err, reqs) - fmt.Println(set) - fmt.Println(get) - // Output: [SET key1 hello1 GET key2] - // SET key1 hello1 - // GET key2 - -We can also send several commands in transaction: - - func transaction(multi *redis.MultiClient) ([]redis.Req, error) { - get := multi.Get("key") - if err := get.Err(); err != nil && err != redis.Nil { - return nil, err - } - - val, _ := strconv.ParseInt(get.Val(), 10, 64) - - reqs, err := multi.Exec(func() { - multi.Set("key", strconv.FormatInt(val+1, 10)) - }) - // Transaction failed. Repeat. - if err == redis.Nil { - return transaction(multi) - } - return reqs, err - } - - multi, err := client.MultiClient() - _ = err - defer multi.Close() - - watch := multi.Watch("key") - _ = watch.Err() - - reqs, err := transaction(multi) - fmt.Println(err, reqs) - - // Output: [SET key 1: OK] - -To subscribe to the channel: - - pubsub, err := client.PubSubClient() - defer pubsub.Close() - - ch, err := pubsub.Subscribe("mychannel") - _ = err - - subscribeMsg := <-ch - fmt.Println(subscribeMsg.Err, subscribeMsg.Name) - - pub := client.Publish("mychannel", "hello") - _ = pub.Err() - - msg := <-ch - fmt.Println(msg.Err, msg.Message) - - // Output: subscribe - // hello - -You can also write custom commands: - - func Get(client *redis.Client, key string) *redis.StringReq { - req := redis.NewStringReq("GET", key) - client.Process(req) - return req - } - - get := Get(client, "key_does_not_exist") - fmt.Println(get.Err(), get.Val()) - // Output: (nil) - -Client uses connection pool to send commands. You can change maximum number of connections with: - - client.ConnPool.(*redis.MultiConnPool).MaxCap = 1 +Package gopkg.in/redis.v1 implements a Redis client. */ package redis diff --git a/example_test.go b/example_test.go index 2661667..ca0c0b1 100644 --- a/example_test.go +++ b/example_test.go @@ -4,132 +4,155 @@ import ( "fmt" "strconv" - "github.com/vmihailenco/redis" + "gopkg.in/redis.v1" ) -func ExampleTCPClient() { - password := "" // no password set - db := int64(-1) // use default DB - client := redis.NewTCPClient("localhost:6379", password, db) - defer client.Close() +var client *redis.Client - ping := client.Ping() - fmt.Println(ping.Err(), ping.Val()) - // Output: PONG +func init() { + client = redis.NewTCPClient(&redis.Options{ + Addr: ":6379", + }) } -func ExampleUnixClient() { - client := redis.NewUnixClient("/tmp/redis.sock", "", -1) +func ExampleNewTCPClient() { + client := redis.NewTCPClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password set + DB: 0, // use default DB + }) defer client.Close() - ping := client.Ping() - fmt.Println(ping.Err(), ping.Val()) - // Output: PONG + pong, err := client.Ping().Result() + fmt.Println(pong, err) + // Output: PONG } -func ExampleSetGet() { - client := redis.NewTCPClient(":6379", "", -1) - defer client.Close() - +func ExampleClient() { set := client.Set("foo", "bar") - fmt.Println(set.Err(), set.Val()) + fmt.Println(set.Err()) - get := client.Get("foo") - fmt.Println(get.Err(), get.Val()) + v, err := client.Get("hello").Result() + fmt.Printf("%q %s %v", v, err, err == redis.Nil) - // Output: OK - // bar + // Output: + // "" redis: nil true +} + +func ExampleClient_Pipelined() { + cmds, err := client.Pipelined(func(c *redis.Pipeline) { + c.Set("key1", "hello1") + c.Get("key1") + }) + fmt.Println(err) + set := cmds[0].(*redis.StatusCmd) + fmt.Println(set) + get := cmds[1].(*redis.StringCmd) + fmt.Println(get) + // Output: + // SET key1 hello1: OK + // GET key1: hello1 } func ExamplePipeline() { - client := redis.NewTCPClient(":6379", "", -1) - defer client.Close() - - var set *redis.StatusReq - var get *redis.StringReq - reqs, err := client.Pipelined(func(c *redis.PipelineClient) { - set = c.Set("key1", "hello1") - get = c.Get("key2") - }) - fmt.Println(err, reqs) + pipeline := client.Pipeline() + set := pipeline.Set("key1", "hello1") + get := pipeline.Get("key1") + cmds, err := pipeline.Exec() + fmt.Println(cmds, err) fmt.Println(set) fmt.Println(get) - // Output: [SET key1 hello1: OK GET key2: (nil)] + // Output: [SET key1 hello1: OK GET key1: hello1] // SET key1 hello1: OK - // GET key2: (nil) + // GET key1: hello1 } -func transaction(multi *redis.MultiClient) ([]redis.Req, error) { - get := multi.Get("key") - if err := get.Err(); err != nil && err != redis.Nil { - return nil, err +func ExampleMulti() { + incr := func(tx *redis.Multi) ([]redis.Cmder, error) { + s, err := tx.Get("key").Result() + if err != nil && err != redis.Nil { + return nil, err + } + n, _ := strconv.ParseInt(s, 10, 64) + + return tx.Exec(func() { + tx.Set("key", strconv.FormatInt(n+1, 10)) + }) } - val, _ := strconv.ParseInt(get.Val(), 10, 64) - - reqs, err := multi.Exec(func() { - multi.Set("key", strconv.FormatInt(val+1, 10)) - }) - // Transaction failed. Repeat. - if err == redis.Nil { - return transaction(multi) - } - return reqs, err -} - -func ExampleTransaction() { - client := redis.NewTCPClient(":6379", "", -1) - defer client.Close() - client.Del("key") - multi, err := client.MultiClient() - _ = err - defer multi.Close() + tx := client.Multi() + defer tx.Close() - watch := multi.Watch("key") + watch := tx.Watch("key") _ = watch.Err() - reqs, err := transaction(multi) - fmt.Println(err, reqs) + for { + cmds, err := incr(tx) + if err == redis.TxFailedErr { + continue + } else if err != nil { + panic(err) + } + fmt.Println(cmds, err) + break + } - // Output: [SET key 1: OK] + // Output: [SET key 1: OK] } func ExamplePubSub() { - client := redis.NewTCPClient(":6379", "", -1) - defer client.Close() - - pubsub, err := client.PubSubClient() + pubsub := client.PubSub() defer pubsub.Close() - ch, err := pubsub.Subscribe("mychannel") + err := pubsub.Subscribe("mychannel") _ = err - subscribeMsg := <-ch - fmt.Println(subscribeMsg.Err, subscribeMsg.Name) + msg, err := pubsub.Receive() + fmt.Println(msg, err) pub := client.Publish("mychannel", "hello") _ = pub.Err() - msg := <-ch - fmt.Println(msg.Err, msg.Message) + msg, err = pubsub.Receive() + fmt.Println(msg, err) - // Output: subscribe - // hello + // Output: &{subscribe mychannel 1} + // &{mychannel hello} } -func Get(client *redis.Client, key string) *redis.StringReq { - req := redis.NewStringReq("GET", key) - client.Process(req) - return req +func ExampleScript() { + setnx := redis.NewScript(` + if redis.call("get", KEYS[1]) == false then + redis.call("set", KEYS[1], ARGV[1]) + return 1 + end + return 0 + `) + + v1, err := setnx.Run(client, []string{"keynx"}, []string{"foo"}).Result() + fmt.Println(v1.(int64), err) + + v2, err := setnx.Run(client, []string{"keynx"}, []string{"bar"}).Result() + fmt.Println(v2.(int64), err) + + get := client.Get("keynx") + fmt.Println(get) + + // Output: 1 + // 0 + // GET keynx: foo } -func ExampleCustomCommand() { - client := redis.NewTCPClient(":6379", "", -1) - defer client.Close() +func Example_customCommand() { + Get := func(client *redis.Client, key string) *redis.StringCmd { + cmd := redis.NewStringCmd("GET", key) + client.Process(cmd) + return cmd + } - get := Get(client, "key_does_not_exist") - fmt.Println(get.Err(), get.Val()) - // Output: (nil) + v, err := Get(client, "key_does_not_exist").Result() + fmt.Printf("%q %s", v, err) + // Output: "" redis: nil } diff --git a/v2/export_test.go b/export_test.go similarity index 100% rename from v2/export_test.go rename to export_test.go diff --git a/multi.go b/multi.go index 061a1ec..0360a76 100644 --- a/multi.go +++ b/multi.go @@ -1,132 +1,134 @@ package redis import ( + "errors" "fmt" - "sync" ) -type MultiClient struct { +var errDiscard = errors.New("redis: Discard can be used only inside Exec") + +// Not thread-safe. +type Multi struct { *Client - execMtx sync.Mutex } -func (c *Client) MultiClient() (*MultiClient, error) { - return &MultiClient{ +func (c *Client) Multi() *Multi { + return &Multi{ Client: &Client{ - BaseClient: &BaseClient{ - ConnPool: NewSingleConnPool(c.ConnPool, true), - InitConn: c.InitConn, + baseClient: &baseClient{ + opt: c.opt, + connPool: newSingleConnPool(c.connPool, nil, true), }, }, - }, nil + } } -func (c *MultiClient) Close() error { +func (c *Multi) Close() error { c.Unwatch() return c.Client.Close() } -func (c *MultiClient) Watch(keys ...string) *StatusReq { +func (c *Multi) Watch(keys ...string) *StatusCmd { args := append([]string{"WATCH"}, keys...) - req := NewStatusReq(args...) - c.Process(req) - return req + cmd := NewStatusCmd(args...) + c.Process(cmd) + return cmd } -func (c *MultiClient) Unwatch(keys ...string) *StatusReq { +func (c *Multi) Unwatch(keys ...string) *StatusCmd { args := append([]string{"UNWATCH"}, keys...) - req := NewStatusReq(args...) - c.Process(req) - return req + cmd := NewStatusCmd(args...) + c.Process(cmd) + return cmd } -func (c *MultiClient) Discard() { - c.reqsMtx.Lock() - if c.reqs == nil { - panic("Discard can be used only inside Exec") +func (c *Multi) Discard() error { + if c.cmds == nil { + return errDiscard } - c.reqs = c.reqs[:1] - c.reqsMtx.Unlock() + c.cmds = c.cmds[:1] + return nil } -func (c *MultiClient) Exec(do func()) ([]Req, error) { - c.reqsMtx.Lock() - c.reqs = []Req{NewStatusReq("MULTI")} - c.reqsMtx.Unlock() +// Exec always returns list of commands. If transaction fails +// TxFailedErr is returned. Otherwise Exec returns error of the first +// failed command or nil. +func (c *Multi) Exec(f func()) ([]Cmder, error) { + c.cmds = []Cmder{NewStatusCmd("MULTI")} + f() + c.cmds = append(c.cmds, NewSliceCmd("EXEC")) - do() + cmds := c.cmds + c.cmds = nil - c.Queue(NewIfaceSliceReq("EXEC")) - - c.reqsMtx.Lock() - reqs := c.reqs - c.reqs = nil - c.reqsMtx.Unlock() - - if len(reqs) == 2 { - return []Req{}, nil + if len(cmds) == 2 { + return []Cmder{}, nil } - conn, err := c.conn() + cn, err := c.conn() if err != nil { - return nil, err + setCmdsErr(cmds[1:len(cmds)-1], err) + return cmds[1 : len(cmds)-1], err } - // Synchronize writes and reads to the connection using mutex. - c.execMtx.Lock() - err = c.ExecReqs(reqs, conn) - c.execMtx.Unlock() + err = c.execCmds(cn, cmds) if err != nil { - c.ConnPool.Remove(conn) - return nil, err + c.freeConn(cn, err) + return cmds[1 : len(cmds)-1], err } - c.ConnPool.Add(conn) - return reqs[1 : len(reqs)-1], nil + c.putConn(cn) + return cmds[1 : len(cmds)-1], nil } -func (c *MultiClient) ExecReqs(reqs []Req, conn *Conn) error { - err := c.WriteReq(conn, reqs...) +func (c *Multi) execCmds(cn *conn, cmds []Cmder) error { + err := c.writeCmd(cn, cmds...) if err != nil { + setCmdsErr(cmds[1:len(cmds)-1], err) return err } - statusReq := NewStatusReq() + statusCmd := NewStatusCmd() - // Omit last request (EXEC). - reqsLen := len(reqs) - 1 + // Omit last command (EXEC). + cmdsLen := len(cmds) - 1 // Parse queued replies. - for i := 0; i < reqsLen; i++ { - _, err = statusReq.ParseReply(conn.Rd) - if err != nil { + for i := 0; i < cmdsLen; i++ { + if err := statusCmd.parseReply(cn.rd); err != nil { + setCmdsErr(cmds[1:len(cmds)-1], err) return err } } // Parse number of replies. - line, err := readLine(conn.Rd) + line, err := readLine(cn.rd) if err != nil { + setCmdsErr(cmds[1:len(cmds)-1], err) return err } if line[0] != '*' { - return fmt.Errorf("Expected '*', but got line %q", line) + err := fmt.Errorf("redis: expected '*', but got line %q", line) + setCmdsErr(cmds[1:len(cmds)-1], err) + return err } if len(line) == 3 && line[1] == '-' && line[2] == '1' { - return Nil + setCmdsErr(cmds[1:len(cmds)-1], TxFailedErr) + return TxFailedErr } + var firstCmdErr error + // Parse replies. - // Loop starts from 1 to omit first request (MULTI). - for i := 1; i < reqsLen; i++ { - req := reqs[i] - val, err := req.ParseReply(conn.Rd) - if err != nil { - req.SetErr(err) - } else { - req.SetVal(val) + // Loop starts from 1 to omit MULTI cmd. + for i := 1; i < cmdsLen; i++ { + cmd := cmds[i] + if err := cmd.parseReply(cn.rd); err != nil { + if firstCmdErr == nil { + firstCmdErr = err + } } } - return nil + return firstCmdErr } diff --git a/parser.go b/parser.go index b224682..729946d 100644 --- a/parser.go +++ b/parser.go @@ -8,38 +8,22 @@ import ( "github.com/vmihailenco/bufio" ) -type replyType int +type multiBulkParser func(rd reader, n int64) (interface{}, error) -const ( - ifaceSlice replyType = iota - stringSlice - boolSlice - stringStringMap - stringFloatMap -) +// Redis nil reply. +var Nil = errors.New("redis: nil") -// Represents Redis nil reply. -var Nil = errors.New("(nil)") +// Redis transaction failed. +var TxFailedErr = errors.New("redis: transaction failed") var ( - errReaderTooSmall = errors.New("redis: reader is too small") - errValNotSet = errors.New("redis: value is not set") - errInvalidType = errors.New("redis: invalid reply type") + errReaderTooSmall = errors.New("redis: reader is too small") + errInvalidReplyType = errors.New("redis: invalid reply type") ) //------------------------------------------------------------------------------ -type parserError struct { - err error -} - -func (e *parserError) Error() string { - return e.err.Error() -} - -//------------------------------------------------------------------------------ - -func appendReq(buf []byte, args []string) []byte { +func appendCmd(buf []byte, args []string) []byte { buf = append(buf, '*') buf = strconv.AppendUint(buf, uint64(len(args)), 10) buf = append(buf, '\r', '\n') @@ -60,6 +44,7 @@ type reader interface { Read([]byte) (int, error) ReadN(n int) ([]byte, error) Buffered() int + Peek(int) ([]byte, error) } func readLine(rd reader) ([]byte, error) { @@ -99,7 +84,7 @@ func readN(rd reader, n int) ([]byte, error) { //------------------------------------------------------------------------------ -func ParseReq(rd reader) ([]string, error) { +func parseReq(rd reader) ([]string, error) { line, err := readLine(rd) if err != nil { return nil, err @@ -139,30 +124,10 @@ func ParseReq(rd reader) ([]string, error) { //------------------------------------------------------------------------------ -func parseReply(rd reader) (interface{}, error) { - return _parseReply(rd, ifaceSlice) -} - -func parseStringSliceReply(rd reader) (interface{}, error) { - return _parseReply(rd, stringSlice) -} - -func parseBoolSliceReply(rd reader) (interface{}, error) { - return _parseReply(rd, boolSlice) -} - -func parseStringStringMapReply(rd reader) (interface{}, error) { - return _parseReply(rd, stringStringMap) -} - -func parseStringFloatMapReply(rd reader) (interface{}, error) { - return _parseReply(rd, stringFloatMap) -} - -func _parseReply(rd reader, typ replyType) (interface{}, error) { +func parseReply(rd reader, p multiBulkParser) (interface{}, error) { line, err := readLine(rd) if err != nil { - return 0, &parserError{err} + return nil, err } switch line[0] { @@ -173,23 +138,23 @@ func _parseReply(rd reader, typ replyType) (interface{}, error) { case ':': v, err := strconv.ParseInt(string(line[1:]), 10, 64) if err != nil { - return 0, &parserError{err} + return nil, err } return v, nil case '$': if len(line) == 3 && line[1] == '-' && line[2] == '1' { - return "", Nil + return nil, Nil } replyLenInt32, err := strconv.ParseInt(string(line[1:]), 10, 32) if err != nil { - return "", &parserError{err} + return nil, err } replyLen := int(replyLenInt32) + 2 line, err = readN(rd, replyLen) if err != nil { - return "", &parserError{err} + return nil, err } return string(line[:len(line)-2]), nil case '*': @@ -199,106 +164,113 @@ func _parseReply(rd reader, typ replyType) (interface{}, error) { repliesNum, err := strconv.ParseInt(string(line[1:]), 10, 64) if err != nil { - return nil, &parserError{err} + return nil, err } - switch typ { - case stringSlice: - vals := make([]string, 0, repliesNum) - for i := int64(0); i < repliesNum; i++ { - vi, err := parseReply(rd) - if err != nil { - return nil, err - } - if v, ok := vi.(string); ok { - vals = append(vals, v) - } else { - return nil, errInvalidType - } - } - return vals, nil - case boolSlice: - vals := make([]bool, 0, repliesNum) - for i := int64(0); i < repliesNum; i++ { - vi, err := parseReply(rd) - if err != nil { - return nil, err - } - if v, ok := vi.(int64); ok { - vals = append(vals, v == 1) - } else { - return nil, errInvalidType - } - } - return vals, nil - case stringStringMap: // TODO: Consider handling Nil values. - m := make(map[string]string, repliesNum/2) - for i := int64(0); i < repliesNum; i += 2 { - keyI, err := parseReply(rd) - if err != nil { - return nil, err - } - key, ok := keyI.(string) - if !ok { - return nil, errInvalidType - } - - valueI, err := parseReply(rd) - if err != nil { - return nil, err - } - value, ok := valueI.(string) - if !ok { - return nil, errInvalidType - } - - m[key] = value - } - return m, nil - case stringFloatMap: // TODO: Consider handling Nil values. - m := make(map[string]float64, repliesNum/2) - for i := int64(0); i < repliesNum; i += 2 { - keyI, err := parseReply(rd) - if err != nil { - return nil, err - } - key, ok := keyI.(string) - if !ok { - return nil, errInvalidType - } - - valueI, err := parseReply(rd) - if err != nil { - return nil, err - } - valueS, ok := valueI.(string) - if !ok { - return nil, errInvalidType - } - value, err := strconv.ParseFloat(valueS, 64) - if err != nil { - return nil, &parserError{err} - } - - m[key] = value - } - return m, nil - default: - vals := make([]interface{}, 0, repliesNum) - for i := int64(0); i < repliesNum; i++ { - v, err := parseReply(rd) - if err == Nil { - vals = append(vals, nil) - } else if err != nil { - return nil, err - } else { - vals = append(vals, v) - } - } - return vals, nil - } - default: - return nil, &parserError{fmt.Errorf("redis: can't parse %q", line)} + return p(rd, repliesNum) } - panic("not reachable") + return nil, fmt.Errorf("redis: can't parse %q", line) +} + +func parseSlice(rd reader, n int64) (interface{}, error) { + vals := make([]interface{}, 0, n) + for i := int64(0); i < n; i++ { + v, err := parseReply(rd, parseSlice) + if err == Nil { + vals = append(vals, nil) + } else if err != nil { + return nil, err + } else { + vals = append(vals, v) + } + } + return vals, nil +} + +func parseStringSlice(rd reader, n int64) (interface{}, error) { + vals := make([]string, 0, n) + for i := int64(0); i < n; i++ { + vi, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + if v, ok := vi.(string); ok { + vals = append(vals, v) + } else { + return nil, errInvalidReplyType + } + } + return vals, nil +} + +func parseBoolSlice(rd reader, n int64) (interface{}, error) { + vals := make([]bool, 0, n) + for i := int64(0); i < n; i++ { + vi, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + if v, ok := vi.(int64); ok { + vals = append(vals, v == 1) + } else { + return nil, errInvalidReplyType + } + } + return vals, nil +} + +func parseStringStringMap(rd reader, n int64) (interface{}, error) { + m := make(map[string]string, n/2) + for i := int64(0); i < n; i += 2 { + keyI, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + key, ok := keyI.(string) + if !ok { + return nil, errInvalidReplyType + } + + valueI, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + value, ok := valueI.(string) + if !ok { + return nil, errInvalidReplyType + } + + m[key] = value + } + return m, nil +} + +func parseStringFloatMap(rd reader, n int64) (interface{}, error) { + m := make(map[string]float64, n/2) + for i := int64(0); i < n; i += 2 { + keyI, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + key, ok := keyI.(string) + if !ok { + return nil, errInvalidReplyType + } + + valueI, err := parseReply(rd, nil) + if err != nil { + return nil, err + } + valueS, ok := valueI.(string) + if !ok { + return nil, errInvalidReplyType + } + value, err := strconv.ParseFloat(valueS, 64) + if err != nil { + return nil, err + } + + m[key] = value + } + return m, nil } diff --git a/parser_test.go b/parser_test.go deleted file mode 100644 index 17eefcd..0000000 --- a/parser_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package redis_test - -import ( - "bytes" - - "github.com/vmihailenco/bufio" - . "launchpad.net/gocheck" - - "github.com/vmihailenco/redis" -) - -type ParserTest struct{} - -var _ = Suite(&ParserTest{}) - -func (t *ParserTest) TestParseReq(c *C) { - buf := bytes.NewBufferString("*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nhello\r\n") - rd := bufio.NewReaderSize(buf, 1024) - - args, err := redis.ParseReq(rd) - c.Check(err, IsNil) - c.Check(args, DeepEquals, []string{"SET", "key", "hello"}) -} diff --git a/pipeline.go b/pipeline.go index de0017b..6d436d2 100644 --- a/pipeline.go +++ b/pipeline.go @@ -1,84 +1,90 @@ package redis -type PipelineClient struct { +// Not thread-safe. +type Pipeline struct { *Client + + closed bool } -func (c *Client) PipelineClient() (*PipelineClient, error) { - return &PipelineClient{ +func (c *Client) Pipeline() *Pipeline { + return &Pipeline{ Client: &Client{ - BaseClient: &BaseClient{ - ConnPool: c.ConnPool, - InitConn: c.InitConn, - reqs: make([]Req, 0), + baseClient: &baseClient{ + opt: c.opt, + connPool: c.connPool, + + cmds: make([]Cmder, 0), }, }, - }, nil -} - -func (c *Client) Pipelined(do func(*PipelineClient)) ([]Req, error) { - pc, err := c.PipelineClient() - if err != nil { - return nil, err } - defer pc.Close() - - do(pc) - - return pc.RunQueued() } -func (c *PipelineClient) Close() error { +func (c *Client) Pipelined(f func(*Pipeline)) ([]Cmder, error) { + pc := c.Pipeline() + f(pc) + cmds, err := pc.Exec() + pc.Close() + return cmds, err +} + +func (c *Pipeline) Close() error { + c.closed = true return nil } -func (c *PipelineClient) DiscardQueued() { - c.reqsMtx.Lock() - c.reqs = c.reqs[:0] - c.reqsMtx.Unlock() +func (c *Pipeline) Discard() error { + if c.closed { + return errClosed + } + c.cmds = c.cmds[:0] + return nil } -func (c *PipelineClient) RunQueued() ([]Req, error) { - c.reqsMtx.Lock() - reqs := c.reqs - c.reqs = make([]Req, 0) - c.reqsMtx.Unlock() - - if len(reqs) == 0 { - return []Req{}, nil +// Exec always returns list of commands and error of the first failed +// command if any. +func (c *Pipeline) Exec() ([]Cmder, error) { + if c.closed { + return nil, errClosed } - conn, err := c.conn() + cmds := c.cmds + c.cmds = make([]Cmder, 0) + + if len(cmds) == 0 { + return []Cmder{}, nil + } + + cn, err := c.conn() if err != nil { - return nil, err + setCmdsErr(cmds, err) + return cmds, err } - err = c.RunReqs(reqs, conn) - if err != nil { - c.ConnPool.Remove(conn) - return nil, err + if err := c.execCmds(cn, cmds); err != nil { + c.freeConn(cn, err) + return cmds, err } - c.ConnPool.Add(conn) - return reqs, nil + c.putConn(cn) + return cmds, nil } -func (c *PipelineClient) RunReqs(reqs []Req, conn *Conn) error { - err := c.WriteReq(conn, reqs...) +func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error { + err := c.writeCmd(cn, cmds...) if err != nil { + setCmdsErr(cmds, err) return err } - reqsLen := len(reqs) - for i := 0; i < reqsLen; i++ { - req := reqs[i] - val, err := req.ParseReply(conn.Rd) - if err != nil { - req.SetErr(err) - } else { - req.SetVal(val) + var firstCmdErr error + for _, cmd := range cmds { + if err := cmd.parseReply(cn.rd); err != nil { + if firstCmdErr == nil { + firstCmdErr = err + } } } - return nil + return firstCmdErr } diff --git a/v2/pool.go b/pool.go similarity index 100% rename from v2/pool.go rename to pool.go diff --git a/pubsub.go b/pubsub.go index d30b296..cc8d7e0 100644 --- a/pubsub.go +++ b/pubsub.go @@ -2,123 +2,121 @@ package redis import ( "fmt" - "sync" + "time" ) -type PubSubClient struct { - *BaseClient - ch chan *Message - once sync.Once +// Not thread-safe. +type PubSub struct { + *baseClient } -func (c *Client) PubSubClient() (*PubSubClient, error) { - return &PubSubClient{ - BaseClient: &BaseClient{ - ConnPool: NewSingleConnPool(c.ConnPool, false), - InitConn: c.InitConn, +func (c *Client) PubSub() *PubSub { + return &PubSub{ + baseClient: &baseClient{ + opt: c.opt, + connPool: newSingleConnPool(c.connPool, nil, false), }, - ch: make(chan *Message), - }, nil + } } -func (c *Client) Publish(channel, message string) *IntReq { - req := NewIntReq("PUBLISH", channel, message) +func (c *Client) Publish(channel, message string) *IntCmd { + req := NewIntCmd("PUBLISH", channel, message) c.Process(req) return req } type Message struct { - Name, Channel, ChannelPattern, Message string - Number int64 - - Err error + Channel string + Payload string } -func (c *PubSubClient) consumeMessages(conn *Conn) { - req := NewIfaceSliceReq() - - for { - msg := &Message{} - - replyIface, err := req.ParseReply(conn.Rd) - if err != nil { - msg.Err = err - c.ch <- msg - return - } - reply, ok := replyIface.([]interface{}) - if !ok { - msg.Err = fmt.Errorf("redis: unexpected reply type %T", replyIface) - c.ch <- msg - return - } - - msgName := reply[0].(string) - switch msgName { - case "subscribe", "unsubscribe", "psubscribe", "punsubscribe": - msg.Name = msgName - msg.Channel = reply[1].(string) - msg.Number = reply[2].(int64) - case "message": - msg.Name = msgName - msg.Channel = reply[1].(string) - msg.Message = reply[2].(string) - case "pmessage": - msg.Name = msgName - msg.ChannelPattern = reply[1].(string) - msg.Channel = reply[2].(string) - msg.Message = reply[3].(string) - default: - msg.Err = fmt.Errorf("Unsupported message name: %q.", msgName) - } - c.ch <- msg - } +type PMessage struct { + Channel string + Pattern string + Payload string } -func (c *PubSubClient) subscribe(cmd string, channels ...string) (chan *Message, error) { - args := append([]string{cmd}, channels...) - req := NewIfaceSliceReq(args...) +type Subscription struct { + Kind string + Channel string + Count int +} - conn, err := c.conn() +func (c *PubSub) Receive() (interface{}, error) { + return c.ReceiveTimeout(0) +} + +func (c *PubSub) ReceiveTimeout(timeout time.Duration) (interface{}, error) { + cn, err := c.conn() if err != nil { return nil, err } + cn.readTimeout = timeout - if err := c.WriteReq(conn, req); err != nil { + cmd := NewSliceCmd() + if err := cmd.parseReply(cn.rd); err != nil { return nil, err } - c.once.Do(func() { - go c.consumeMessages(conn) - }) + reply := cmd.Val() - return c.ch, nil + msgName := reply[0].(string) + switch msgName { + case "subscribe", "unsubscribe", "psubscribe", "punsubscribe": + return &Subscription{ + Kind: msgName, + Channel: reply[1].(string), + Count: int(reply[2].(int64)), + }, nil + case "message": + return &Message{ + Channel: reply[1].(string), + Payload: reply[2].(string), + }, nil + case "pmessage": + return &PMessage{ + Pattern: reply[1].(string), + Channel: reply[2].(string), + Payload: reply[3].(string), + }, nil + } + return nil, fmt.Errorf("redis: unsupported message name: %q", msgName) } -func (c *PubSubClient) Subscribe(channels ...string) (chan *Message, error) { - return c.subscribe("SUBSCRIBE", channels...) -} - -func (c *PubSubClient) PSubscribe(patterns ...string) (chan *Message, error) { - return c.subscribe("PSUBSCRIBE", patterns...) -} - -func (c *PubSubClient) unsubscribe(cmd string, channels ...string) error { - args := append([]string{cmd}, channels...) - req := NewIfaceSliceReq(args...) - - conn, err := c.conn() +func (c *PubSub) subscribe(cmd string, channels ...string) error { + cn, err := c.conn() if err != nil { return err } - return c.WriteReq(conn, req) + args := append([]string{cmd}, channels...) + req := NewSliceCmd(args...) + return c.writeCmd(cn, req) } -func (c *PubSubClient) Unsubscribe(channels ...string) error { +func (c *PubSub) Subscribe(channels ...string) error { + return c.subscribe("SUBSCRIBE", channels...) +} + +func (c *PubSub) PSubscribe(patterns ...string) error { + return c.subscribe("PSUBSCRIBE", patterns...) +} + +func (c *PubSub) unsubscribe(cmd string, channels ...string) error { + cn, err := c.conn() + if err != nil { + return err + } + + args := append([]string{cmd}, channels...) + req := NewSliceCmd(args...) + return c.writeCmd(cn, req) +} + +func (c *PubSub) Unsubscribe(channels ...string) error { return c.unsubscribe("UNSUBSCRIBE", channels...) } -func (c *PubSubClient) PUnsubscribe(patterns ...string) error { +func (c *PubSub) PUnsubscribe(patterns ...string) error { return c.unsubscribe("PUNSUBSCRIBE", patterns...) } diff --git a/redis.go b/redis.go index c8fe071..6e945da 100644 --- a/redis.go +++ b/redis.go @@ -1,192 +1,191 @@ package redis import ( - "crypto/tls" - "log" "net" - "os" - "sync" "time" + + "github.com/golang/glog" ) -// Package logger. -var Logger = log.New(os.Stdout, "redis: ", log.Ldate|log.Ltime) +type baseClient struct { + connPool pool -type OpenConnFunc func() (net.Conn, error) -type CloseConnFunc func(net.Conn) error -type InitConnFunc func(*Client) error + opt *Options -func TCPConnector(addr string) OpenConnFunc { - return func() (net.Conn, error) { - return net.DialTimeout("tcp", addr, 3*time.Second) - } + cmds []Cmder } -func TLSConnector(addr string, tlsConfig *tls.Config) OpenConnFunc { - return func() (net.Conn, error) { - conn, err := net.DialTimeout("tcp", addr, 3*time.Second) - if err != nil { - return nil, err - } - return tls.Client(conn, tlsConfig), nil - } -} - -func UnixConnector(addr string) OpenConnFunc { - return func() (net.Conn, error) { - return net.DialTimeout("unix", addr, 3*time.Second) - } -} - -func AuthSelectFunc(password string, db int64) InitConnFunc { - if password == "" && db < 0 { - return nil - } - - return func(client *Client) error { - if password != "" { - auth := client.Auth(password) - if auth.Err() != nil { - return auth.Err() - } - } - - if db >= 0 { - sel := client.Select(db) - if sel.Err() != nil { - return sel.Err() - } - } - - return nil - } -} - -//------------------------------------------------------------------------------ - -type BaseClient struct { - ConnPool ConnPool - InitConn InitConnFunc - reqs []Req - reqsMtx sync.Mutex -} - -func (c *BaseClient) WriteReq(conn *Conn, reqs ...Req) error { +func (c *baseClient) writeCmd(cn *conn, cmds ...Cmder) error { buf := make([]byte, 0, 1000) - for _, req := range reqs { - buf = appendReq(buf, req.Args()) + for _, cmd := range cmds { + buf = appendCmd(buf, cmd.args()) } - _, err := conn.RW.Write(buf) + _, err := cn.Write(buf) return err } -func (c *BaseClient) conn() (*Conn, error) { - conn, isNew, err := c.ConnPool.Get() +func (c *baseClient) conn() (*conn, error) { + cn, isNew, err := c.connPool.Get() if err != nil { return nil, err } - if isNew && c.InitConn != nil { - client := &Client{ - BaseClient: &BaseClient{ - ConnPool: NewSingleConnPoolConn(c.ConnPool, conn, true), - }, - } - err = c.InitConn(client) - if err != nil { - if err := c.ConnPool.Remove(conn); err != nil { - Logger.Printf("ConnPool.Remove error: %v", err) - } + if isNew && (c.opt.Password != "" || c.opt.DB > 0) { + if err = c.init(cn, c.opt.Password, c.opt.DB); err != nil { + c.removeConn(cn) return nil, err } } - return conn, nil + + return cn, nil } -func (c *BaseClient) Process(req Req) { - if c.reqs == nil { - c.Run(req) +func (c *baseClient) init(cn *conn, password string, db int64) error { + // Client is not closed on purpose. + client := &Client{ + baseClient: &baseClient{ + opt: c.opt, + connPool: newSingleConnPool(c.connPool, cn, false), + }, + } + + if password != "" { + auth := client.Auth(password) + if auth.Err() != nil { + return auth.Err() + } + } + + if db > 0 { + sel := client.Select(db) + if sel.Err() != nil { + return sel.Err() + } + } + + return nil +} + +func (c *baseClient) freeConn(cn *conn, err error) { + if err == Nil || err == TxFailedErr { + c.putConn(cn) } else { - c.Queue(req) + c.removeConn(cn) } } -func (c *BaseClient) Run(req Req) { - conn, err := c.conn() - if err != nil { - req.SetErr(err) - return +func (c *baseClient) removeConn(cn *conn) { + if err := c.connPool.Remove(cn); err != nil { + glog.Errorf("pool.Remove failed: %s", err) } - - err = c.WriteReq(conn, req) - if err != nil { - if err := c.ConnPool.Remove(conn); err != nil { - Logger.Printf("ConnPool.Remove error: %v", err) - } - req.SetErr(err) - return - } - - val, err := req.ParseReply(conn.Rd) - if err != nil { - if _, ok := err.(*parserError); ok { - if err := c.ConnPool.Remove(conn); err != nil { - Logger.Printf("ConnPool.Remove error: %v", err) - } - } else { - if err := c.ConnPool.Add(conn); err != nil { - Logger.Printf("ConnPool.Add error: %v", err) - } - } - req.SetErr(err) - return - } - - if err := c.ConnPool.Add(conn); err != nil { - Logger.Printf("ConnPool.Add error: %v", err) - } - req.SetVal(val) } -// Queues request to be executed later. -func (c *BaseClient) Queue(req Req) { - c.reqsMtx.Lock() - c.reqs = append(c.reqs, req) - c.reqsMtx.Unlock() +func (c *baseClient) putConn(cn *conn) { + if err := c.connPool.Put(cn); err != nil { + glog.Errorf("pool.Put failed: %s", err) + } } -func (c *BaseClient) Close() error { - return c.ConnPool.Close() +func (c *baseClient) Process(cmd Cmder) { + if c.cmds == nil { + c.run(cmd) + } else { + c.cmds = append(c.cmds, cmd) + } +} + +func (c *baseClient) run(cmd Cmder) { + cn, err := c.conn() + if err != nil { + cmd.setErr(err) + return + } + + cn.writeTimeout = c.opt.WriteTimeout + if timeout := cmd.writeTimeout(); timeout != nil { + cn.writeTimeout = *timeout + } + + cn.readTimeout = c.opt.ReadTimeout + if timeout := cmd.readTimeout(); timeout != nil { + cn.readTimeout = *timeout + } + + if err := c.writeCmd(cn, cmd); err != nil { + c.freeConn(cn, err) + cmd.setErr(err) + return + } + + if err := cmd.parseReply(cn.rd); err != nil { + c.freeConn(cn, err) + return + } + + c.putConn(cn) +} + +// Close closes the client, releasing any open resources. +func (c *baseClient) Close() error { + return c.connPool.Close() +} + +//------------------------------------------------------------------------------ + +type Options struct { + Addr string + Password string + DB int64 + + PoolSize int + + DialTimeout time.Duration + ReadTimeout time.Duration + WriteTimeout time.Duration + IdleTimeout time.Duration +} + +func (opt *Options) getPoolSize() int { + if opt.PoolSize == 0 { + return 10 + } + return opt.PoolSize +} + +func (opt *Options) getDialTimeout() time.Duration { + if opt.DialTimeout == 0 { + return 5 * time.Second + } + return opt.DialTimeout } //------------------------------------------------------------------------------ type Client struct { - *BaseClient + *baseClient } -func NewClient(openConn OpenConnFunc, closeConn CloseConnFunc, initConn InitConnFunc) *Client { +func newClient(opt *Options, dial func() (net.Conn, error)) *Client { return &Client{ - BaseClient: &BaseClient{ - ConnPool: NewMultiConnPool(openConn, closeConn, 10), - InitConn: initConn, + baseClient: &baseClient{ + opt: opt, + + connPool: newConnPool(newConnFunc(dial), opt.getPoolSize(), opt.IdleTimeout), }, } } -func NewTCPClient(addr string, password string, db int64) *Client { - return NewClient(TCPConnector(addr), nil, AuthSelectFunc(password, db)) +func NewTCPClient(opt *Options) *Client { + dial := func() (net.Conn, error) { + return net.DialTimeout("tcp", opt.Addr, opt.getDialTimeout()) + } + return newClient(opt, dial) } -func NewTLSClient(addr string, tlsConfig *tls.Config, password string, db int64) *Client { - return NewClient( - TLSConnector(addr, tlsConfig), - nil, - AuthSelectFunc(password, db), - ) -} - -func NewUnixClient(addr string, password string, db int64) *Client { - return NewClient(UnixConnector(addr), nil, AuthSelectFunc(password, db)) +func NewUnixClient(opt *Options) *Client { + dial := func() (net.Conn, error) { + return net.DialTimeout("unix", opt.Addr, opt.getDialTimeout()) + } + return newClient(opt, dial) } diff --git a/redis_test.go b/redis_test.go index 448c569..48386d8 100644 --- a/redis_test.go +++ b/redis_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "github.com/vmihailenco/redis" + "gopkg.in/redis.v1" . "launchpad.net/gocheck" ) @@ -27,103 +27,147 @@ func sortStrings(slice []string) []string { //------------------------------------------------------------------------------ -type RedisShutdownTest struct { - client *redis.Client -} - -var _ = Suite(&RedisShutdownTest{}) - -func (t *RedisShutdownTest) SetUpTest(c *C) { - t.client = redis.NewTCPClient(redisAddr, "", -1) -} - -func (t *RedisShutdownTest) TestShutdown(c *C) { - c.Skip("shutdowns server") - - shutdown := t.client.Shutdown() - c.Check(shutdown.Err(), Equals, io.EOF) - c.Check(shutdown.Val(), Equals, "") - - ping := t.client.Ping() - c.Check(ping.Err(), ErrorMatches, "dial tcp :[0-9]+: connection refused") - c.Check(ping.Val(), Equals, "") -} - -//------------------------------------------------------------------------------ - type RedisConnectorTest struct{} var _ = Suite(&RedisConnectorTest{}) -func (t *RedisConnectorTest) TestTCPConnector(c *C) { - client := redis.NewTCPClient(":6379", "", -1) +func (t *RedisConnectorTest) TestShutdown(c *C) { + c.Skip("shutdowns server") + + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) + + shutdown := client.Shutdown() + c.Check(shutdown.Err(), Equals, io.EOF) + c.Check(shutdown.Val(), Equals, "") + + ping := client.Ping() + c.Check(ping.Err(), ErrorMatches, "dial tcp :[0-9]+: connection refused") + c.Check(ping.Val(), Equals, "") +} + +func (t *RedisConnectorTest) TestNewTCPClient(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) ping := client.Ping() c.Check(ping.Err(), IsNil) c.Check(ping.Val(), Equals, "PONG") c.Assert(client.Close(), IsNil) } -func (t *RedisConnectorTest) TestUnixConnector(c *C) { - client := redis.NewUnixClient("/tmp/redis.sock", "", -1) +func (t *RedisConnectorTest) TestNewUnixClient(c *C) { + c.Skip("not available on Travis CI") + + client := redis.NewUnixClient(&redis.Options{ + Addr: "/tmp/redis.sock", + }) ping := client.Ping() c.Check(ping.Err(), IsNil) c.Check(ping.Val(), Equals, "PONG") c.Assert(client.Close(), IsNil) } +func (t *RedisConnectorTest) TestClose(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) + c.Assert(client.Close(), IsNil) + + ping := client.Ping() + c.Assert(ping.Err(), Not(IsNil)) + c.Assert(ping.Err().Error(), Equals, "redis: client is closed") + + c.Assert(client.Close(), IsNil) +} + +func (t *RedisConnectorTest) TestPubSubClose(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) + + pubsub := client.PubSub() + c.Assert(pubsub.Close(), IsNil) + + _, err := pubsub.Receive() + c.Assert(err, Not(IsNil)) + c.Assert(err.Error(), Equals, "redis: client is closed") + + ping := client.Ping() + c.Assert(ping.Err(), IsNil) + + c.Assert(client.Close(), IsNil) +} + +func (t *RedisConnectorTest) TestMultiClose(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) + + multi := client.Multi() + c.Assert(multi.Close(), IsNil) + + _, err := multi.Exec(func() { + multi.Ping() + }) + c.Assert(err, Not(IsNil)) + c.Assert(err.Error(), Equals, "redis: client is closed") + + ping := client.Ping() + c.Assert(ping.Err(), IsNil) + + c.Assert(client.Close(), IsNil) +} + +func (t *RedisConnectorTest) TestPipelineClose(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) + + _, err := client.Pipelined(func(pipeline *redis.Pipeline) { + c.Assert(pipeline.Close(), IsNil) + pipeline.Ping() + }) + c.Assert(err, Not(IsNil)) + c.Assert(err.Error(), Equals, "redis: client is closed") + + ping := client.Ping() + c.Assert(ping.Err(), IsNil) + + c.Assert(client.Close(), IsNil) +} + +func (t *RedisConnectorTest) TestIdleTimeout(c *C) { + client := redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + IdleTimeout: time.Nanosecond, + }) + for i := 0; i < 10; i++ { + c.Assert(client.Ping().Err(), IsNil) + } +} + //------------------------------------------------------------------------------ type RedisConnPoolTest struct { - openedConnCount, closedConnCount, initedConnCount int64 - client *redis.Client } var _ = Suite(&RedisConnPoolTest{}) -func (t *RedisConnPoolTest) SetUpSuite(c *C) { - openConn := func() (net.Conn, error) { - t.openedConnCount++ - return net.Dial("tcp", redisAddr) - } - initConn := func(c *redis.Client) error { - t.initedConnCount++ - return nil - } - closeConn := func(conn net.Conn) error { - t.closedConnCount++ - return nil - } - - t.client = redis.NewClient(openConn, closeConn, initConn) - t.client.ConnPool.(*redis.MultiConnPool).MaxCap = 10 -} - -func (t *RedisConnPoolTest) TearDownSuite(c *C) { - c.Assert(t.client.Close(), IsNil) +func (t *RedisConnPoolTest) SetUpTest(c *C) { + t.client = redis.NewTCPClient(&redis.Options{ + Addr: redisAddr, + }) } func (t *RedisConnPoolTest) TearDownTest(c *C) { - t.resetRedis(c) - t.resetClient(c) -} - -func (t *RedisConnPoolTest) resetRedis(c *C) { - // This is much faster than Flushall. - c.Assert(t.client.Select(1).Err(), IsNil) - c.Assert(t.client.FlushDb().Err(), IsNil) - c.Assert(t.client.Select(0).Err(), IsNil) c.Assert(t.client.FlushDb().Err(), IsNil) + c.Assert(t.client.Close(), IsNil) } -func (t *RedisConnPoolTest) resetClient(c *C) { - t.client.Close() - c.Check(t.closedConnCount, Equals, t.openedConnCount) - c.Check(t.initedConnCount, Equals, t.openedConnCount) - t.openedConnCount, t.closedConnCount, t.initedConnCount = 0, 0, 0 -} - -func (t *RedisConnPoolTest) TestConnPoolMaxCap(c *C) { +func (t *RedisConnPoolTest) TestConnPoolMaxSize(c *C) { wg := &sync.WaitGroup{} for i := 0; i < 1000; i++ { wg.Add(1) @@ -136,23 +180,22 @@ func (t *RedisConnPoolTest) TestConnPoolMaxCap(c *C) { } wg.Wait() - c.Assert(t.client.Close(), IsNil) - c.Assert(t.openedConnCount, Equals, int64(10)) - c.Assert(t.closedConnCount, Equals, int64(10)) + c.Assert(t.client.Pool().Size(), Equals, 10) + c.Assert(t.client.Pool().Len(), Equals, 10) } -func (t *RedisConnPoolTest) TestConnPoolMaxCapOnPipelineClient(c *C) { - wg := &sync.WaitGroup{} - for i := 0; i < 1000; i++ { - wg.Add(1) - go func() { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) +func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnPipelineClient(c *C) { + const N = 1000 + wg := &sync.WaitGroup{} + wg.Add(N) + for i := 0; i < N; i++ { + go func() { + pipeline := t.client.Pipeline() ping := pipeline.Ping() - reqs, err := pipeline.RunQueued() + cmds, err := pipeline.Exec() c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 1) + c.Assert(cmds, HasLen, 1) c.Assert(ping.Err(), IsNil) c.Assert(ping.Val(), Equals, "PONG") @@ -163,25 +206,24 @@ func (t *RedisConnPoolTest) TestConnPoolMaxCapOnPipelineClient(c *C) { } wg.Wait() - c.Assert(t.client.Close(), IsNil) - c.Assert(t.openedConnCount, Equals, int64(10)) - c.Assert(t.closedConnCount, Equals, int64(10)) + c.Assert(t.client.Pool().Size(), Equals, 10) + c.Assert(t.client.Pool().Len(), Equals, 10) } -func (t *RedisConnPoolTest) TestConnPoolMaxCapOnMultiClient(c *C) { - wg := &sync.WaitGroup{} - for i := 0; i < 1000; i++ { - wg.Add(1) - go func() { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) +func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnMultiClient(c *C) { + const N = 1000 - var ping *redis.StatusReq - reqs, err := multi.Exec(func() { + wg := &sync.WaitGroup{} + wg.Add(N) + for i := 0; i < N; i++ { + go func() { + multi := t.client.Multi() + var ping *redis.StatusCmd + cmds, err := multi.Exec(func() { ping = multi.Ping() }) c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 1) + c.Assert(cmds, HasLen, 1) c.Assert(ping.Err(), IsNil) c.Assert(ping.Val(), Equals, "PONG") @@ -192,39 +234,62 @@ func (t *RedisConnPoolTest) TestConnPoolMaxCapOnMultiClient(c *C) { } wg.Wait() - c.Assert(t.client.Close(), IsNil) - c.Assert(t.openedConnCount, Equals, int64(10)) - c.Assert(t.closedConnCount, Equals, int64(10)) + c.Assert(t.client.Pool().Size(), Equals, 10) + c.Assert(t.client.Pool().Len(), Equals, 10) } -func (t *RedisConnPoolTest) TestConnPoolMaxCapOnPubSubClient(c *C) { +func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnPubSub(c *C) { + const N = 1000 + wg := &sync.WaitGroup{} - for i := 0; i < 1000; i++ { - wg.Add(1) + wg.Add(N) + for i := 0; i < N; i++ { go func() { - pubsub, err := t.client.PubSubClient() - c.Assert(err, IsNil) - - _, err = pubsub.Subscribe() - c.Assert(err, IsNil) - + pubsub := t.client.PubSub() + c.Assert(pubsub.Subscribe(), IsNil) c.Assert(pubsub.Close(), IsNil) - wg.Done() }() } wg.Wait() - c.Assert(t.client.Close(), IsNil) - c.Assert(t.openedConnCount, Equals, int64(1000)) - c.Assert(t.closedConnCount, Equals, int64(1000)) + c.Assert(t.client.Pool().Size(), Equals, 0) + c.Assert(t.client.Pool().Len(), Equals, 0) +} + +func (t *RedisConnPoolTest) TestConnPoolRemovesBrokenConn(c *C) { + cn, _, err := t.client.Pool().Get() + c.Assert(err, IsNil) + c.Assert(cn.Close(), IsNil) + c.Assert(t.client.Pool().Put(cn), IsNil) + + ping := t.client.Ping() + c.Assert(ping.Err().Error(), Equals, "use of closed network connection") + c.Assert(ping.Val(), Equals, "") + + ping = t.client.Ping() + c.Assert(ping.Err(), IsNil) + c.Assert(ping.Val(), Equals, "PONG") + + c.Assert(t.client.Pool().Size(), Equals, 1) + c.Assert(t.client.Pool().Len(), Equals, 1) +} + +func (t *RedisConnPoolTest) TestConnPoolReusesConn(c *C) { + for i := 0; i < 1000; i++ { + ping := t.client.Ping() + c.Assert(ping.Err(), IsNil) + c.Assert(ping.Val(), Equals, "PONG") + } + + c.Assert(t.client.Pool().Size(), Equals, 1) + c.Assert(t.client.Pool().Len(), Equals, 1) } //------------------------------------------------------------------------------ type RedisTest struct { - openedConnCount, closedConnCount, initedConnCount int - client *redis.Client + client *redis.Client } var _ = Suite(&RedisTest{}) @@ -232,36 +297,16 @@ var _ = Suite(&RedisTest{}) func Test(t *testing.T) { TestingT(t) } func (t *RedisTest) SetUpSuite(c *C) { - openConn := func() (net.Conn, error) { - t.openedConnCount++ - return net.Dial("tcp", redisAddr) - } - initConn := func(c *redis.Client) error { - t.initedConnCount++ - return nil - } - closeConn := func(conn net.Conn) error { - t.closedConnCount++ - return nil - } - - t.client = redis.NewClient(openConn, closeConn, initConn) - t.client.ConnPool.(*redis.MultiConnPool).MaxCap = 10 + t.client = redis.NewTCPClient(&redis.Options{ + Addr: ":6379", + }) } func (t *RedisTest) TearDownSuite(c *C) { c.Assert(t.client.Close(), IsNil) } -func (t *RedisTest) TearDownTest(c *C) { - // Assert that all connections are in pool. - c.Assert( - t.client.ConnPool.(*redis.MultiConnPool).Len(), - Equals, - t.openedConnCount-t.closedConnCount, - ) - - c.Assert(t.openedConnCount, Equals, t.initedConnCount) +func (t *RedisTest) SetUpTest(c *C) { t.resetRedis(c) } @@ -275,7 +320,7 @@ func (t *RedisTest) resetRedis(c *C) { //------------------------------------------------------------------------------ -func (t *RedisTest) TestReqStringMethod(c *C) { +func (t *RedisTest) TestCmdStringMethod(c *C) { set := t.client.Set("foo", "bar") c.Assert(set.String(), Equals, "SET foo bar: OK") @@ -283,9 +328,9 @@ func (t *RedisTest) TestReqStringMethod(c *C) { c.Assert(get.String(), Equals, "GET foo: bar") } -func (t *RedisTest) TestReqStringMethodError(c *C) { +func (t *RedisTest) TestCmdStringMethodError(c *C) { get2 := t.client.Get("key_does_not_exists") - c.Assert(get2.String(), Equals, "GET key_does_not_exists: (nil)") + c.Assert(get2.String(), Equals, "GET key_does_not_exists: redis: nil") } func (t *RedisTest) TestRunWithouthCheckingErrVal(c *C) { @@ -354,30 +399,6 @@ func (t *RedisTest) TestManyKeys2(c *C) { //------------------------------------------------------------------------------ -func (t *RedisTest) TestConnPoolRemovesBrokenConn(c *C) { - conn, err := net.Dial("tcp", redisAddr) - c.Assert(err, IsNil) - c.Assert(conn.Close(), IsNil) - - client := redis.NewTCPClient(redisAddr, "", -1) - client.ConnPool.(*redis.MultiConnPool).MaxCap = 1 - defer func() { - c.Assert(client.Close(), IsNil) - }() - - c.Assert(client.ConnPool.Add(redis.NewConn(conn)), IsNil) - - ping := client.Ping() - c.Assert(ping.Err().Error(), Equals, "use of closed network connection") - c.Assert(ping.Val(), Equals, "") - - ping = client.Ping() - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") -} - -//------------------------------------------------------------------------------ - func (t *RedisTest) TestAuth(c *C) { auth := t.client.Auth("password") c.Assert(auth.Err(), ErrorMatches, "ERR Client sent AUTH, but no password is set") @@ -446,13 +467,13 @@ func (t *RedisTest) TestCmdKeysExpire(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - expire := t.client.Expire("key", 10) + expire := t.client.Expire("key", 10*time.Second) c.Assert(expire.Err(), IsNil) c.Assert(expire.Val(), Equals, true) ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(10)) + c.Assert(ttl.Val(), Equals, 10*time.Second) set = t.client.Set("key", "Hello World") c.Assert(set.Err(), IsNil) @@ -460,7 +481,7 @@ func (t *RedisTest) TestCmdKeysExpire(c *C) { ttl = t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(-1)) + c.Assert(ttl.Val() < 0, Equals, true) } func (t *RedisTest) TestCmdKeysExpireAt(c *C) { @@ -472,7 +493,7 @@ func (t *RedisTest) TestCmdKeysExpireAt(c *C) { c.Assert(exists.Err(), IsNil) c.Assert(exists.Val(), Equals, true) - expireAt := t.client.ExpireAt("key", 1293840000) + expireAt := t.client.ExpireAt("key", time.Now().Add(-time.Hour)) c.Assert(expireAt.Err(), IsNil) c.Assert(expireAt.Val(), Equals, true) @@ -558,7 +579,7 @@ func (t *RedisTest) TestCmdKeysObject(c *C) { idleTime := t.client.ObjectIdleTime("key") c.Assert(idleTime.Err(), IsNil) - c.Assert(idleTime.Val(), Equals, int64(0)) + c.Assert(idleTime.Val(), Equals, time.Duration(0)) } func (t *RedisTest) TestCmdKeysPersist(c *C) { @@ -566,13 +587,13 @@ func (t *RedisTest) TestCmdKeysPersist(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - expire := t.client.Expire("key", 10) + expire := t.client.Expire("key", 10*time.Second) c.Assert(expire.Err(), IsNil) c.Assert(expire.Val(), Equals, true) ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(10)) + c.Assert(ttl.Val(), Equals, 10*time.Second) persist := t.client.Persist("key") c.Assert(persist.Err(), IsNil) @@ -580,7 +601,7 @@ func (t *RedisTest) TestCmdKeysPersist(c *C) { ttl = t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(-1)) + c.Assert(ttl.Val() < 0, Equals, true) } func (t *RedisTest) TestCmdKeysPExpire(c *C) { @@ -588,17 +609,19 @@ func (t *RedisTest) TestCmdKeysPExpire(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - pexpire := t.client.PExpire("key", 1900) + expiration := 900 * time.Millisecond + pexpire := t.client.PExpire("key", expiration) c.Assert(pexpire.Err(), IsNil) c.Assert(pexpire.Val(), Equals, true) ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(2)) + c.Assert(ttl.Val(), Equals, time.Second) pttl := t.client.PTTL("key") c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() > 1800 && pttl.Val() <= 1900, Equals, true) + c.Assert(pttl.Val() <= expiration, Equals, true) + c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) } func (t *RedisTest) TestCmdKeysPExpireAt(c *C) { @@ -606,17 +629,19 @@ func (t *RedisTest) TestCmdKeysPExpireAt(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - pExpireAt := t.client.PExpireAt("key", 1555555555005) - c.Assert(pExpireAt.Err(), IsNil) - c.Assert(pExpireAt.Val(), Equals, true) + expiration := 900 * time.Millisecond + pexpireat := t.client.PExpireAt("key", time.Now().Add(expiration)) + c.Assert(pexpireat.Err(), IsNil) + c.Assert(pexpireat.Val(), Equals, true) ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Not(Equals), int64(0)) + c.Assert(ttl.Val(), Equals, time.Second) pttl := t.client.PTTL("key") c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val(), Not(Equals), int64(0)) + c.Assert(pttl.Val() <= expiration, Equals, true) + c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) } func (t *RedisTest) TestCmdKeysPTTL(c *C) { @@ -624,13 +649,15 @@ func (t *RedisTest) TestCmdKeysPTTL(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - expire := t.client.Expire("key", 1) + expiration := time.Second + expire := t.client.Expire("key", expiration) c.Assert(expire.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") pttl := t.client.PTTL("key") c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() > 900 && pttl.Val() <= 1000, Equals, true) + c.Assert(pttl.Val() <= expiration, Equals, true) + c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) } func (t *RedisTest) TestCmdKeysRandomKey(c *C) { @@ -718,19 +745,19 @@ func (t *RedisTest) TestCmdKeysSort(c *C) { func (t *RedisTest) TestCmdKeysTTL(c *C) { ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(-1)) + c.Assert(ttl.Val() < 0, Equals, true) set := t.client.Set("key", "hello") c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - expire := t.client.Expire("key", 60) + expire := t.client.Expire("key", 60*time.Second) c.Assert(expire.Err(), IsNil) c.Assert(expire.Val(), Equals, true) ttl = t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(60)) + c.Assert(ttl.Val(), Equals, 60*time.Second) } func (t *RedisTest) TestCmdKeysType(c *C) { @@ -743,6 +770,54 @@ func (t *RedisTest) TestCmdKeysType(c *C) { c.Assert(type_.Val(), Equals, "string") } +func (t *RedisTest) TestCmdScan(c *C) { + for i := 0; i < 1000; i++ { + set := t.client.Set(fmt.Sprintf("key%d", i), "hello") + c.Assert(set.Err(), IsNil) + } + + cursor, keys, err := t.client.Scan(0, "", 0).Result() + c.Assert(err, IsNil) + c.Assert(cursor > 0, Equals, true) + c.Assert(len(keys) > 0, Equals, true) +} + +func (t *RedisTest) TestCmdSScan(c *C) { + for i := 0; i < 1000; i++ { + sadd := t.client.SAdd("myset", fmt.Sprintf("member%d", i)) + c.Assert(sadd.Err(), IsNil) + } + + cursor, keys, err := t.client.SScan("myset", 0, "", 0).Result() + c.Assert(err, IsNil) + c.Assert(cursor > 0, Equals, true) + c.Assert(len(keys) > 0, Equals, true) +} + +func (t *RedisTest) TestCmdHScan(c *C) { + for i := 0; i < 1000; i++ { + sadd := t.client.HSet("myhash", fmt.Sprintf("key%d", i), "hello") + c.Assert(sadd.Err(), IsNil) + } + + cursor, keys, err := t.client.HScan("myhash", 0, "", 0).Result() + c.Assert(err, IsNil) + c.Assert(cursor > 0, Equals, true) + c.Assert(len(keys) > 0, Equals, true) +} + +func (t *RedisTest) TestCmdZScan(c *C) { + for i := 0; i < 1000; i++ { + sadd := t.client.ZAdd("myset", redis.Z{float64(i), fmt.Sprintf("member%d", i)}) + c.Assert(sadd.Err(), IsNil) + } + + cursor, keys, err := t.client.ZScan("myset", 0, "", 0).Result() + c.Assert(err, IsNil) + c.Assert(cursor > 0, Equals, true) + c.Assert(len(keys) > 0, Equals, true) +} + //------------------------------------------------------------------------------ func (t *RedisTest) TestStringsAppend(c *C) { @@ -1014,13 +1089,15 @@ func (t *RedisTest) TestStringsMSetNX(c *C) { } func (t *RedisTest) TestStringsPSetEx(c *C) { - pSetEx := t.client.PSetEx("key", 1000, "hello") - c.Assert(pSetEx.Err(), IsNil) - c.Assert(pSetEx.Val(), Equals, "OK") + expiration := 50 * time.Millisecond + psetex := t.client.PSetEx("key", expiration, "hello") + c.Assert(psetex.Err(), IsNil) + c.Assert(psetex.Val(), Equals, "OK") pttl := t.client.PTTL("key") c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() > 900 && pttl.Val() <= 1000, Equals, true) + c.Assert(pttl.Val() <= expiration, Equals, true) + c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) get := t.client.Get("key") c.Assert(get.Err(), IsNil) @@ -1038,13 +1115,13 @@ func (t *RedisTest) TestStringsSetGet(c *C) { } func (t *RedisTest) TestStringsSetEx(c *C) { - setEx := t.client.SetEx("key", 10, "hello") + setEx := t.client.SetEx("key", 10*time.Second, "hello") c.Assert(setEx.Err(), IsNil) c.Assert(setEx.Val(), Equals, "OK") ttl := t.client.TTL("key") c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, int64(10)) + c.Assert(ttl.Val(), Equals, 10*time.Second) } func (t *RedisTest) TestStringsSetNX(c *C) { @@ -1188,14 +1265,18 @@ func (t *RedisTest) TestCmdHIncrByFloat(c *C) { } func (t *RedisTest) TestCmdHKeys(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) + hkeys := t.client.HKeys("hash") + c.Assert(hkeys.Err(), IsNil) + c.Assert(hkeys.Val(), DeepEquals, []string{}) - hKeys := t.client.HKeys("hash") - c.Assert(hKeys.Err(), IsNil) - c.Assert(hKeys.Val(), DeepEquals, []string{"key1", "key2"}) + hset := t.client.HSet("hash", "key1", "hello1") + c.Assert(hset.Err(), IsNil) + hset = t.client.HSet("hash", "key2", "hello2") + c.Assert(hset.Err(), IsNil) + + hkeys = t.client.HKeys("hash") + c.Assert(hkeys.Err(), IsNil) + c.Assert(hkeys.Val(), DeepEquals, []string{"key1", "key2"}) } func (t *RedisTest) TestCmdHLen(c *C) { @@ -1331,9 +1412,9 @@ func (t *RedisTest) TestCmdListsBRPopBlocks(c *C) { done := make(chan bool) go func() { started <- true - bRPop := t.client.BRPop(0, "list") - c.Assert(bRPop.Err(), IsNil) - c.Assert(bRPop.Val(), DeepEquals, []string{"list", "a"}) + brpop := t.client.BRPop(0, "list") + c.Assert(brpop.Err(), IsNil) + c.Assert(brpop.Val(), DeepEquals, []string{"list", "a"}) done <- true }() <-started @@ -2027,44 +2108,31 @@ func (t *RedisTest) TestZRangeByScore(c *C) { zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) c.Assert(zAdd.Err(), IsNil) - zRangeByScore := t.client.ZRangeByScore("zset", "-inf", "+inf", 0, 0) + zRangeByScore := t.client.ZRangeByScore("zset", redis.ZRangeByScore{ + Min: "-inf", + Max: "+inf", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "two", "three"}) - zRangeByScore = t.client.ZRangeByScore("zset", "1", "2", 0, 0) + zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ + Min: "1", + Max: "2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "two"}) - zRangeByScore = t.client.ZRangeByScore("zset", "(1", "2", 0, 0) + zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ + Min: "(1", + Max: "2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, []string{"two"}) - zRangeByScore = t.client.ZRangeByScore("zset", "(1", "(2", 0, 0) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{}) -} - -func (t *RedisTest) TestZRangeByScoreWithScores(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRangeByScore := t.client.ZRangeByScoreWithScores("zset", "-inf", "+inf", 0, 0) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "1", "two", "2", "three", "3"}) - - zRangeByScore = t.client.ZRangeByScoreWithScores("zset", "1", "2", 0, 0) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "1", "two", "2"}) - - zRangeByScore = t.client.ZRangeByScoreWithScores("zset", "(1", "2", 0, 0) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"two", "2"}) - - zRangeByScore = t.client.ZRangeByScoreWithScores("zset", "(1", "(2", 0, 0) + zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ + Min: "(1", + Max: "(2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, []string{}) } @@ -2077,19 +2145,31 @@ func (t *RedisTest) TestZRangeByScoreWithScoresMap(c *C) { zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) c.Assert(zAdd.Err(), IsNil) - zRangeByScore := t.client.ZRangeByScoreWithScoresMap("zset", "-inf", "+inf", 0, 0) + zRangeByScore := t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ + Min: "-inf", + Max: "+inf", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"one": 1, "two": 2, "three": 3}) - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", "1", "2", 0, 0) + zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ + Min: "1", + Max: "2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"one": 1, "two": 2}) - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", "(1", "2", 0, 0) + zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ + Min: "(1", + Max: "2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"two": 2}) - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", "(1", "(2", 0, 0) + zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ + Min: "(1", + Max: "(2", + }) c.Assert(zRangeByScore.Err(), IsNil) c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{}) } @@ -2205,45 +2285,41 @@ func (t *RedisTest) TestZRevRangeWithScoresMap(c *C) { } func (t *RedisTest) TestZRevRangeByScore(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) + zadd := t.client.ZAdd("zset", redis.Z{1, "one"}) + c.Assert(zadd.Err(), IsNil) + zadd = t.client.ZAdd("zset", redis.Z{2, "two"}) + c.Assert(zadd.Err(), IsNil) + zadd = t.client.ZAdd("zset", redis.Z{3, "three"}) + c.Assert(zadd.Err(), IsNil) - zRevRangeByScore := t.client.ZRevRangeByScore("zset", "+inf", "-inf", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{"three", "two", "one"}) + vals, err := t.client.ZRevRangeByScore( + "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}).Result() + c.Assert(err, IsNil) + c.Assert(vals, DeepEquals, []string{"three", "two", "one"}) - zRevRangeByScore = t.client.ZRevRangeByScore("zset", "2", "(1", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{"two"}) + vals, err = t.client.ZRevRangeByScore( + "zset", redis.ZRangeByScore{Max: "2", Min: "(1"}).Result() + c.Assert(err, IsNil) + c.Assert(vals, DeepEquals, []string{"two"}) - zRevRangeByScore = t.client.ZRevRangeByScore("zset", "(2", "(1", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{}) + vals, err = t.client.ZRevRangeByScore( + "zset", redis.ZRangeByScore{Max: "(2", Min: "(1"}).Result() + c.Assert(err, IsNil) + c.Assert(vals, DeepEquals, []string{}) } func (t *RedisTest) TestZRevRangeByScoreWithScores(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) + zadd := t.client.ZAdd("zset", redis.Z{1, "one"}) + c.Assert(zadd.Err(), IsNil) + zadd = t.client.ZAdd("zset", redis.Z{2, "two"}) + c.Assert(zadd.Err(), IsNil) + zadd = t.client.ZAdd("zset", redis.Z{3, "three"}) + c.Assert(zadd.Err(), IsNil) - zRevRangeByScore := t.client.ZRevRangeByScoreWithScores("zset", "+inf", "-inf", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{"three", "3", "two", "2", "one", "1"}) - - zRevRangeByScore = t.client.ZRevRangeByScoreWithScores("zset", "2", "(1", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{"two", "2"}) - - zRevRangeByScore = t.client.ZRevRangeByScoreWithScores("zset", "(2", "(1", 0, 0) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, []string{}) + vals, err := t.client.ZRevRangeByScoreWithScores( + "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}).Result() + c.Assert(err, IsNil) + c.Assert(vals, DeepEquals, []string{"three", "3", "two", "2", "one", "1"}) } func (t *RedisTest) TestZRevRangeByScoreWithScoresMap(c *C) { @@ -2254,15 +2330,18 @@ func (t *RedisTest) TestZRevRangeByScoreWithScoresMap(c *C) { zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) c.Assert(zAdd.Err(), IsNil) - zRevRangeByScore := t.client.ZRevRangeByScoreWithScoresMap("zset", "+inf", "-inf", 0, 0) + zRevRangeByScore := t.client.ZRevRangeByScoreWithScoresMap( + "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}) c.Assert(zRevRangeByScore.Err(), IsNil) c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{"three": 3, "two": 2, "one": 1}) - zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap("zset", "2", "(1", 0, 0) + zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap( + "zset", redis.ZRangeByScore{Max: "2", Min: "(1"}) c.Assert(zRevRangeByScore.Err(), IsNil) c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{"two": 2}) - zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap("zset", "(2", "(1", 0, 0) + zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap( + "zset", redis.ZRangeByScore{Max: "(2", Min: "(1"}) c.Assert(zRevRangeByScore.Err(), IsNil) c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{}) } @@ -2319,69 +2398,60 @@ func (t *RedisTest) TestZUnionStore(c *C) { //------------------------------------------------------------------------------ func (t *RedisTest) TestPatternPubSub(c *C) { - pubsub, err := t.client.PubSubClient() - c.Assert(err, IsNil) + pubsub := t.client.PubSub() defer func() { c.Assert(pubsub.Close(), IsNil) }() - ch, err := pubsub.PSubscribe("mychannel*") - c.Assert(err, IsNil) - c.Assert(ch, Not(IsNil)) + c.Assert(pubsub.PSubscribe("mychannel*"), IsNil) pub := t.client.Publish("mychannel1", "hello") c.Assert(pub.Err(), IsNil) c.Assert(pub.Val(), Equals, int64(1)) - err = pubsub.PUnsubscribe("mychannel*") - c.Assert(err, IsNil) + c.Assert(pubsub.PUnsubscribe("mychannel*"), IsNil) - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "psubscribe") - c.Assert(msg.Channel, Equals, "mychannel*") - c.Assert(msg.Number, Equals, int64(1)) - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "psubscribe") + c.Assert(subscr.Channel, Equals, "mychannel*") + c.Assert(subscr.Count, Equals, 1) } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "pmessage") - c.Assert(msg.ChannelPattern, Equals, "mychannel*") - c.Assert(msg.Channel, Equals, "mychannel1") - c.Assert(msg.Message, Equals, "hello") - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.PMessage) + c.Assert(subscr.Channel, Equals, "mychannel1") + c.Assert(subscr.Pattern, Equals, "mychannel*") + c.Assert(subscr.Payload, Equals, "hello") } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "punsubscribe") - c.Assert(msg.Channel, Equals, "mychannel*") - c.Assert(msg.Number, Equals, int64(0)) - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "punsubscribe") + c.Assert(subscr.Channel, Equals, "mychannel*") + c.Assert(subscr.Count, Equals, 0) + } + + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err.(net.Error).Timeout(), Equals, true) + c.Assert(msgi, IsNil) } } func (t *RedisTest) TestPubSub(c *C) { - pubsub, err := t.client.PubSubClient() - c.Assert(err, IsNil) + pubsub := t.client.PubSub() defer func() { c.Assert(pubsub.Close(), IsNil) }() - ch, err := pubsub.Subscribe("mychannel") - c.Assert(err, IsNil) - c.Assert(ch, Not(IsNil)) - - ch2, err := pubsub.Subscribe("mychannel2") - c.Assert(err, IsNil) - c.Assert(ch2, Equals, ch) + c.Assert(pubsub.Subscribe("mychannel", "mychannel2"), IsNil) pub := t.client.Publish("mychannel", "hello") c.Assert(pub.Err(), IsNil) @@ -2391,70 +2461,64 @@ func (t *RedisTest) TestPubSub(c *C) { c.Assert(pub.Err(), IsNil) c.Assert(pub.Val(), Equals, int64(1)) - err = pubsub.Unsubscribe("mychannel") - c.Assert(err, IsNil) + c.Assert(pubsub.Unsubscribe("mychannel", "mychannel2"), IsNil) - err = pubsub.Unsubscribe("mychannel2") - c.Assert(err, IsNil) - - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "subscribe") - c.Assert(msg.Channel, Equals, "mychannel") - c.Assert(msg.Number, Equals, int64(1)) - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "subscribe") + c.Assert(subscr.Channel, Equals, "mychannel") + c.Assert(subscr.Count, Equals, 1) } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "subscribe") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "subscribe") + c.Assert(subscr.Channel, Equals, "mychannel2") + c.Assert(subscr.Count, Equals, 2) + } + + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Message) + c.Assert(subscr.Channel, Equals, "mychannel") + c.Assert(subscr.Payload, Equals, "hello") + } + + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + msg := msgi.(*redis.Message) c.Assert(msg.Channel, Equals, "mychannel2") - c.Assert(msg.Number, Equals, int64(2)) - case <-time.After(time.Second): - c.Error("Channel is empty.") + c.Assert(msg.Payload, Equals, "hello2") } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "message") - c.Assert(msg.Channel, Equals, "mychannel") - c.Assert(msg.Message, Equals, "hello") - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "unsubscribe") + c.Assert(subscr.Channel, Equals, "mychannel") + c.Assert(subscr.Count, Equals, 1) } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "message") - c.Assert(msg.Channel, Equals, "mychannel2") - c.Assert(msg.Message, Equals, "hello2") - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err, IsNil) + subscr := msgi.(*redis.Subscription) + c.Assert(subscr.Kind, Equals, "unsubscribe") + c.Assert(subscr.Channel, Equals, "mychannel2") + c.Assert(subscr.Count, Equals, 0) } - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "unsubscribe") - c.Assert(msg.Channel, Equals, "mychannel") - c.Assert(msg.Number, Equals, int64(1)) - case <-time.After(time.Second): - c.Error("Channel is empty.") - } - - select { - case msg := <-ch: - c.Assert(msg.Err, Equals, nil) - c.Assert(msg.Name, Equals, "unsubscribe") - c.Assert(msg.Channel, Equals, "mychannel2") - c.Assert(msg.Number, Equals, int64(0)) - case <-time.After(time.Second): - c.Error("Channel is empty.") + { + msgi, err := pubsub.ReceiveTimeout(time.Second) + c.Assert(err.(net.Error).Timeout(), Equals, true) + c.Assert(msgi, IsNil) } } @@ -2465,8 +2529,7 @@ func (t *RedisTest) TestPipeline(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) + pipeline := t.client.Pipeline() defer func() { c.Assert(pipeline.Close(), IsNil) }() @@ -2476,9 +2539,9 @@ func (t *RedisTest) TestPipeline(c *C) { incr := pipeline.Incr("key3") getNil := pipeline.Get("key4") - reqs, err := pipeline.RunQueued() - c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 4) + cmds, err := pipeline.Exec() + c.Assert(err, Equals, redis.Nil) + c.Assert(cmds, HasLen, 4) c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") @@ -2494,104 +2557,99 @@ func (t *RedisTest) TestPipeline(c *C) { } func (t *RedisTest) TestPipelineDiscardQueued(c *C) { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() + pipeline := t.client.Pipeline() pipeline.Get("key") - pipeline.DiscardQueued() - reqs, err := pipeline.RunQueued() + pipeline.Discard() + cmds, err := pipeline.Exec() c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 0) + c.Assert(cmds, HasLen, 0) + + c.Assert(pipeline.Close(), IsNil) } func (t *RedisTest) TestPipelineFunc(c *C) { - var get *redis.StringReq - reqs, err := t.client.Pipelined(func(c *redis.PipelineClient) { + var get *redis.StringCmd + cmds, err := t.client.Pipelined(func(c *redis.Pipeline) { get = c.Get("foo") }) - c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 1) + c.Assert(err, Equals, redis.Nil) + c.Assert(cmds, HasLen, 1) c.Assert(get.Err(), Equals, redis.Nil) c.Assert(get.Val(), Equals, "") } func (t *RedisTest) TestPipelineErrValNotSet(c *C) { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) + pipeline := t.client.Pipeline() defer func() { c.Assert(pipeline.Close(), IsNil) }() get := pipeline.Get("key") - c.Assert(get.Err(), ErrorMatches, "redis: value is not set") + c.Assert(get.Err(), IsNil) + c.Assert(get.Val(), Equals, "") } func (t *RedisTest) TestPipelineRunQueuedOnEmptyQueue(c *C) { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) + pipeline := t.client.Pipeline() defer func() { c.Assert(pipeline.Close(), IsNil) }() - reqs, err := pipeline.RunQueued() + cmds, err := pipeline.Exec() c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 0) + c.Assert(cmds, HasLen, 0) } -func (t *RedisTest) TestPipelineIncrFromGoroutines(c *C) { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() +// TODO: make thread safe? +func (t *RedisTest) TestPipelineIncr(c *C) { + const N = 20000 + key := "TestPipelineIncr" + + pipeline := t.client.Pipeline() wg := &sync.WaitGroup{} - for i := int64(0); i < 20000; i++ { - wg.Add(1) - go func() { - pipeline.Incr("TestIncrPipeliningFromGoroutinesKey") - wg.Done() - }() + wg.Add(N) + for i := 0; i < N; i++ { + pipeline.Incr(key) + wg.Done() } wg.Wait() - reqs, err := pipeline.RunQueued() + cmds, err := pipeline.Exec() c.Assert(err, IsNil) - c.Assert(len(reqs), Equals, 20000) - for _, req := range reqs { - if req.Err() != nil { - c.Errorf("got %v, expected nil", req.Err()) + c.Assert(len(cmds), Equals, 20000) + for _, cmd := range cmds { + if cmd.Err() != nil { + c.Errorf("got %v, expected nil", cmd.Err()) } } - get := t.client.Get("TestIncrPipeliningFromGoroutinesKey") + get := t.client.Get(key) c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "20000") + c.Assert(get.Val(), Equals, strconv.Itoa(N)) + + c.Assert(pipeline.Close(), IsNil) } -func (t *RedisTest) TestPipelineEchoFromGoroutines(c *C) { - pipeline, err := t.client.PipelineClient() - c.Assert(err, IsNil) - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() +func (t *RedisTest) TestPipelineEcho(c *C) { + const N = 1000 wg := &sync.WaitGroup{} - for i := int64(0); i < 1000; i += 2 { - wg.Add(1) - go func() { - msg1 := "echo" + strconv.FormatInt(i, 10) - msg2 := "echo" + strconv.FormatInt(i+1, 10) + wg.Add(N) + for i := 0; i < N; i++ { + go func(i int) { + pipeline := t.client.Pipeline() + + msg1 := "echo" + strconv.Itoa(i) + msg2 := "echo" + strconv.Itoa(i+1) echo1 := pipeline.Echo(msg1) echo2 := pipeline.Echo(msg2) - reqs, err := pipeline.RunQueued() + cmds, err := pipeline.Exec() c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 2) + c.Assert(cmds, HasLen, 2) c.Assert(echo1.Err(), IsNil) c.Assert(echo1.Val(), Equals, msg1) @@ -2599,8 +2657,10 @@ func (t *RedisTest) TestPipelineEchoFromGoroutines(c *C) { c.Assert(echo2.Err(), IsNil) c.Assert(echo2.Val(), Equals, msg2) + c.Assert(pipeline.Close(), IsNil) + wg.Done() - }() + }(i) } wg.Wait() } @@ -2608,22 +2668,21 @@ func (t *RedisTest) TestPipelineEchoFromGoroutines(c *C) { //------------------------------------------------------------------------------ func (t *RedisTest) TestMultiExec(c *C) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() var ( - set *redis.StatusReq - get *redis.StringReq + set *redis.StatusCmd + get *redis.StringCmd ) - reqs, err := multi.Exec(func() { + cmds, err := multi.Exec(func() { set = multi.Set("key", "hello") get = multi.Get("key") }) c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 2) + c.Assert(cmds, HasLen, 2) c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") @@ -2633,19 +2692,18 @@ func (t *RedisTest) TestMultiExec(c *C) { } func (t *RedisTest) TestMultiExecDiscard(c *C) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() - reqs, err := multi.Exec(func() { + cmds, err := multi.Exec(func() { multi.Set("key1", "hello1") multi.Discard() multi.Set("key2", "hello2") }) c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 1) + c.Assert(cmds, HasLen, 1) get := t.client.Get("key1") c.Assert(get.Err(), Equals, redis.Nil) @@ -2657,15 +2715,14 @@ func (t *RedisTest) TestMultiExecDiscard(c *C) { } func (t *RedisTest) TestMultiExecEmpty(c *C) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() - reqs, err := multi.Exec(func() {}) + cmds, err := multi.Exec(func() {}) c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 0) + c.Assert(cmds, HasLen, 0) ping := multi.Ping() c.Check(ping.Err(), IsNil) @@ -2673,45 +2730,42 @@ func (t *RedisTest) TestMultiExecEmpty(c *C) { } func (t *RedisTest) TestMultiExecOnEmptyQueue(c *C) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() - reqs, err := multi.Exec(func() {}) + cmds, err := multi.Exec(func() {}) c.Assert(err, IsNil) - c.Assert(reqs, HasLen, 0) + c.Assert(cmds, HasLen, 0) } -func (t *RedisTest) TestMultiExecIncrTransaction(c *C) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) +func (t *RedisTest) TestMultiExecIncr(c *C) { + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() - reqs, err := multi.Exec(func() { + cmds, err := multi.Exec(func() { for i := int64(0); i < 20000; i++ { - multi.Incr("TestIncrTransactionKey") + multi.Incr("key") } }) c.Assert(err, IsNil) - c.Assert(len(reqs), Equals, 20000) - for _, req := range reqs { - if req.Err() != nil { - c.Errorf("got %v, expected nil", req.Err()) + c.Assert(len(cmds), Equals, 20000) + for _, cmd := range cmds { + if cmd.Err() != nil { + c.Errorf("got %v, expected nil", cmd.Err()) } } - get := t.client.Get("TestIncrTransactionKey") + get := t.client.Get("key") c.Assert(get.Err(), IsNil) c.Assert(get.Val(), Equals, "20000") } -func (t *RedisTest) transactionalIncr(c *C) ([]redis.Req, error) { - multi, err := t.client.MultiClient() - c.Assert(err, IsNil) +func (t *RedisTest) transactionalIncr(c *C) ([]redis.Cmder, error) { + multi := t.client.Multi() defer func() { c.Assert(multi.Close(), IsNil) }() @@ -2727,13 +2781,9 @@ func (t *RedisTest) transactionalIncr(c *C) ([]redis.Req, error) { v, err := strconv.ParseInt(get.Val(), 10, 64) c.Assert(err, IsNil) - reqs, err := multi.Exec(func() { + return multi.Exec(func() { multi.Set("key", strconv.FormatInt(v+1, 10)) }) - if err == redis.Nil { - return t.transactionalIncr(c) - } - return reqs, err } func (t *RedisTest) TestWatchUnwatch(c *C) { @@ -2745,10 +2795,16 @@ func (t *RedisTest) TestWatchUnwatch(c *C) { for i := 0; i < 1000; i++ { wg.Add(1) go func() { - reqs, err := t.transactionalIncr(c) - c.Assert(reqs, HasLen, 1) - c.Assert(err, IsNil) - c.Assert(reqs[0].Err(), IsNil) + for { + cmds, err := t.transactionalIncr(c) + if err == redis.TxFailedErr { + continue + } + c.Assert(err, IsNil) + c.Assert(cmds, HasLen, 1) + c.Assert(cmds[0].Err(), IsNil) + break + } wg.Done() }() } @@ -2761,36 +2817,43 @@ func (t *RedisTest) TestWatchUnwatch(c *C) { //------------------------------------------------------------------------------ -func (t *RedisTest) TestSyncEchoFromGoroutines(c *C) { +func (t *RedisTest) TestRaceEcho(c *C) { + const N = 10000 + wg := &sync.WaitGroup{} - for i := int64(0); i < 1000; i++ { - wg.Add(1) - go func() { - msg := "echo" + strconv.FormatInt(i, 10) + wg.Add(N) + for i := 0; i < N; i++ { + go func(i int) { + msg := "echo" + strconv.Itoa(i) echo := t.client.Echo(msg) c.Assert(echo.Err(), IsNil) c.Assert(echo.Val(), Equals, msg) wg.Done() - }() + }(i) } wg.Wait() } -func (t *RedisTest) TestIncrFromGoroutines(c *C) { +func (t *RedisTest) TestRaceIncr(c *C) { + const N = 10000 + key := "TestIncrFromGoroutines" + wg := &sync.WaitGroup{} - for i := int64(0); i < 20000; i++ { - wg.Add(1) + wg.Add(N) + for i := int64(0); i < N; i++ { go func() { - incr := t.client.Incr("TestIncrFromGoroutinesKey") - c.Assert(incr.Err(), IsNil) + incr := t.client.Incr(key) + if err := incr.Err(); err != nil { + panic(err) + } wg.Done() }() } wg.Wait() - get := t.client.Get("TestIncrFromGoroutinesKey") + get := t.client.Get(key) c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "20000") + c.Assert(get.Val(), Equals, strconv.Itoa(N)) } //------------------------------------------------------------------------------ @@ -2925,15 +2988,15 @@ func (t *RedisTest) TestScriptingEvalSha(c *C) { c.Assert(set.Err(), IsNil) c.Assert(set.Val(), Equals, "OK") - eval := t.client.Eval("return redis.call('get','foo')", []string{}, []string{}) + eval := t.client.Eval("return redis.call('get','foo')", nil, nil) c.Assert(eval.Err(), IsNil) c.Assert(eval.Val(), Equals, "bar") - evalSha := t.client.EvalSha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791", []string{}, []string{}) + evalSha := t.client.EvalSha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791", nil, nil) c.Assert(evalSha.Err(), IsNil) c.Assert(evalSha.Val(), Equals, "bar") - evalSha = t.client.EvalSha("ffffffffffffffffffffffffffffffffffffffff", []string{}, []string{}) + evalSha = t.client.EvalSha("ffffffffffffffffffffffffffffffffffffffff", nil, nil) c.Assert(evalSha.Err(), ErrorMatches, "NOSCRIPT No matching script. Please use EVAL.") c.Assert(evalSha.Val(), Equals, nil) } @@ -2969,6 +3032,53 @@ func (t *RedisTest) TestScriptingScriptLoad(c *C) { c.Assert(scriptLoad.Val(), Equals, "6b1bf486c81ceb7edf3c093f4c48582e38c0e791") } +func (t *RedisTest) TestScriptingNewScript(c *C) { + s := redis.NewScript("return 1") + run := s.Run(t.client, nil, nil) + c.Assert(run.Err(), IsNil) + c.Assert(run.Val(), Equals, int64(1)) +} + +func (t *RedisTest) TestScriptingEvalAndPipeline(c *C) { + pipeline := t.client.Pipeline() + s := redis.NewScript("return 1") + run := s.Eval(pipeline, nil, nil) + _, err := pipeline.Exec() + c.Assert(err, IsNil) + c.Assert(run.Err(), IsNil) + c.Assert(run.Val(), Equals, int64(1)) +} + +func (t *RedisTest) TestScriptingEvalShaAndPipeline(c *C) { + s := redis.NewScript("return 1") + c.Assert(s.Load(t.client).Err(), IsNil) + + pipeline := t.client.Pipeline() + run := s.Eval(pipeline, nil, nil) + _, err := pipeline.Exec() + c.Assert(err, IsNil) + c.Assert(run.Err(), IsNil) + c.Assert(run.Val(), Equals, int64(1)) +} + +//------------------------------------------------------------------------------ + +func (t *RedisTest) TestCmdDebugObject(c *C) { + { + debug := t.client.DebugObject("foo") + c.Assert(debug.Err(), Not(IsNil)) + c.Assert(debug.Err().Error(), Equals, "ERR no such key") + } + + { + t.client.Set("foo", "bar") + debug := t.client.DebugObject("foo") + c.Assert(debug.Err(), IsNil) + c.Assert(debug.Val(), FitsTypeOf, "") + c.Assert(debug.Val(), Not(Equals), "") + } +} + //------------------------------------------------------------------------------ func (t *RedisTest) BenchmarkRedisPing(c *C) { @@ -3013,8 +3123,8 @@ func (t *RedisTest) BenchmarkRedisGet(c *C) { func (t *RedisTest) BenchmarkRedisMGet(c *C) { c.StopTimer() - mSet := t.client.MSet("key1", "hello1", "key2", "hello2") - c.Assert(mSet.Err(), IsNil) + mset := t.client.MSet("key1", "hello1", "key2", "hello2") + c.Assert(mset.Err(), IsNil) c.StartTimer() @@ -3024,28 +3134,3 @@ func (t *RedisTest) BenchmarkRedisMGet(c *C) { } } } - -func (t *RedisTest) BenchmarkRedisWriteRead(c *C) { - c.StopTimer() - - conn, _, err := t.client.ConnPool.Get() - c.Assert(err, IsNil) - defer t.client.ConnPool.Add(conn) - - c.StartTimer() - - for i := 0; i < c.N; i++ { - if err := t.client.WriteReq(conn, redis.NewStatusReq("PING")); err != nil { - panic(err) - } - if _, _, err := conn.Rd.ReadLine(); err != nil { - panic(err) - } - } -} - -func (t *RedisTest) BenchmarkFireAndForget(c *C) { - for i := 0; i < c.N; i++ { - t.client.Incr("key") - } -} diff --git a/req.go b/req.go deleted file mode 100644 index 180bfa4..0000000 --- a/req.go +++ /dev/null @@ -1,315 +0,0 @@ -package redis - -import ( - "fmt" - "strconv" - "strings" -) - -type Req interface { - Args() []string - ParseReply(reader) (interface{}, error) - SetErr(error) - Err() error - SetVal(interface{}) - IfaceVal() interface{} -} - -//------------------------------------------------------------------------------ - -type BaseReq struct { - args []string - - val interface{} - err error -} - -func NewBaseReq(args ...string) *BaseReq { - return &BaseReq{ - args: args, - } -} - -func (r *BaseReq) Args() []string { - return r.args -} - -func (r *BaseReq) SetErr(err error) { - if err == nil { - panic("non-nil value expected") - } - r.err = err -} - -func (r *BaseReq) Err() error { - if r.err != nil { - return r.err - } - if r.val == nil { - return errValNotSet - } - return nil -} - -func (r *BaseReq) SetVal(val interface{}) { - if val == nil { - panic("non-nil value expected") - } - r.val = val -} - -func (r *BaseReq) IfaceVal() interface{} { - return r.val -} - -func (r *BaseReq) ParseReply(rd reader) (interface{}, error) { - return parseReply(rd) -} - -func (r *BaseReq) String() string { - args := strings.Join(r.args, " ") - if r.err != nil { - return args + ": " + r.err.Error() - } else if r.val != nil { - return args + ": " + fmt.Sprint(r.val) - } - return args -} - -//------------------------------------------------------------------------------ - -type IfaceReq struct { - *BaseReq -} - -func NewIfaceReq(args ...string) *IfaceReq { - return &IfaceReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *IfaceReq) Val() interface{} { - return r.val -} - -//------------------------------------------------------------------------------ - -type StatusReq struct { - *BaseReq -} - -func NewStatusReq(args ...string) *StatusReq { - return &StatusReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *StatusReq) Val() string { - if r.val == nil { - return "" - } - return r.val.(string) -} - -//------------------------------------------------------------------------------ - -type IntReq struct { - *BaseReq -} - -func NewIntReq(args ...string) *IntReq { - return &IntReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *IntReq) Val() int64 { - if r.val == nil { - return 0 - } - return r.val.(int64) -} - -//------------------------------------------------------------------------------ - -type BoolReq struct { - *BaseReq -} - -func NewBoolReq(args ...string) *BoolReq { - return &BoolReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *BoolReq) ParseReply(rd reader) (interface{}, error) { - v, err := parseReply(rd) - if err != nil { - return nil, err - } - return v.(int64) == 1, nil -} - -func (r *BoolReq) Val() bool { - if r.val == nil { - return false - } - return r.val.(bool) -} - -//------------------------------------------------------------------------------ - -type StringReq struct { - *BaseReq -} - -func NewStringReq(args ...string) *StringReq { - return &StringReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *StringReq) Val() string { - if r.val == nil { - return "" - } - return r.val.(string) -} - -//------------------------------------------------------------------------------ - -type FloatReq struct { - *BaseReq -} - -func NewFloatReq(args ...string) *FloatReq { - return &FloatReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *FloatReq) ParseReply(rd reader) (interface{}, error) { - v, err := parseReply(rd) - if err != nil { - return nil, err - } - return strconv.ParseFloat(v.(string), 64) -} - -func (r *FloatReq) Val() float64 { - if r.val == nil { - return 0 - } - return r.val.(float64) -} - -//------------------------------------------------------------------------------ - -type IfaceSliceReq struct { - *BaseReq -} - -func NewIfaceSliceReq(args ...string) *IfaceSliceReq { - return &IfaceSliceReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *IfaceSliceReq) Val() []interface{} { - if r.val == nil { - return nil - } - return r.val.([]interface{}) -} - -//------------------------------------------------------------------------------ - -type StringSliceReq struct { - *BaseReq -} - -func NewStringSliceReq(args ...string) *StringSliceReq { - return &StringSliceReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *StringSliceReq) ParseReply(rd reader) (interface{}, error) { - return parseStringSliceReply(rd) -} - -func (r *StringSliceReq) Val() []string { - if r.val == nil { - return nil - } - return r.val.([]string) -} - -//------------------------------------------------------------------------------ - -type BoolSliceReq struct { - *BaseReq -} - -func NewBoolSliceReq(args ...string) *BoolSliceReq { - return &BoolSliceReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *BoolSliceReq) ParseReply(rd reader) (interface{}, error) { - return parseBoolSliceReply(rd) -} - -func (r *BoolSliceReq) Val() []bool { - if r.val == nil { - return nil - } - return r.val.([]bool) -} - -//------------------------------------------------------------------------------ - -type StringStringMapReq struct { - *BaseReq -} - -func NewStringStringMapReq(args ...string) *StringStringMapReq { - return &StringStringMapReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *StringStringMapReq) ParseReply(rd reader) (interface{}, error) { - return parseStringStringMapReply(rd) -} - -func (r *StringStringMapReq) Val() map[string]string { - if r.val == nil { - return nil - } - return r.val.(map[string]string) -} - -//------------------------------------------------------------------------------ - -type StringFloatMapReq struct { - *BaseReq -} - -func NewStringFloatMapReq(args ...string) *StringFloatMapReq { - return &StringFloatMapReq{ - BaseReq: NewBaseReq(args...), - } -} - -func (r *StringFloatMapReq) ParseReply(rd reader) (interface{}, error) { - return parseStringFloatMapReply(rd) -} - -func (r *StringFloatMapReq) Val() map[string]float64 { - if r.val == nil { - return nil - } - return r.val.(map[string]float64) -} diff --git a/req_test.go b/req_test.go deleted file mode 100644 index d7588a3..0000000 --- a/req_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package redis_test - -import ( - "github.com/vmihailenco/bufio" - . "launchpad.net/gocheck" - - "github.com/vmihailenco/redis" -) - -//------------------------------------------------------------------------------ - -type LineReader struct { - line []byte -} - -func NewLineReader(line []byte) *LineReader { - return &LineReader{line: line} -} - -func (r *LineReader) Read(buf []byte) (int, error) { - return copy(buf, r.line), nil -} - -//------------------------------------------------------------------------------ - -type RequestTest struct{} - -var _ = Suite(&RequestTest{}) - -//------------------------------------------------------------------------------ - -func (t *RequestTest) SetUpTest(c *C) {} - -func (t *RequestTest) TearDownTest(c *C) {} - -//------------------------------------------------------------------------------ - -func (t *RequestTest) benchmarkReq(c *C, reqString string, req redis.Req, checker Checker, expected interface{}) { - c.StopTimer() - - lineReader := NewLineReader([]byte(reqString)) - rd := bufio.NewReaderSize(lineReader, 1024) - - for i := 0; i < 10; i++ { - vIface, err := req.ParseReply(rd) - c.Check(err, IsNil) - c.Check(vIface, checker, expected) - req.SetVal(vIface) - } - - c.StartTimer() - - for i := 0; i < c.N; i++ { - v, _ := req.ParseReply(rd) - req.SetVal(v) - } -} - -func (t *RequestTest) BenchmarkStatusReq(c *C) { - t.benchmarkReq(c, "+OK\r\n", redis.NewStatusReq(), Equals, "OK") -} - -func (t *RequestTest) BenchmarkIntReq(c *C) { - t.benchmarkReq(c, ":1\r\n", redis.NewIntReq(), Equals, int64(1)) -} - -func (t *RequestTest) BenchmarkStringReq(c *C) { - t.benchmarkReq(c, "$5\r\nhello\r\n", redis.NewStringReq(), Equals, "hello") -} - -func (t *RequestTest) BenchmarkFloatReq(c *C) { - t.benchmarkReq(c, "$5\r\n1.111\r\n", redis.NewFloatReq(), Equals, 1.111) -} - -func (t *RequestTest) BenchmarkStringSliceReq(c *C) { - t.benchmarkReq( - c, - "*2\r\n$5\r\nhello\r\n$5\r\nhello\r\n", - redis.NewStringSliceReq(), - DeepEquals, - []string{"hello", "hello"}, - ) -} - -func (t *RequestTest) BenchmarkIfaceSliceReq(c *C) { - t.benchmarkReq( - c, - "*2\r\n$5\r\nhello\r\n$5\r\nhello\r\n", - redis.NewIfaceSliceReq(), - DeepEquals, - []interface{}{"hello", "hello"}, - ) -} diff --git a/script.go b/script.go index 6284a23..96c35f5 100644 --- a/script.go +++ b/script.go @@ -7,6 +7,13 @@ import ( "strings" ) +type scripter interface { + Eval(script string, keys []string, args []string) *Cmd + EvalSha(sha1 string, keys []string, args []string) *Cmd + ScriptExists(scripts ...string) *BoolSliceCmd + ScriptLoad(script string) *StringCmd +} + type Script struct { src, hash string } @@ -20,23 +27,23 @@ func NewScript(src string) *Script { } } -func (s *Script) Load(c *Client) *StringReq { +func (s *Script) Load(c scripter) *StringCmd { return c.ScriptLoad(s.src) } -func (s *Script) Exists(c *Client) *BoolSliceReq { +func (s *Script) Exists(c scripter) *BoolSliceCmd { return c.ScriptExists(s.src) } -func (s *Script) Eval(c *Client, keys []string, args []string) *IfaceReq { +func (s *Script) Eval(c scripter, keys []string, args []string) *Cmd { return c.Eval(s.src, keys, args) } -func (s *Script) EvalSha(c *Client, keys []string, args []string) *IfaceReq { +func (s *Script) EvalSha(c scripter, keys []string, args []string) *Cmd { return c.EvalSha(s.hash, keys, args) } -func (s *Script) Run(c *Client, keys []string, args []string) *IfaceReq { +func (s *Script) Run(c *Client, keys []string, args []string) *Cmd { r := s.EvalSha(c, keys, args) if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") { return s.Eval(c, keys, args) diff --git a/v2/README.md b/v2/README.md deleted file mode 100644 index 696c5e0..0000000 --- a/v2/README.md +++ /dev/null @@ -1,50 +0,0 @@ -Redis client for Golang [![Build Status](https://travis-ci.org/vmihailenco/redis.png?branch=master)](https://travis-ci.org/vmihailenco/redis) -======================= - -Supports: - -- Redis 2.8 commands except QUIT, MONITOR, SLOWLOG and SYNC. -- Pub/sub. -- Transactions. -- Pipelining. -- Connection pool. -- TLS connections. -- Thread safety. -- Timeouts. - -API docs: http://godoc.org/github.com/vmihailenco/redis/v2. -Examples: http://godoc.org/github.com/vmihailenco/redis/v2#pkg-examples. - -Installation ------------- - -Install: - - go get github.com/vmihailenco/redis/v2 - -Upgrading from previous version -------------------------------- - -Type system should catch most changes. But you have to manually change `SetEx`, `PSetEx`, `Expire` and `PExpire` to use `time.Duration` instead of `int64`. - -Look and feel -------------- - -Some corner cases: - - SORT list LIMIT 0 2 ASC - vals, err := client.Sort("list", redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result() - - ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2 - vals, err := client.ZRangeByScoreWithScores("zset", redis.ZRangeByScore{ - Min: "-inf", - Max: "+inf", - Offset: 0, - Count: 2, - }).Result() - - ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM - vals, err := client.ZInterStore("out", redis.ZStore{Weights: []int64{2, 3}}, "zset1", "zset2").Result() - - EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello" - vals, err := client.Eval("return {KEYS[1],ARGV[1]}", []string{"key"}, []string{"hello"}).Result() diff --git a/v2/commands.go b/v2/commands.go deleted file mode 100644 index c94adc1..0000000 --- a/v2/commands.go +++ /dev/null @@ -1,1226 +0,0 @@ -package redis - -import ( - "strconv" - "time" -) - -func formatFloat(f float64) string { - return strconv.FormatFloat(f, 'f', -1, 64) -} - -func readTimeout(sec int64) time.Duration { - if sec == 0 { - return 0 - } - return time.Duration(sec+1) * time.Second -} - -//------------------------------------------------------------------------------ - -func (c *Client) Auth(password string) *StatusCmd { - req := NewStatusCmd("AUTH", password) - c.Process(req) - return req -} - -func (c *Client) Echo(message string) *StringCmd { - req := NewStringCmd("ECHO", message) - c.Process(req) - return req -} - -func (c *Client) Ping() *StatusCmd { - req := NewStatusCmd("PING") - c.Process(req) - return req -} - -func (c *Client) Quit() *StatusCmd { - panic("not implemented") -} - -func (c *Client) Select(index int64) *StatusCmd { - req := NewStatusCmd("SELECT", strconv.FormatInt(index, 10)) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) Del(keys ...string) *IntCmd { - args := append([]string{"DEL"}, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) Dump(key string) *StringCmd { - req := NewStringCmd("DUMP", key) - c.Process(req) - return req -} - -func (c *Client) Exists(key string) *BoolCmd { - req := NewBoolCmd("EXISTS", key) - c.Process(req) - return req -} - -func (c *Client) Expire(key string, dur time.Duration) *BoolCmd { - req := NewBoolCmd("EXPIRE", key, strconv.FormatInt(int64(dur/time.Second), 10)) - c.Process(req) - return req -} - -func (c *Client) ExpireAt(key string, tm time.Time) *BoolCmd { - req := NewBoolCmd("EXPIREAT", key, strconv.FormatInt(tm.Unix(), 10)) - c.Process(req) - return req -} - -func (c *Client) Keys(pattern string) *StringSliceCmd { - req := NewStringSliceCmd("KEYS", pattern) - c.Process(req) - return req -} - -func (c *Client) Migrate(host, port, key string, db, timeout int64) *StatusCmd { - req := NewStatusCmd( - "MIGRATE", - host, - port, - key, - strconv.FormatInt(db, 10), - strconv.FormatInt(timeout, 10), - ) - req.setReadTimeout(readTimeout(timeout)) - c.Process(req) - return req -} - -func (c *Client) Move(key string, db int64) *BoolCmd { - req := NewBoolCmd("MOVE", key, strconv.FormatInt(db, 10)) - c.Process(req) - return req -} - -func (c *Client) ObjectRefCount(keys ...string) *IntCmd { - args := append([]string{"OBJECT", "REFCOUNT"}, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ObjectEncoding(keys ...string) *StringCmd { - args := append([]string{"OBJECT", "ENCODING"}, keys...) - req := NewStringCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ObjectIdleTime(keys ...string) *DurationCmd { - args := append([]string{"OBJECT", "IDLETIME"}, keys...) - req := NewDurationCmd(time.Second, args...) - c.Process(req) - return req -} - -func (c *Client) Persist(key string) *BoolCmd { - req := NewBoolCmd("PERSIST", key) - c.Process(req) - return req -} - -func (c *Client) PExpire(key string, dur time.Duration) *BoolCmd { - req := NewBoolCmd("PEXPIRE", key, strconv.FormatInt(int64(dur/time.Millisecond), 10)) - c.Process(req) - return req -} - -func (c *Client) PExpireAt(key string, tm time.Time) *BoolCmd { - req := NewBoolCmd( - "PEXPIREAT", - key, - strconv.FormatInt(tm.UnixNano()/int64(time.Millisecond), 10), - ) - c.Process(req) - return req -} - -func (c *Client) PTTL(key string) *DurationCmd { - req := NewDurationCmd(time.Millisecond, "PTTL", key) - c.Process(req) - return req -} - -func (c *Client) RandomKey() *StringCmd { - req := NewStringCmd("RANDOMKEY") - c.Process(req) - return req -} - -func (c *Client) Rename(key, newkey string) *StatusCmd { - req := NewStatusCmd("RENAME", key, newkey) - c.Process(req) - return req -} - -func (c *Client) RenameNX(key, newkey string) *BoolCmd { - req := NewBoolCmd("RENAMENX", key, newkey) - c.Process(req) - return req -} - -func (c *Client) Restore(key string, ttl int64, value string) *StatusCmd { - req := NewStatusCmd( - "RESTORE", - key, - strconv.FormatInt(ttl, 10), - value, - ) - c.Process(req) - return req -} - -type Sort struct { - By string - Offset, Count float64 - Get []string - Order string - IsAlpha bool - Store string -} - -func (c *Client) Sort(key string, sort Sort) *StringSliceCmd { - args := []string{"SORT", key} - if sort.By != "" { - args = append(args, sort.By) - } - if sort.Offset != 0 || sort.Count != 0 { - args = append(args, "LIMIT", formatFloat(sort.Offset), formatFloat(sort.Count)) - } - for _, get := range sort.Get { - args = append(args, "GET", get) - } - if sort.Order != "" { - args = append(args, sort.Order) - } - if sort.IsAlpha { - args = append(args, "ALPHA") - } - if sort.Store != "" { - args = append(args, "STORE", sort.Store) - } - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) TTL(key string) *DurationCmd { - req := NewDurationCmd(time.Second, "TTL", key) - c.Process(req) - return req -} - -func (c *Client) Type(key string) *StatusCmd { - req := NewStatusCmd("TYPE", key) - c.Process(req) - return req -} - -func (c *Client) Scan(cursor int64, match string, count int64) *ScanCmd { - args := []string{"SCAN", strconv.FormatInt(cursor, 10)} - if match != "" { - args = append(args, "MATCH", match) - } - if count > 0 { - args = append(args, "COUNT", strconv.FormatInt(count, 10)) - } - req := NewScanCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SScan(key string, cursor int64, match string, count int64) *ScanCmd { - args := []string{"SSCAN", key, strconv.FormatInt(cursor, 10)} - if match != "" { - args = append(args, "MATCH", match) - } - if count > 0 { - args = append(args, "COUNT", strconv.FormatInt(count, 10)) - } - req := NewScanCmd(args...) - c.Process(req) - return req -} - -func (c *Client) HScan(key string, cursor int64, match string, count int64) *ScanCmd { - args := []string{"HSCAN", key, strconv.FormatInt(cursor, 10)} - if match != "" { - args = append(args, "MATCH", match) - } - if count > 0 { - args = append(args, "COUNT", strconv.FormatInt(count, 10)) - } - req := NewScanCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZScan(key string, cursor int64, match string, count int64) *ScanCmd { - args := []string{"ZSCAN", key, strconv.FormatInt(cursor, 10)} - if match != "" { - args = append(args, "MATCH", match) - } - if count > 0 { - args = append(args, "COUNT", strconv.FormatInt(count, 10)) - } - req := NewScanCmd(args...) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) Append(key, value string) *IntCmd { - req := NewIntCmd("APPEND", key, value) - c.Process(req) - return req -} - -type BitCount struct { - Start, End int64 -} - -func (c *Client) BitCount(key string, bitCount *BitCount) *IntCmd { - args := []string{"BITCOUNT", key} - if bitCount != nil { - args = append( - args, - strconv.FormatInt(bitCount.Start, 10), - strconv.FormatInt(bitCount.End, 10), - ) - } - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) bitOp(op, destKey string, keys ...string) *IntCmd { - args := []string{"BITOP", op, destKey} - args = append(args, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) BitOpAnd(destKey string, keys ...string) *IntCmd { - return c.bitOp("AND", destKey, keys...) -} - -func (c *Client) BitOpOr(destKey string, keys ...string) *IntCmd { - return c.bitOp("OR", destKey, keys...) -} - -func (c *Client) BitOpXor(destKey string, keys ...string) *IntCmd { - return c.bitOp("XOR", destKey, keys...) -} - -func (c *Client) BitOpNot(destKey string, key string) *IntCmd { - return c.bitOp("NOT", destKey, key) -} - -func (c *Client) Decr(key string) *IntCmd { - req := NewIntCmd("DECR", key) - c.Process(req) - return req -} - -func (c *Client) DecrBy(key string, decrement int64) *IntCmd { - req := NewIntCmd("DECRBY", key, strconv.FormatInt(decrement, 10)) - c.Process(req) - return req -} - -func (c *Client) Get(key string) *StringCmd { - req := NewStringCmd("GET", key) - c.Process(req) - return req -} - -func (c *Client) GetBit(key string, offset int64) *IntCmd { - req := NewIntCmd("GETBIT", key, strconv.FormatInt(offset, 10)) - c.Process(req) - return req -} - -func (c *Client) GetRange(key string, start, end int64) *StringCmd { - req := NewStringCmd( - "GETRANGE", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(end, 10), - ) - c.Process(req) - return req -} - -func (c *Client) GetSet(key, value string) *StringCmd { - req := NewStringCmd("GETSET", key, value) - c.Process(req) - return req -} - -func (c *Client) Incr(key string) *IntCmd { - req := NewIntCmd("INCR", key) - c.Process(req) - return req -} - -func (c *Client) IncrBy(key string, value int64) *IntCmd { - req := NewIntCmd("INCRBY", key, strconv.FormatInt(value, 10)) - c.Process(req) - return req -} - -func (c *Client) IncrByFloat(key string, value float64) *FloatCmd { - req := NewFloatCmd("INCRBYFLOAT", key, formatFloat(value)) - c.Process(req) - return req -} - -func (c *Client) MGet(keys ...string) *SliceCmd { - args := append([]string{"MGET"}, keys...) - req := NewSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) MSet(pairs ...string) *StatusCmd { - args := append([]string{"MSET"}, pairs...) - req := NewStatusCmd(args...) - c.Process(req) - return req -} - -func (c *Client) MSetNX(pairs ...string) *BoolCmd { - args := append([]string{"MSETNX"}, pairs...) - req := NewBoolCmd(args...) - c.Process(req) - return req -} - -func (c *Client) PSetEx(key string, dur time.Duration, value string) *StatusCmd { - req := NewStatusCmd( - "PSETEX", - key, - strconv.FormatInt(int64(dur/time.Millisecond), 10), - value, - ) - c.Process(req) - return req -} - -func (c *Client) Set(key, value string) *StatusCmd { - req := NewStatusCmd("SET", key, value) - c.Process(req) - return req -} - -func (c *Client) SetBit(key string, offset int64, value int) *IntCmd { - req := NewIntCmd( - "SETBIT", - key, - strconv.FormatInt(offset, 10), - strconv.FormatInt(int64(value), 10), - ) - c.Process(req) - return req -} - -func (c *Client) SetEx(key string, dur time.Duration, value string) *StatusCmd { - req := NewStatusCmd("SETEX", key, strconv.FormatInt(int64(dur/time.Second), 10), value) - c.Process(req) - return req -} - -func (c *Client) SetNX(key, value string) *BoolCmd { - req := NewBoolCmd("SETNX", key, value) - c.Process(req) - return req -} - -func (c *Client) SetRange(key string, offset int64, value string) *IntCmd { - req := NewIntCmd("SETRANGE", key, strconv.FormatInt(offset, 10), value) - c.Process(req) - return req -} - -func (c *Client) StrLen(key string) *IntCmd { - req := NewIntCmd("STRLEN", key) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) HDel(key string, fields ...string) *IntCmd { - args := append([]string{"HDEL", key}, fields...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) HExists(key, field string) *BoolCmd { - req := NewBoolCmd("HEXISTS", key, field) - c.Process(req) - return req -} - -func (c *Client) HGet(key, field string) *StringCmd { - req := NewStringCmd("HGET", key, field) - c.Process(req) - return req -} - -func (c *Client) HGetAll(key string) *StringSliceCmd { - req := NewStringSliceCmd("HGETALL", key) - c.Process(req) - return req -} - -func (c *Client) HGetAllMap(key string) *StringStringMapCmd { - req := NewStringStringMapCmd("HGETALL", key) - c.Process(req) - return req -} - -func (c *Client) HIncrBy(key, field string, incr int64) *IntCmd { - req := NewIntCmd("HINCRBY", key, field, strconv.FormatInt(incr, 10)) - c.Process(req) - return req -} - -func (c *Client) HIncrByFloat(key, field string, incr float64) *FloatCmd { - req := NewFloatCmd("HINCRBYFLOAT", key, field, formatFloat(incr)) - c.Process(req) - return req -} - -func (c *Client) HKeys(key string) *StringSliceCmd { - req := NewStringSliceCmd("HKEYS", key) - c.Process(req) - return req -} - -func (c *Client) HLen(key string) *IntCmd { - req := NewIntCmd("HLEN", key) - c.Process(req) - return req -} - -func (c *Client) HMGet(key string, fields ...string) *SliceCmd { - args := append([]string{"HMGET", key}, fields...) - req := NewSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) HMSet(key, field, value string, pairs ...string) *StatusCmd { - args := append([]string{"HMSET", key, field, value}, pairs...) - req := NewStatusCmd(args...) - c.Process(req) - return req -} - -func (c *Client) HSet(key, field, value string) *BoolCmd { - req := NewBoolCmd("HSET", key, field, value) - c.Process(req) - return req -} - -func (c *Client) HSetNX(key, field, value string) *BoolCmd { - req := NewBoolCmd("HSETNX", key, field, value) - c.Process(req) - return req -} - -func (c *Client) HVals(key string) *StringSliceCmd { - req := NewStringSliceCmd("HVALS", key) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) BLPop(timeout int64, keys ...string) *StringSliceCmd { - args := append([]string{"BLPOP"}, keys...) - args = append(args, strconv.FormatInt(timeout, 10)) - req := NewStringSliceCmd(args...) - req.setReadTimeout(readTimeout(timeout)) - c.Process(req) - return req -} - -func (c *Client) BRPop(timeout int64, keys ...string) *StringSliceCmd { - args := append([]string{"BRPOP"}, keys...) - args = append(args, strconv.FormatInt(timeout, 10)) - req := NewStringSliceCmd(args...) - req.setReadTimeout(readTimeout(timeout)) - c.Process(req) - return req -} - -func (c *Client) BRPopLPush(source, destination string, timeout int64) *StringCmd { - req := NewStringCmd( - "BRPOPLPUSH", - source, - destination, - strconv.FormatInt(timeout, 10), - ) - req.setReadTimeout(readTimeout(timeout)) - c.Process(req) - return req -} - -func (c *Client) LIndex(key string, index int64) *StringCmd { - req := NewStringCmd("LINDEX", key, strconv.FormatInt(index, 10)) - c.Process(req) - return req -} - -func (c *Client) LInsert(key, op, pivot, value string) *IntCmd { - req := NewIntCmd("LINSERT", key, op, pivot, value) - c.Process(req) - return req -} - -func (c *Client) LLen(key string) *IntCmd { - req := NewIntCmd("LLEN", key) - c.Process(req) - return req -} - -func (c *Client) LPop(key string) *StringCmd { - req := NewStringCmd("LPOP", key) - c.Process(req) - return req -} - -func (c *Client) LPush(key string, values ...string) *IntCmd { - args := append([]string{"LPUSH", key}, values...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) LPushX(key, value string) *IntCmd { - req := NewIntCmd("LPUSHX", key, value) - c.Process(req) - return req -} - -func (c *Client) LRange(key string, start, stop int64) *StringSliceCmd { - req := NewStringSliceCmd( - "LRANGE", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(stop, 10), - ) - c.Process(req) - return req -} - -func (c *Client) LRem(key string, count int64, value string) *IntCmd { - req := NewIntCmd("LREM", key, strconv.FormatInt(count, 10), value) - c.Process(req) - return req -} - -func (c *Client) LSet(key string, index int64, value string) *StatusCmd { - req := NewStatusCmd("LSET", key, strconv.FormatInt(index, 10), value) - c.Process(req) - return req -} - -func (c *Client) LTrim(key string, start, stop int64) *StatusCmd { - req := NewStatusCmd( - "LTRIM", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(stop, 10), - ) - c.Process(req) - return req -} - -func (c *Client) RPop(key string) *StringCmd { - req := NewStringCmd("RPOP", key) - c.Process(req) - return req -} - -func (c *Client) RPopLPush(source, destination string) *StringCmd { - req := NewStringCmd("RPOPLPUSH", source, destination) - c.Process(req) - return req -} - -func (c *Client) RPush(key string, values ...string) *IntCmd { - args := append([]string{"RPUSH", key}, values...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) RPushX(key string, value string) *IntCmd { - req := NewIntCmd("RPUSHX", key, value) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) SAdd(key string, members ...string) *IntCmd { - args := append([]string{"SADD", key}, members...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SCard(key string) *IntCmd { - req := NewIntCmd("SCARD", key) - c.Process(req) - return req -} - -func (c *Client) SDiff(keys ...string) *StringSliceCmd { - args := append([]string{"SDIFF"}, keys...) - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SDiffStore(destination string, keys ...string) *IntCmd { - args := append([]string{"SDIFFSTORE", destination}, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SInter(keys ...string) *StringSliceCmd { - args := append([]string{"SINTER"}, keys...) - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SInterStore(destination string, keys ...string) *IntCmd { - args := append([]string{"SINTERSTORE", destination}, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SIsMember(key, member string) *BoolCmd { - req := NewBoolCmd("SISMEMBER", key, member) - c.Process(req) - return req -} - -func (c *Client) SMembers(key string) *StringSliceCmd { - req := NewStringSliceCmd("SMEMBERS", key) - c.Process(req) - return req -} - -func (c *Client) SMove(source, destination, member string) *BoolCmd { - req := NewBoolCmd("SMOVE", source, destination, member) - c.Process(req) - return req -} - -func (c *Client) SPop(key string) *StringCmd { - req := NewStringCmd("SPOP", key) - c.Process(req) - return req -} - -func (c *Client) SRandMember(key string) *StringCmd { - req := NewStringCmd("SRANDMEMBER", key) - c.Process(req) - return req -} - -func (c *Client) SRem(key string, members ...string) *IntCmd { - args := append([]string{"SREM", key}, members...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SUnion(keys ...string) *StringSliceCmd { - args := append([]string{"SUNION"}, keys...) - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) SUnionStore(destination string, keys ...string) *IntCmd { - args := append([]string{"SUNIONSTORE", destination}, keys...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -type Z struct { - Score float64 - Member string -} - -type ZStore struct { - Weights []int64 - Aggregate string -} - -func (c *Client) ZAdd(key string, members ...Z) *IntCmd { - args := []string{"ZADD", key} - for _, m := range members { - args = append(args, formatFloat(m.Score), m.Member) - } - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZCard(key string) *IntCmd { - req := NewIntCmd("ZCARD", key) - c.Process(req) - return req -} - -func (c *Client) ZCount(key, min, max string) *IntCmd { - req := NewIntCmd("ZCOUNT", key, min, max) - c.Process(req) - return req -} - -func (c *Client) ZIncrBy(key string, increment float64, member string) *FloatCmd { - req := NewFloatCmd("ZINCRBY", key, formatFloat(increment), member) - c.Process(req) - return req -} - -func (c *Client) ZInterStore( - destination string, - store ZStore, - keys ...string, -) *IntCmd { - args := []string{"ZINTERSTORE", destination, strconv.FormatInt(int64(len(keys)), 10)} - args = append(args, keys...) - if len(store.Weights) > 0 { - args = append(args, "WEIGHTS") - for _, weight := range store.Weights { - args = append(args, strconv.FormatInt(weight, 10)) - } - } - if store.Aggregate != "" { - args = append(args, "AGGREGATE", store.Aggregate) - } - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) zRange(key string, start, stop int64, withScores bool) *StringSliceCmd { - args := []string{ - "ZRANGE", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(stop, 10), - } - if withScores { - args = append(args, "WITHSCORES") - } - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRange(key string, start, stop int64) *StringSliceCmd { - return c.zRange(key, start, stop, false) -} - -func (c *Client) ZRangeWithScores(key string, start, stop int64) *StringSliceCmd { - return c.zRange(key, start, stop, true) -} - -func (c *Client) ZRangeWithScoresMap(key string, start, stop int64) *StringFloatMapCmd { - args := []string{ - "ZRANGE", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(stop, 10), - "WITHSCORES", - } - req := NewStringFloatMapCmd(args...) - c.Process(req) - return req -} - -type ZRangeByScore struct { - Min, Max string - - Offset, Count int64 -} - -func (c *Client) zRangeByScore(key string, opt ZRangeByScore, withScores bool) *StringSliceCmd { - args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max} - if withScores { - args = append(args, "WITHSCORES") - } - if opt.Offset != 0 || opt.Count != 0 { - args = append( - args, - "LIMIT", - strconv.FormatInt(opt.Offset, 10), - strconv.FormatInt(opt.Count, 10), - ) - } - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd { - return c.zRangeByScore(key, opt, false) -} - -func (c *Client) ZRangeByScoreWithScores(key string, opt ZRangeByScore) *StringSliceCmd { - return c.zRangeByScore(key, opt, true) -} - -func (c *Client) ZRangeByScoreWithScoresMap(key string, opt ZRangeByScore) *StringFloatMapCmd { - args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max, "WITHSCORES"} - if opt.Offset != 0 || opt.Count != 0 { - args = append( - args, - "LIMIT", - strconv.FormatInt(opt.Offset, 10), - strconv.FormatInt(opt.Count, 10), - ) - } - req := NewStringFloatMapCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRank(key, member string) *IntCmd { - req := NewIntCmd("ZRANK", key, member) - c.Process(req) - return req -} - -func (c *Client) ZRem(key string, members ...string) *IntCmd { - args := append([]string{"ZREM", key}, members...) - req := NewIntCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRemRangeByRank(key string, start, stop int64) *IntCmd { - req := NewIntCmd( - "ZREMRANGEBYRANK", - key, - strconv.FormatInt(start, 10), - strconv.FormatInt(stop, 10), - ) - c.Process(req) - return req -} - -func (c *Client) ZRemRangeByScore(key, min, max string) *IntCmd { - req := NewIntCmd("ZREMRANGEBYSCORE", key, min, max) - c.Process(req) - return req -} - -func (c *Client) zRevRange(key, start, stop string, withScores bool) *StringSliceCmd { - args := []string{"ZREVRANGE", key, start, stop} - if withScores { - args = append(args, "WITHSCORES") - } - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRevRange(key, start, stop string) *StringSliceCmd { - return c.zRevRange(key, start, stop, false) -} - -func (c *Client) ZRevRangeWithScores(key, start, stop string) *StringSliceCmd { - return c.zRevRange(key, start, stop, true) -} - -func (c *Client) ZRevRangeWithScoresMap(key, start, stop string) *StringFloatMapCmd { - args := []string{"ZREVRANGE", key, start, stop, "WITHSCORES"} - req := NewStringFloatMapCmd(args...) - c.Process(req) - return req -} - -func (c *Client) zRevRangeByScore(key string, opt ZRangeByScore, withScores bool) *StringSliceCmd { - args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min} - if withScores { - args = append(args, "WITHSCORES") - } - if opt.Offset != 0 || opt.Count != 0 { - args = append( - args, - "LIMIT", - strconv.FormatInt(opt.Offset, 10), - strconv.FormatInt(opt.Count, 10), - ) - } - req := NewStringSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRevRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd { - return c.zRevRangeByScore(key, opt, false) -} - -func (c *Client) ZRevRangeByScoreWithScores(key string, opt ZRangeByScore) *StringSliceCmd { - return c.zRevRangeByScore(key, opt, true) -} - -func (c *Client) ZRevRangeByScoreWithScoresMap(key string, opt ZRangeByScore) *StringFloatMapCmd { - args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min, "WITHSCORES"} - if opt.Offset != 0 || opt.Count != 0 { - args = append( - args, - "LIMIT", - strconv.FormatInt(opt.Offset, 10), - strconv.FormatInt(opt.Count, 10), - ) - } - req := NewStringFloatMapCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ZRevRank(key, member string) *IntCmd { - req := NewIntCmd("ZREVRANK", key, member) - c.Process(req) - return req -} - -func (c *Client) ZScore(key, member string) *FloatCmd { - req := NewFloatCmd("ZSCORE", key, member) - c.Process(req) - return req -} - -func (c *Client) ZUnionStore( - destination string, - store ZStore, - keys ...string, -) *IntCmd { - args := []string{"ZUNIONSTORE", destination, strconv.FormatInt(int64(len(keys)), 10)} - args = append(args, keys...) - if len(store.Weights) > 0 { - args = append(args, "WEIGHTS") - for _, weight := range store.Weights { - args = append(args, strconv.FormatInt(weight, 10)) - } - } - if store.Aggregate != "" { - args = append(args, "AGGREGATE", store.Aggregate) - } - req := NewIntCmd(args...) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) BgRewriteAOF() *StatusCmd { - req := NewStatusCmd("BGREWRITEAOF") - c.Process(req) - return req -} - -func (c *Client) BgSave() *StatusCmd { - req := NewStatusCmd("BGSAVE") - c.Process(req) - return req -} - -func (c *Client) ClientKill(ipPort string) *StatusCmd { - req := NewStatusCmd("CLIENT", "KILL", ipPort) - c.Process(req) - return req -} - -func (c *Client) ClientList() *StringCmd { - req := NewStringCmd("CLIENT", "LIST") - c.Process(req) - return req -} - -func (c *Client) ConfigGet(parameter string) *SliceCmd { - req := NewSliceCmd("CONFIG", "GET", parameter) - c.Process(req) - return req -} - -func (c *Client) ConfigResetStat() *StatusCmd { - req := NewStatusCmd("CONFIG", "RESETSTAT") - c.Process(req) - return req -} - -func (c *Client) ConfigSet(parameter, value string) *StatusCmd { - req := NewStatusCmd("CONFIG", "SET", parameter, value) - c.Process(req) - return req -} - -func (c *Client) DbSize() *IntCmd { - req := NewIntCmd("DBSIZE") - c.Process(req) - return req -} - -func (c *Client) FlushAll() *StatusCmd { - req := NewStatusCmd("FLUSHALL") - c.Process(req) - return req -} - -func (c *Client) FlushDb() *StatusCmd { - req := NewStatusCmd("FLUSHDB") - c.Process(req) - return req -} - -func (c *Client) Info() *StringCmd { - req := NewStringCmd("INFO") - c.Process(req) - return req -} - -func (c *Client) LastSave() *IntCmd { - req := NewIntCmd("LASTSAVE") - c.Process(req) - return req -} - -func (c *Client) Save() *StatusCmd { - req := NewStatusCmd("SAVE") - c.Process(req) - return req -} - -func (c *Client) shutdown(modifier string) *StatusCmd { - var args []string - if modifier == "" { - args = []string{"SHUTDOWN"} - } else { - args = []string{"SHUTDOWN", modifier} - } - req := NewStatusCmd(args...) - c.Process(req) - c.Close() - return req -} - -func (c *Client) Shutdown() *StatusCmd { - return c.shutdown("") -} - -func (c *Client) ShutdownSave() *StatusCmd { - return c.shutdown("SAVE") -} - -func (c *Client) ShutdownNoSave() *StatusCmd { - return c.shutdown("NOSAVE") -} - -func (c *Client) SlaveOf(host, port string) *StatusCmd { - req := NewStatusCmd("SLAVEOF", host, port) - c.Process(req) - return req -} - -func (c *Client) SlowLog() { - panic("not implemented") -} - -func (c *Client) Sync() { - panic("not implemented") -} - -func (c *Client) Time() *StringSliceCmd { - req := NewStringSliceCmd("TIME") - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) Eval(script string, keys []string, args []string) *Cmd { - reqArgs := []string{"EVAL", script, strconv.FormatInt(int64(len(keys)), 10)} - reqArgs = append(reqArgs, keys...) - reqArgs = append(reqArgs, args...) - req := NewCmd(reqArgs...) - c.Process(req) - return req -} - -func (c *Client) EvalSha(sha1 string, keys []string, args []string) *Cmd { - reqArgs := []string{"EVALSHA", sha1, strconv.FormatInt(int64(len(keys)), 10)} - reqArgs = append(reqArgs, keys...) - reqArgs = append(reqArgs, args...) - req := NewCmd(reqArgs...) - c.Process(req) - return req -} - -func (c *Client) ScriptExists(scripts ...string) *BoolSliceCmd { - args := append([]string{"SCRIPT", "EXISTS"}, scripts...) - req := NewBoolSliceCmd(args...) - c.Process(req) - return req -} - -func (c *Client) ScriptFlush() *StatusCmd { - req := NewStatusCmd("SCRIPT", "FLUSH") - c.Process(req) - return req -} - -func (c *Client) ScriptKill() *StatusCmd { - req := NewStatusCmd("SCRIPT", "KILL") - c.Process(req) - return req -} - -func (c *Client) ScriptLoad(script string) *StringCmd { - req := NewStringCmd("SCRIPT", "LOAD", script) - c.Process(req) - return req -} - -//------------------------------------------------------------------------------ - -func (c *Client) DebugObject(key string) *StringCmd { - req := NewStringCmd("DEBUG", "OBJECT", key) - c.Process(req) - return req -} diff --git a/v2/doc.go b/v2/doc.go deleted file mode 100644 index e800154..0000000 --- a/v2/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package github.com/vmihailenco/redis/v2 implements a Redis client. -*/ -package redis diff --git a/v2/example_test.go b/v2/example_test.go deleted file mode 100644 index ee4277c..0000000 --- a/v2/example_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package redis_test - -import ( - "fmt" - "strconv" - - "github.com/vmihailenco/redis/v2" -) - -var client *redis.Client - -func init() { - client = redis.NewTCPClient(&redis.Options{ - Addr: ":6379", - }) -} - -func ExampleNewTCPClient() { - client := redis.NewTCPClient(&redis.Options{ - Addr: "localhost:6379", - Password: "", // no password set - DB: 0, // use default DB - }) - defer client.Close() - - pong, err := client.Ping().Result() - fmt.Println(pong, err) - // Output: PONG -} - -func ExampleClient() { - set := client.Set("foo", "bar") - fmt.Println(set.Err()) - - v, err := client.Get("hello").Result() - fmt.Printf("%q %s %v", v, err, err == redis.Nil) - - // Output: - // "" redis: nil true -} - -func ExampleClient_Pipelined() { - cmds, err := client.Pipelined(func(c *redis.Pipeline) { - c.Set("key1", "hello1") - c.Get("key1") - }) - fmt.Println(err) - set := cmds[0].(*redis.StatusCmd) - fmt.Println(set) - get := cmds[1].(*redis.StringCmd) - fmt.Println(get) - // Output: - // SET key1 hello1: OK - // GET key1: hello1 -} - -func ExamplePipeline() { - pipeline := client.Pipeline() - set := pipeline.Set("key1", "hello1") - get := pipeline.Get("key1") - cmds, err := pipeline.Exec() - fmt.Println(cmds, err) - fmt.Println(set) - fmt.Println(get) - // Output: [SET key1 hello1: OK GET key1: hello1] - // SET key1 hello1: OK - // GET key1: hello1 -} - -func ExampleMulti() { - incr := func(tx *redis.Multi) ([]redis.Cmder, error) { - s, err := tx.Get("key").Result() - if err != nil && err != redis.Nil { - return nil, err - } - n, _ := strconv.ParseInt(s, 10, 64) - - return tx.Exec(func() { - tx.Set("key", strconv.FormatInt(n+1, 10)) - }) - } - - client.Del("key") - - tx := client.Multi() - defer tx.Close() - - watch := tx.Watch("key") - _ = watch.Err() - - for { - cmds, err := incr(tx) - if err == redis.TxFailedErr { - continue - } else if err != nil { - panic(err) - } - fmt.Println(cmds, err) - break - } - - // Output: [SET key 1: OK] -} - -func ExamplePubSub() { - pubsub := client.PubSub() - defer pubsub.Close() - - err := pubsub.Subscribe("mychannel") - _ = err - - msg, err := pubsub.Receive() - fmt.Println(msg, err) - - pub := client.Publish("mychannel", "hello") - _ = pub.Err() - - msg, err = pubsub.Receive() - fmt.Println(msg, err) - - // Output: &{subscribe mychannel 1} - // &{mychannel hello} -} - -func ExampleScript() { - setnx := redis.NewScript(` - if redis.call("get", KEYS[1]) == false then - redis.call("set", KEYS[1], ARGV[1]) - return 1 - end - return 0 - `) - - v1, err := setnx.Run(client, []string{"keynx"}, []string{"foo"}).Result() - fmt.Println(v1.(int64), err) - - v2, err := setnx.Run(client, []string{"keynx"}, []string{"bar"}).Result() - fmt.Println(v2.(int64), err) - - get := client.Get("keynx") - fmt.Println(get) - - // Output: 1 - // 0 - // GET keynx: foo -} - -func Example_customCommand() { - Get := func(client *redis.Client, key string) *redis.StringCmd { - cmd := redis.NewStringCmd("GET", key) - client.Process(cmd) - return cmd - } - - v, err := Get(client, "key_does_not_exist").Result() - fmt.Printf("%q %s", v, err) - // Output: "" redis: nil -} diff --git a/v2/multi.go b/v2/multi.go deleted file mode 100644 index 0360a76..0000000 --- a/v2/multi.go +++ /dev/null @@ -1,134 +0,0 @@ -package redis - -import ( - "errors" - "fmt" -) - -var errDiscard = errors.New("redis: Discard can be used only inside Exec") - -// Not thread-safe. -type Multi struct { - *Client -} - -func (c *Client) Multi() *Multi { - return &Multi{ - Client: &Client{ - baseClient: &baseClient{ - opt: c.opt, - connPool: newSingleConnPool(c.connPool, nil, true), - }, - }, - } -} - -func (c *Multi) Close() error { - c.Unwatch() - return c.Client.Close() -} - -func (c *Multi) Watch(keys ...string) *StatusCmd { - args := append([]string{"WATCH"}, keys...) - cmd := NewStatusCmd(args...) - c.Process(cmd) - return cmd -} - -func (c *Multi) Unwatch(keys ...string) *StatusCmd { - args := append([]string{"UNWATCH"}, keys...) - cmd := NewStatusCmd(args...) - c.Process(cmd) - return cmd -} - -func (c *Multi) Discard() error { - if c.cmds == nil { - return errDiscard - } - c.cmds = c.cmds[:1] - return nil -} - -// Exec always returns list of commands. If transaction fails -// TxFailedErr is returned. Otherwise Exec returns error of the first -// failed command or nil. -func (c *Multi) Exec(f func()) ([]Cmder, error) { - c.cmds = []Cmder{NewStatusCmd("MULTI")} - f() - c.cmds = append(c.cmds, NewSliceCmd("EXEC")) - - cmds := c.cmds - c.cmds = nil - - if len(cmds) == 2 { - return []Cmder{}, nil - } - - cn, err := c.conn() - if err != nil { - setCmdsErr(cmds[1:len(cmds)-1], err) - return cmds[1 : len(cmds)-1], err - } - - err = c.execCmds(cn, cmds) - if err != nil { - c.freeConn(cn, err) - return cmds[1 : len(cmds)-1], err - } - - c.putConn(cn) - return cmds[1 : len(cmds)-1], nil -} - -func (c *Multi) execCmds(cn *conn, cmds []Cmder) error { - err := c.writeCmd(cn, cmds...) - if err != nil { - setCmdsErr(cmds[1:len(cmds)-1], err) - return err - } - - statusCmd := NewStatusCmd() - - // Omit last command (EXEC). - cmdsLen := len(cmds) - 1 - - // Parse queued replies. - for i := 0; i < cmdsLen; i++ { - if err := statusCmd.parseReply(cn.rd); err != nil { - setCmdsErr(cmds[1:len(cmds)-1], err) - return err - } - } - - // Parse number of replies. - line, err := readLine(cn.rd) - if err != nil { - setCmdsErr(cmds[1:len(cmds)-1], err) - return err - } - if line[0] != '*' { - err := fmt.Errorf("redis: expected '*', but got line %q", line) - setCmdsErr(cmds[1:len(cmds)-1], err) - return err - } - if len(line) == 3 && line[1] == '-' && line[2] == '1' { - setCmdsErr(cmds[1:len(cmds)-1], TxFailedErr) - return TxFailedErr - } - - var firstCmdErr error - - // Parse replies. - // Loop starts from 1 to omit MULTI cmd. - for i := 1; i < cmdsLen; i++ { - cmd := cmds[i] - if err := cmd.parseReply(cn.rd); err != nil { - if firstCmdErr == nil { - firstCmdErr = err - } - } - } - - return firstCmdErr -} diff --git a/v2/parser.go b/v2/parser.go deleted file mode 100644 index 729946d..0000000 --- a/v2/parser.go +++ /dev/null @@ -1,276 +0,0 @@ -package redis - -import ( - "errors" - "fmt" - "strconv" - - "github.com/vmihailenco/bufio" -) - -type multiBulkParser func(rd reader, n int64) (interface{}, error) - -// Redis nil reply. -var Nil = errors.New("redis: nil") - -// Redis transaction failed. -var TxFailedErr = errors.New("redis: transaction failed") - -var ( - errReaderTooSmall = errors.New("redis: reader is too small") - errInvalidReplyType = errors.New("redis: invalid reply type") -) - -//------------------------------------------------------------------------------ - -func appendCmd(buf []byte, args []string) []byte { - buf = append(buf, '*') - buf = strconv.AppendUint(buf, uint64(len(args)), 10) - buf = append(buf, '\r', '\n') - for _, arg := range args { - buf = append(buf, '$') - buf = strconv.AppendUint(buf, uint64(len(arg)), 10) - buf = append(buf, '\r', '\n') - buf = append(buf, arg...) - buf = append(buf, '\r', '\n') - } - return buf -} - -//------------------------------------------------------------------------------ - -type reader interface { - ReadLine() ([]byte, bool, error) - Read([]byte) (int, error) - ReadN(n int) ([]byte, error) - Buffered() int - Peek(int) ([]byte, error) -} - -func readLine(rd reader) ([]byte, error) { - line, isPrefix, err := rd.ReadLine() - if err != nil { - return line, err - } - if isPrefix { - return line, errReaderTooSmall - } - return line, nil -} - -func readN(rd reader, n int) ([]byte, error) { - b, err := rd.ReadN(n) - if err == bufio.ErrBufferFull { - newB := make([]byte, n) - r := copy(newB, b) - b = newB - - for { - nn, err := rd.Read(b[r:]) - r += nn - if r >= n { - // Ignore error if we read enough. - break - } - if err != nil { - return nil, err - } - } - } else if err != nil { - return nil, err - } - return b, nil -} - -//------------------------------------------------------------------------------ - -func parseReq(rd reader) ([]string, error) { - line, err := readLine(rd) - if err != nil { - return nil, err - } - - if line[0] != '*' { - return []string{string(line)}, nil - } - numReplies, err := strconv.ParseInt(string(line[1:]), 10, 64) - if err != nil { - return nil, err - } - - args := make([]string, 0, numReplies) - for i := int64(0); i < numReplies; i++ { - line, err = readLine(rd) - if err != nil { - return nil, err - } - if line[0] != '$' { - return nil, fmt.Errorf("redis: expected '$', but got %q", line) - } - - argLen, err := strconv.ParseInt(string(line[1:]), 10, 32) - if err != nil { - return nil, err - } - - arg, err := readN(rd, int(argLen)+2) - if err != nil { - return nil, err - } - args = append(args, string(arg[:argLen])) - } - return args, nil -} - -//------------------------------------------------------------------------------ - -func parseReply(rd reader, p multiBulkParser) (interface{}, error) { - line, err := readLine(rd) - if err != nil { - return nil, err - } - - switch line[0] { - case '-': - return nil, errors.New(string(line[1:])) - case '+': - return string(line[1:]), nil - case ':': - v, err := strconv.ParseInt(string(line[1:]), 10, 64) - if err != nil { - return nil, err - } - return v, nil - case '$': - if len(line) == 3 && line[1] == '-' && line[2] == '1' { - return nil, Nil - } - - replyLenInt32, err := strconv.ParseInt(string(line[1:]), 10, 32) - if err != nil { - return nil, err - } - replyLen := int(replyLenInt32) + 2 - - line, err = readN(rd, replyLen) - if err != nil { - return nil, err - } - return string(line[:len(line)-2]), nil - case '*': - if len(line) == 3 && line[1] == '-' && line[2] == '1' { - return nil, Nil - } - - repliesNum, err := strconv.ParseInt(string(line[1:]), 10, 64) - if err != nil { - return nil, err - } - - return p(rd, repliesNum) - } - return nil, fmt.Errorf("redis: can't parse %q", line) -} - -func parseSlice(rd reader, n int64) (interface{}, error) { - vals := make([]interface{}, 0, n) - for i := int64(0); i < n; i++ { - v, err := parseReply(rd, parseSlice) - if err == Nil { - vals = append(vals, nil) - } else if err != nil { - return nil, err - } else { - vals = append(vals, v) - } - } - return vals, nil -} - -func parseStringSlice(rd reader, n int64) (interface{}, error) { - vals := make([]string, 0, n) - for i := int64(0); i < n; i++ { - vi, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - if v, ok := vi.(string); ok { - vals = append(vals, v) - } else { - return nil, errInvalidReplyType - } - } - return vals, nil -} - -func parseBoolSlice(rd reader, n int64) (interface{}, error) { - vals := make([]bool, 0, n) - for i := int64(0); i < n; i++ { - vi, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - if v, ok := vi.(int64); ok { - vals = append(vals, v == 1) - } else { - return nil, errInvalidReplyType - } - } - return vals, nil -} - -func parseStringStringMap(rd reader, n int64) (interface{}, error) { - m := make(map[string]string, n/2) - for i := int64(0); i < n; i += 2 { - keyI, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - key, ok := keyI.(string) - if !ok { - return nil, errInvalidReplyType - } - - valueI, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - value, ok := valueI.(string) - if !ok { - return nil, errInvalidReplyType - } - - m[key] = value - } - return m, nil -} - -func parseStringFloatMap(rd reader, n int64) (interface{}, error) { - m := make(map[string]float64, n/2) - for i := int64(0); i < n; i += 2 { - keyI, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - key, ok := keyI.(string) - if !ok { - return nil, errInvalidReplyType - } - - valueI, err := parseReply(rd, nil) - if err != nil { - return nil, err - } - valueS, ok := valueI.(string) - if !ok { - return nil, errInvalidReplyType - } - value, err := strconv.ParseFloat(valueS, 64) - if err != nil { - return nil, err - } - - m[key] = value - } - return m, nil -} diff --git a/v2/pipeline.go b/v2/pipeline.go deleted file mode 100644 index 6d436d2..0000000 --- a/v2/pipeline.go +++ /dev/null @@ -1,90 +0,0 @@ -package redis - -// Not thread-safe. -type Pipeline struct { - *Client - - closed bool -} - -func (c *Client) Pipeline() *Pipeline { - return &Pipeline{ - Client: &Client{ - baseClient: &baseClient{ - opt: c.opt, - connPool: c.connPool, - - cmds: make([]Cmder, 0), - }, - }, - } -} - -func (c *Client) Pipelined(f func(*Pipeline)) ([]Cmder, error) { - pc := c.Pipeline() - f(pc) - cmds, err := pc.Exec() - pc.Close() - return cmds, err -} - -func (c *Pipeline) Close() error { - c.closed = true - return nil -} - -func (c *Pipeline) Discard() error { - if c.closed { - return errClosed - } - c.cmds = c.cmds[:0] - return nil -} - -// Exec always returns list of commands and error of the first failed -// command if any. -func (c *Pipeline) Exec() ([]Cmder, error) { - if c.closed { - return nil, errClosed - } - - cmds := c.cmds - c.cmds = make([]Cmder, 0) - - if len(cmds) == 0 { - return []Cmder{}, nil - } - - cn, err := c.conn() - if err != nil { - setCmdsErr(cmds, err) - return cmds, err - } - - if err := c.execCmds(cn, cmds); err != nil { - c.freeConn(cn, err) - return cmds, err - } - - c.putConn(cn) - return cmds, nil -} - -func (c *Pipeline) execCmds(cn *conn, cmds []Cmder) error { - err := c.writeCmd(cn, cmds...) - if err != nil { - setCmdsErr(cmds, err) - return err - } - - var firstCmdErr error - for _, cmd := range cmds { - if err := cmd.parseReply(cn.rd); err != nil { - if firstCmdErr == nil { - firstCmdErr = err - } - } - } - - return firstCmdErr -} diff --git a/v2/pubsub.go b/v2/pubsub.go deleted file mode 100644 index cc8d7e0..0000000 --- a/v2/pubsub.go +++ /dev/null @@ -1,122 +0,0 @@ -package redis - -import ( - "fmt" - "time" -) - -// Not thread-safe. -type PubSub struct { - *baseClient -} - -func (c *Client) PubSub() *PubSub { - return &PubSub{ - baseClient: &baseClient{ - opt: c.opt, - connPool: newSingleConnPool(c.connPool, nil, false), - }, - } -} - -func (c *Client) Publish(channel, message string) *IntCmd { - req := NewIntCmd("PUBLISH", channel, message) - c.Process(req) - return req -} - -type Message struct { - Channel string - Payload string -} - -type PMessage struct { - Channel string - Pattern string - Payload string -} - -type Subscription struct { - Kind string - Channel string - Count int -} - -func (c *PubSub) Receive() (interface{}, error) { - return c.ReceiveTimeout(0) -} - -func (c *PubSub) ReceiveTimeout(timeout time.Duration) (interface{}, error) { - cn, err := c.conn() - if err != nil { - return nil, err - } - cn.readTimeout = timeout - - cmd := NewSliceCmd() - if err := cmd.parseReply(cn.rd); err != nil { - return nil, err - } - - reply := cmd.Val() - - msgName := reply[0].(string) - switch msgName { - case "subscribe", "unsubscribe", "psubscribe", "punsubscribe": - return &Subscription{ - Kind: msgName, - Channel: reply[1].(string), - Count: int(reply[2].(int64)), - }, nil - case "message": - return &Message{ - Channel: reply[1].(string), - Payload: reply[2].(string), - }, nil - case "pmessage": - return &PMessage{ - Pattern: reply[1].(string), - Channel: reply[2].(string), - Payload: reply[3].(string), - }, nil - } - return nil, fmt.Errorf("redis: unsupported message name: %q", msgName) -} - -func (c *PubSub) subscribe(cmd string, channels ...string) error { - cn, err := c.conn() - if err != nil { - return err - } - - args := append([]string{cmd}, channels...) - req := NewSliceCmd(args...) - return c.writeCmd(cn, req) -} - -func (c *PubSub) Subscribe(channels ...string) error { - return c.subscribe("SUBSCRIBE", channels...) -} - -func (c *PubSub) PSubscribe(patterns ...string) error { - return c.subscribe("PSUBSCRIBE", patterns...) -} - -func (c *PubSub) unsubscribe(cmd string, channels ...string) error { - cn, err := c.conn() - if err != nil { - return err - } - - args := append([]string{cmd}, channels...) - req := NewSliceCmd(args...) - return c.writeCmd(cn, req) -} - -func (c *PubSub) Unsubscribe(channels ...string) error { - return c.unsubscribe("UNSUBSCRIBE", channels...) -} - -func (c *PubSub) PUnsubscribe(patterns ...string) error { - return c.unsubscribe("PUNSUBSCRIBE", patterns...) -} diff --git a/v2/redis.go b/v2/redis.go deleted file mode 100644 index 6e945da..0000000 --- a/v2/redis.go +++ /dev/null @@ -1,191 +0,0 @@ -package redis - -import ( - "net" - "time" - - "github.com/golang/glog" -) - -type baseClient struct { - connPool pool - - opt *Options - - cmds []Cmder -} - -func (c *baseClient) writeCmd(cn *conn, cmds ...Cmder) error { - buf := make([]byte, 0, 1000) - for _, cmd := range cmds { - buf = appendCmd(buf, cmd.args()) - } - - _, err := cn.Write(buf) - return err -} - -func (c *baseClient) conn() (*conn, error) { - cn, isNew, err := c.connPool.Get() - if err != nil { - return nil, err - } - - if isNew && (c.opt.Password != "" || c.opt.DB > 0) { - if err = c.init(cn, c.opt.Password, c.opt.DB); err != nil { - c.removeConn(cn) - return nil, err - } - } - - return cn, nil -} - -func (c *baseClient) init(cn *conn, password string, db int64) error { - // Client is not closed on purpose. - client := &Client{ - baseClient: &baseClient{ - opt: c.opt, - connPool: newSingleConnPool(c.connPool, cn, false), - }, - } - - if password != "" { - auth := client.Auth(password) - if auth.Err() != nil { - return auth.Err() - } - } - - if db > 0 { - sel := client.Select(db) - if sel.Err() != nil { - return sel.Err() - } - } - - return nil -} - -func (c *baseClient) freeConn(cn *conn, err error) { - if err == Nil || err == TxFailedErr { - c.putConn(cn) - } else { - c.removeConn(cn) - } -} - -func (c *baseClient) removeConn(cn *conn) { - if err := c.connPool.Remove(cn); err != nil { - glog.Errorf("pool.Remove failed: %s", err) - } -} - -func (c *baseClient) putConn(cn *conn) { - if err := c.connPool.Put(cn); err != nil { - glog.Errorf("pool.Put failed: %s", err) - } -} - -func (c *baseClient) Process(cmd Cmder) { - if c.cmds == nil { - c.run(cmd) - } else { - c.cmds = append(c.cmds, cmd) - } -} - -func (c *baseClient) run(cmd Cmder) { - cn, err := c.conn() - if err != nil { - cmd.setErr(err) - return - } - - cn.writeTimeout = c.opt.WriteTimeout - if timeout := cmd.writeTimeout(); timeout != nil { - cn.writeTimeout = *timeout - } - - cn.readTimeout = c.opt.ReadTimeout - if timeout := cmd.readTimeout(); timeout != nil { - cn.readTimeout = *timeout - } - - if err := c.writeCmd(cn, cmd); err != nil { - c.freeConn(cn, err) - cmd.setErr(err) - return - } - - if err := cmd.parseReply(cn.rd); err != nil { - c.freeConn(cn, err) - return - } - - c.putConn(cn) -} - -// Close closes the client, releasing any open resources. -func (c *baseClient) Close() error { - return c.connPool.Close() -} - -//------------------------------------------------------------------------------ - -type Options struct { - Addr string - Password string - DB int64 - - PoolSize int - - DialTimeout time.Duration - ReadTimeout time.Duration - WriteTimeout time.Duration - IdleTimeout time.Duration -} - -func (opt *Options) getPoolSize() int { - if opt.PoolSize == 0 { - return 10 - } - return opt.PoolSize -} - -func (opt *Options) getDialTimeout() time.Duration { - if opt.DialTimeout == 0 { - return 5 * time.Second - } - return opt.DialTimeout -} - -//------------------------------------------------------------------------------ - -type Client struct { - *baseClient -} - -func newClient(opt *Options, dial func() (net.Conn, error)) *Client { - return &Client{ - baseClient: &baseClient{ - opt: opt, - - connPool: newConnPool(newConnFunc(dial), opt.getPoolSize(), opt.IdleTimeout), - }, - } -} - -func NewTCPClient(opt *Options) *Client { - dial := func() (net.Conn, error) { - return net.DialTimeout("tcp", opt.Addr, opt.getDialTimeout()) - } - return newClient(opt, dial) -} - -func NewUnixClient(opt *Options) *Client { - dial := func() (net.Conn, error) { - return net.DialTimeout("unix", opt.Addr, opt.getDialTimeout()) - } - return newClient(opt, dial) -} diff --git a/v2/redis_test.go b/v2/redis_test.go deleted file mode 100644 index f19e25b..0000000 --- a/v2/redis_test.go +++ /dev/null @@ -1,3136 +0,0 @@ -package redis_test - -import ( - "bytes" - "fmt" - "io" - "net" - "sort" - "strconv" - "sync" - "testing" - "time" - - "github.com/vmihailenco/redis/v2" - - . "launchpad.net/gocheck" -) - -const redisAddr = ":6379" - -//------------------------------------------------------------------------------ - -func sortStrings(slice []string) []string { - sort.Strings(slice) - return slice -} - -//------------------------------------------------------------------------------ - -type RedisConnectorTest struct{} - -var _ = Suite(&RedisConnectorTest{}) - -func (t *RedisConnectorTest) TestShutdown(c *C) { - c.Skip("shutdowns server") - - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - - shutdown := client.Shutdown() - c.Check(shutdown.Err(), Equals, io.EOF) - c.Check(shutdown.Val(), Equals, "") - - ping := client.Ping() - c.Check(ping.Err(), ErrorMatches, "dial tcp :[0-9]+: connection refused") - c.Check(ping.Val(), Equals, "") -} - -func (t *RedisConnectorTest) TestNewTCPClient(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - ping := client.Ping() - c.Check(ping.Err(), IsNil) - c.Check(ping.Val(), Equals, "PONG") - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestNewUnixClient(c *C) { - c.Skip("not available on Travis CI") - - client := redis.NewUnixClient(&redis.Options{ - Addr: "/tmp/redis.sock", - }) - ping := client.Ping() - c.Check(ping.Err(), IsNil) - c.Check(ping.Val(), Equals, "PONG") - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestClose(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - c.Assert(client.Close(), IsNil) - - ping := client.Ping() - c.Assert(ping.Err(), Not(IsNil)) - c.Assert(ping.Err().Error(), Equals, "redis: client is closed") - - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestPubSubClose(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - - pubsub := client.PubSub() - c.Assert(pubsub.Close(), IsNil) - - _, err := pubsub.Receive() - c.Assert(err, Not(IsNil)) - c.Assert(err.Error(), Equals, "redis: client is closed") - - ping := client.Ping() - c.Assert(ping.Err(), IsNil) - - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestMultiClose(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - - multi := client.Multi() - c.Assert(multi.Close(), IsNil) - - _, err := multi.Exec(func() { - multi.Ping() - }) - c.Assert(err, Not(IsNil)) - c.Assert(err.Error(), Equals, "redis: client is closed") - - ping := client.Ping() - c.Assert(ping.Err(), IsNil) - - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestPipelineClose(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) - - _, err := client.Pipelined(func(pipeline *redis.Pipeline) { - c.Assert(pipeline.Close(), IsNil) - pipeline.Ping() - }) - c.Assert(err, Not(IsNil)) - c.Assert(err.Error(), Equals, "redis: client is closed") - - ping := client.Ping() - c.Assert(ping.Err(), IsNil) - - c.Assert(client.Close(), IsNil) -} - -func (t *RedisConnectorTest) TestIdleTimeout(c *C) { - client := redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - IdleTimeout: time.Nanosecond, - }) - for i := 0; i < 10; i++ { - c.Assert(client.Ping().Err(), IsNil) - } -} - -//------------------------------------------------------------------------------ - -type RedisConnPoolTest struct { - client *redis.Client -} - -var _ = Suite(&RedisConnPoolTest{}) - -func (t *RedisConnPoolTest) SetUpTest(c *C) { - t.client = redis.NewTCPClient(&redis.Options{ - Addr: redisAddr, - }) -} - -func (t *RedisConnPoolTest) TearDownTest(c *C) { - c.Assert(t.client.FlushDb().Err(), IsNil) - c.Assert(t.client.Close(), IsNil) -} - -func (t *RedisConnPoolTest) TestConnPoolMaxSize(c *C) { - wg := &sync.WaitGroup{} - for i := 0; i < 1000; i++ { - wg.Add(1) - go func() { - ping := t.client.Ping() - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") - wg.Done() - }() - } - wg.Wait() - - c.Assert(t.client.Pool().Size(), Equals, 10) - c.Assert(t.client.Pool().Len(), Equals, 10) -} - -func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnPipelineClient(c *C) { - const N = 1000 - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - go func() { - pipeline := t.client.Pipeline() - ping := pipeline.Ping() - cmds, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 1) - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") - - c.Assert(pipeline.Close(), IsNil) - - wg.Done() - }() - } - wg.Wait() - - c.Assert(t.client.Pool().Size(), Equals, 10) - c.Assert(t.client.Pool().Len(), Equals, 10) -} - -func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnMultiClient(c *C) { - const N = 1000 - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - go func() { - multi := t.client.Multi() - var ping *redis.StatusCmd - cmds, err := multi.Exec(func() { - ping = multi.Ping() - }) - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 1) - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") - - c.Assert(multi.Close(), IsNil) - - wg.Done() - }() - } - wg.Wait() - - c.Assert(t.client.Pool().Size(), Equals, 10) - c.Assert(t.client.Pool().Len(), Equals, 10) -} - -func (t *RedisConnPoolTest) TestConnPoolMaxSizeOnPubSub(c *C) { - const N = 1000 - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - go func() { - pubsub := t.client.PubSub() - c.Assert(pubsub.Subscribe(), IsNil) - c.Assert(pubsub.Close(), IsNil) - wg.Done() - }() - } - wg.Wait() - - c.Assert(t.client.Pool().Size(), Equals, 0) - c.Assert(t.client.Pool().Len(), Equals, 0) -} - -func (t *RedisConnPoolTest) TestConnPoolRemovesBrokenConn(c *C) { - cn, _, err := t.client.Pool().Get() - c.Assert(err, IsNil) - c.Assert(cn.Close(), IsNil) - c.Assert(t.client.Pool().Put(cn), IsNil) - - ping := t.client.Ping() - c.Assert(ping.Err().Error(), Equals, "use of closed network connection") - c.Assert(ping.Val(), Equals, "") - - ping = t.client.Ping() - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") - - c.Assert(t.client.Pool().Size(), Equals, 1) - c.Assert(t.client.Pool().Len(), Equals, 1) -} - -func (t *RedisConnPoolTest) TestConnPoolReusesConn(c *C) { - for i := 0; i < 1000; i++ { - ping := t.client.Ping() - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") - } - - c.Assert(t.client.Pool().Size(), Equals, 1) - c.Assert(t.client.Pool().Len(), Equals, 1) -} - -//------------------------------------------------------------------------------ - -type RedisTest struct { - client *redis.Client -} - -var _ = Suite(&RedisTest{}) - -func Test(t *testing.T) { TestingT(t) } - -func (t *RedisTest) SetUpSuite(c *C) { - t.client = redis.NewTCPClient(&redis.Options{ - Addr: ":6379", - }) -} - -func (t *RedisTest) TearDownSuite(c *C) { - c.Assert(t.client.Close(), IsNil) -} - -func (t *RedisTest) SetUpTest(c *C) { - t.resetRedis(c) -} - -func (t *RedisTest) resetRedis(c *C) { - // This is much faster than Flushall. - c.Assert(t.client.Select(1).Err(), IsNil) - c.Assert(t.client.FlushDb().Err(), IsNil) - c.Assert(t.client.Select(0).Err(), IsNil) - c.Assert(t.client.FlushDb().Err(), IsNil) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdStringMethod(c *C) { - set := t.client.Set("foo", "bar") - c.Assert(set.String(), Equals, "SET foo bar: OK") - - get := t.client.Get("foo") - c.Assert(get.String(), Equals, "GET foo: bar") -} - -func (t *RedisTest) TestCmdStringMethodError(c *C) { - get2 := t.client.Get("key_does_not_exists") - c.Assert(get2.String(), Equals, "GET key_does_not_exists: redis: nil") -} - -func (t *RedisTest) TestRunWithouthCheckingErrVal(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") - - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") -} - -func (t *RedisTest) TestGetSpecChars(c *C) { - set := t.client.Set("key", "hello1\r\nhello2\r\n") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello1\r\nhello2\r\n") -} - -func (t *RedisTest) TestGetBigVal(c *C) { - val := string(bytes.Repeat([]byte{'*'}, 1<<16)) - - set := t.client.Set("key", val) - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, val) -} - -func (t *RedisTest) TestManyKeys(c *C) { - for i := 0; i < 100000; i++ { - t.client.Set("keys.key"+strconv.Itoa(i), "hello"+strconv.Itoa(i)) - } - keys := t.client.Keys("keys.*") - c.Assert(keys.Err(), IsNil) - c.Assert(len(keys.Val()), Equals, 100000) -} - -func (t *RedisTest) TestManyKeys2(c *C) { - keys := []string{"non-existent-key"} - for i := 0; i < 100000; i++ { - key := "keys.key" + strconv.Itoa(i) - t.client.Set(key, "hello"+strconv.Itoa(i)) - keys = append(keys, key) - } - keys = append(keys, "non-existent-key") - - mget := t.client.MGet(keys...) - c.Assert(mget.Err(), IsNil) - c.Assert(len(mget.Val()), Equals, 100002) - vals := mget.Val() - for i := 0; i < 100000; i++ { - c.Assert(vals[i+1], Equals, "hello"+strconv.Itoa(i)) - } - c.Assert(vals[0], Equals, nil) - c.Assert(vals[100001], Equals, nil) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestAuth(c *C) { - auth := t.client.Auth("password") - c.Assert(auth.Err(), ErrorMatches, "ERR Client sent AUTH, but no password is set") - c.Assert(auth.Val(), Equals, "") -} - -func (t *RedisTest) TestEcho(c *C) { - echo := t.client.Echo("hello") - c.Assert(echo.Err(), IsNil) - c.Assert(echo.Val(), Equals, "hello") -} - -func (t *RedisTest) TestPing(c *C) { - ping := t.client.Ping() - c.Assert(ping.Err(), IsNil) - c.Assert(ping.Val(), Equals, "PONG") -} - -func (t *RedisTest) TestSelect(c *C) { - sel := t.client.Select(1) - c.Assert(sel.Err(), IsNil) - c.Assert(sel.Val(), Equals, "OK") -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdKeysDel(c *C) { - set := t.client.Set("key1", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - set = t.client.Set("key2", "World") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - del := t.client.Del("key1", "key2", "key3") - c.Assert(del.Err(), IsNil) - c.Assert(del.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestCmdKeysDump(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - dump := t.client.Dump("key") - c.Assert(dump.Err(), IsNil) - c.Assert(dump.Val(), Equals, "\x00\x05hello\x06\x00\xf5\x9f\xb7\xf6\x90a\x1c\x99") -} - -func (t *RedisTest) TestCmdKeysExists(c *C) { - set := t.client.Set("key1", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - exists := t.client.Exists("key1") - c.Assert(exists.Err(), IsNil) - c.Assert(exists.Val(), Equals, true) - - exists = t.client.Exists("key2") - c.Assert(exists.Err(), IsNil) - c.Assert(exists.Val(), Equals, false) -} - -func (t *RedisTest) TestCmdKeysExpire(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expire := t.client.Expire("key", 10*time.Second) - c.Assert(expire.Err(), IsNil) - c.Assert(expire.Val(), Equals, true) - - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, 10*time.Second) - - set = t.client.Set("key", "Hello World") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - ttl = t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val() < 0, Equals, true) -} - -func (t *RedisTest) TestCmdKeysExpireAt(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - exists := t.client.Exists("key") - c.Assert(exists.Err(), IsNil) - c.Assert(exists.Val(), Equals, true) - - expireAt := t.client.ExpireAt("key", time.Now().Add(-time.Hour)) - c.Assert(expireAt.Err(), IsNil) - c.Assert(expireAt.Val(), Equals, true) - - exists = t.client.Exists("key") - c.Assert(exists.Err(), IsNil) - c.Assert(exists.Val(), Equals, false) -} - -func (t *RedisTest) TestCmdKeysKeys(c *C) { - mset := t.client.MSet("one", "1", "two", "2", "three", "3", "four", "4") - c.Assert(mset.Err(), IsNil) - c.Assert(mset.Val(), Equals, "OK") - - keys := t.client.Keys("*o*") - c.Assert(keys.Err(), IsNil) - c.Assert(sortStrings(keys.Val()), DeepEquals, []string{"four", "one", "two"}) - - keys = t.client.Keys("t??") - c.Assert(keys.Err(), IsNil) - c.Assert(keys.Val(), DeepEquals, []string{"two"}) - - keys = t.client.Keys("*") - c.Assert(keys.Err(), IsNil) - c.Assert( - sortStrings(keys.Val()), - DeepEquals, - []string{"four", "one", "three", "two"}, - ) -} - -func (t *RedisTest) TestCmdKeysMigrate(c *C) { - migrate := t.client.Migrate("localhost", "6380", "key", 0, 0) - c.Assert(migrate.Err(), IsNil) - c.Assert(migrate.Val(), Equals, "NOKEY") - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - migrate = t.client.Migrate("localhost", "6380", "key", 0, 0) - c.Assert(migrate.Err(), ErrorMatches, "IOERR error or timeout writing to target instance") - c.Assert(migrate.Val(), Equals, "") -} - -func (t *RedisTest) TestCmdKeysMove(c *C) { - move := t.client.Move("key", 1) - c.Assert(move.Err(), IsNil) - c.Assert(move.Val(), Equals, false) - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - move = t.client.Move("key", 1) - c.Assert(move.Err(), IsNil) - c.Assert(move.Val(), Equals, true) - - get := t.client.Get("key") - c.Assert(get.Err(), Equals, redis.Nil) - c.Assert(get.Val(), Equals, "") - - sel := t.client.Select(1) - c.Assert(sel.Err(), IsNil) - c.Assert(sel.Val(), Equals, "OK") - - get = t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdKeysObject(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - refCount := t.client.ObjectRefCount("key") - c.Assert(refCount.Err(), IsNil) - c.Assert(refCount.Val(), Equals, int64(1)) - - enc := t.client.ObjectEncoding("key") - c.Assert(enc.Err(), IsNil) - c.Assert(enc.Val(), Equals, "raw") - - idleTime := t.client.ObjectIdleTime("key") - c.Assert(idleTime.Err(), IsNil) - c.Assert(idleTime.Val(), Equals, time.Duration(0)) -} - -func (t *RedisTest) TestCmdKeysPersist(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expire := t.client.Expire("key", 10*time.Second) - c.Assert(expire.Err(), IsNil) - c.Assert(expire.Val(), Equals, true) - - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, 10*time.Second) - - persist := t.client.Persist("key") - c.Assert(persist.Err(), IsNil) - c.Assert(persist.Val(), Equals, true) - - ttl = t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val() < 0, Equals, true) -} - -func (t *RedisTest) TestCmdKeysPExpire(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expiration := 900 * time.Millisecond - pexpire := t.client.PExpire("key", expiration) - c.Assert(pexpire.Err(), IsNil) - c.Assert(pexpire.Val(), Equals, true) - - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, time.Second) - - pttl := t.client.PTTL("key") - c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() <= expiration, Equals, true) - c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) -} - -func (t *RedisTest) TestCmdKeysPExpireAt(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expiration := 900 * time.Millisecond - pexpireat := t.client.PExpireAt("key", time.Now().Add(expiration)) - c.Assert(pexpireat.Err(), IsNil) - c.Assert(pexpireat.Val(), Equals, true) - - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, time.Second) - - pttl := t.client.PTTL("key") - c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() <= expiration, Equals, true) - c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) -} - -func (t *RedisTest) TestCmdKeysPTTL(c *C) { - set := t.client.Set("key", "Hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expiration := time.Second - expire := t.client.Expire("key", expiration) - c.Assert(expire.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - pttl := t.client.PTTL("key") - c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() <= expiration, Equals, true) - c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) -} - -func (t *RedisTest) TestCmdKeysRandomKey(c *C) { - randomKey := t.client.RandomKey() - c.Assert(randomKey.Err(), Equals, redis.Nil) - c.Assert(randomKey.Val(), Equals, "") - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - randomKey = t.client.RandomKey() - c.Assert(randomKey.Err(), IsNil) - c.Assert(randomKey.Val(), Equals, "key") -} - -func (t *RedisTest) TestCmdKeysRename(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - status := t.client.Rename("key", "key1") - c.Assert(status.Err(), IsNil) - c.Assert(status.Val(), Equals, "OK") - - get := t.client.Get("key1") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdKeysRenameNX(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - renameNX := t.client.RenameNX("key", "key1") - c.Assert(renameNX.Err(), IsNil) - c.Assert(renameNX.Val(), Equals, true) - - get := t.client.Get("key1") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdKeysRestore(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - dump := t.client.Dump("key") - c.Assert(dump.Err(), IsNil) - - del := t.client.Del("key") - c.Assert(del.Err(), IsNil) - - restore := t.client.Restore("key", 0, dump.Val()) - c.Assert(restore.Err(), IsNil) - c.Assert(restore.Val(), Equals, "OK") - - type_ := t.client.Type("key") - c.Assert(type_.Err(), IsNil) - c.Assert(type_.Val(), Equals, "string") - - lRange := t.client.Get("key") - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdKeysSort(c *C) { - lPush := t.client.LPush("list", "1") - c.Assert(lPush.Err(), IsNil) - c.Assert(lPush.Val(), Equals, int64(1)) - lPush = t.client.LPush("list", "3") - c.Assert(lPush.Err(), IsNil) - c.Assert(lPush.Val(), Equals, int64(2)) - lPush = t.client.LPush("list", "2") - c.Assert(lPush.Err(), IsNil) - c.Assert(lPush.Val(), Equals, int64(3)) - - sort := t.client.Sort("list", redis.Sort{Offset: 0, Count: 2, Order: "ASC"}) - c.Assert(sort.Err(), IsNil) - c.Assert(sort.Val(), DeepEquals, []string{"1", "2"}) -} - -func (t *RedisTest) TestCmdKeysTTL(c *C) { - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val() < 0, Equals, true) - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - expire := t.client.Expire("key", 60*time.Second) - c.Assert(expire.Err(), IsNil) - c.Assert(expire.Val(), Equals, true) - - ttl = t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, 60*time.Second) -} - -func (t *RedisTest) TestCmdKeysType(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - type_ := t.client.Type("key") - c.Assert(type_.Err(), IsNil) - c.Assert(type_.Val(), Equals, "string") -} - -func (t *RedisTest) TestCmdScan(c *C) { - for i := 0; i < 1000; i++ { - set := t.client.Set(fmt.Sprintf("key%d", i), "hello") - c.Assert(set.Err(), IsNil) - } - - cursor, keys, err := t.client.Scan(0, "", 0).Result() - c.Assert(err, IsNil) - c.Assert(cursor > 0, Equals, true) - c.Assert(len(keys) > 0, Equals, true) -} - -func (t *RedisTest) TestCmdSScan(c *C) { - for i := 0; i < 1000; i++ { - sadd := t.client.SAdd("myset", fmt.Sprintf("member%d", i)) - c.Assert(sadd.Err(), IsNil) - } - - cursor, keys, err := t.client.SScan("myset", 0, "", 0).Result() - c.Assert(err, IsNil) - c.Assert(cursor > 0, Equals, true) - c.Assert(len(keys) > 0, Equals, true) -} - -func (t *RedisTest) TestCmdHScan(c *C) { - for i := 0; i < 1000; i++ { - sadd := t.client.HSet("myhash", fmt.Sprintf("key%d", i), "hello") - c.Assert(sadd.Err(), IsNil) - } - - cursor, keys, err := t.client.HScan("myhash", 0, "", 0).Result() - c.Assert(err, IsNil) - c.Assert(cursor > 0, Equals, true) - c.Assert(len(keys) > 0, Equals, true) -} - -func (t *RedisTest) TestCmdZScan(c *C) { - for i := 0; i < 1000; i++ { - sadd := t.client.ZAdd("myset", redis.Z{float64(i), fmt.Sprintf("member%d", i)}) - c.Assert(sadd.Err(), IsNil) - } - - cursor, keys, err := t.client.ZScan("myset", 0, "", 0).Result() - c.Assert(err, IsNil) - c.Assert(cursor > 0, Equals, true) - c.Assert(len(keys) > 0, Equals, true) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestStringsAppend(c *C) { - exists := t.client.Exists("key") - c.Assert(exists.Err(), IsNil) - c.Assert(exists.Val(), Equals, false) - - append := t.client.Append("key", "Hello") - c.Assert(append.Err(), IsNil) - c.Assert(append.Val(), Equals, int64(5)) - - append = t.client.Append("key", " World") - c.Assert(append.Err(), IsNil) - c.Assert(append.Val(), Equals, int64(11)) - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "Hello World") -} - -func (t *RedisTest) TestStringsBitCount(c *C) { - set := t.client.Set("key", "foobar") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - bitCount := t.client.BitCount("key", nil) - c.Assert(bitCount.Err(), IsNil) - c.Assert(bitCount.Val(), Equals, int64(26)) - - bitCount = t.client.BitCount("key", &redis.BitCount{0, 0}) - c.Assert(bitCount.Err(), IsNil) - c.Assert(bitCount.Val(), Equals, int64(4)) - - bitCount = t.client.BitCount("key", &redis.BitCount{1, 1}) - c.Assert(bitCount.Err(), IsNil) - c.Assert(bitCount.Val(), Equals, int64(6)) -} - -func (t *RedisTest) TestStringsBitOpAnd(c *C) { - set := t.client.Set("key1", "1") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - set = t.client.Set("key2", "0") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - bitOpAnd := t.client.BitOpAnd("dest", "key1", "key2") - c.Assert(bitOpAnd.Err(), IsNil) - c.Assert(bitOpAnd.Val(), Equals, int64(1)) - - get := t.client.Get("dest") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "0") -} - -func (t *RedisTest) TestStringsBitOpOr(c *C) { - set := t.client.Set("key1", "1") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - set = t.client.Set("key2", "0") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - bitOpOr := t.client.BitOpOr("dest", "key1", "key2") - c.Assert(bitOpOr.Err(), IsNil) - c.Assert(bitOpOr.Val(), Equals, int64(1)) - - get := t.client.Get("dest") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "1") -} - -func (t *RedisTest) TestStringsBitOpXor(c *C) { - set := t.client.Set("key1", "\xff") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - set = t.client.Set("key2", "\x0f") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - bitOpXor := t.client.BitOpXor("dest", "key1", "key2") - c.Assert(bitOpXor.Err(), IsNil) - c.Assert(bitOpXor.Val(), Equals, int64(1)) - - get := t.client.Get("dest") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "\xf0") -} - -func (t *RedisTest) TestStringsBitOpNot(c *C) { - set := t.client.Set("key1", "\x00") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - bitOpNot := t.client.BitOpNot("dest", "key1") - c.Assert(bitOpNot.Err(), IsNil) - c.Assert(bitOpNot.Val(), Equals, int64(1)) - - get := t.client.Get("dest") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "\xff") -} - -func (t *RedisTest) TestStringsDecr(c *C) { - set := t.client.Set("key", "10") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - decr := t.client.Decr("key") - c.Assert(decr.Err(), IsNil) - c.Assert(decr.Val(), Equals, int64(9)) - - set = t.client.Set("key", "234293482390480948029348230948") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - decr = t.client.Decr("key") - c.Assert(decr.Err(), ErrorMatches, "ERR value is not an integer or out of range") - c.Assert(decr.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestStringsDecrBy(c *C) { - set := t.client.Set("key", "10") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - decrBy := t.client.DecrBy("key", 5) - c.Assert(decrBy.Err(), IsNil) - c.Assert(decrBy.Val(), Equals, int64(5)) -} - -func (t *RedisTest) TestStringsGet(c *C) { - get := t.client.Get("_") - c.Assert(get.Err(), Equals, redis.Nil) - c.Assert(get.Val(), Equals, "") - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - get = t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestStringsGetBit(c *C) { - setBit := t.client.SetBit("key", 7, 1) - c.Assert(setBit.Err(), IsNil) - c.Assert(setBit.Val(), Equals, int64(0)) - - getBit := t.client.GetBit("key", 0) - c.Assert(getBit.Err(), IsNil) - c.Assert(getBit.Val(), Equals, int64(0)) - - getBit = t.client.GetBit("key", 7) - c.Assert(getBit.Err(), IsNil) - c.Assert(getBit.Val(), Equals, int64(1)) - - getBit = t.client.GetBit("key", 100) - c.Assert(getBit.Err(), IsNil) - c.Assert(getBit.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestStringsGetRange(c *C) { - set := t.client.Set("key", "This is a string") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - getRange := t.client.GetRange("key", 0, 3) - c.Assert(getRange.Err(), IsNil) - c.Assert(getRange.Val(), Equals, "This") - - getRange = t.client.GetRange("key", -3, -1) - c.Assert(getRange.Err(), IsNil) - c.Assert(getRange.Val(), Equals, "ing") - - getRange = t.client.GetRange("key", 0, -1) - c.Assert(getRange.Err(), IsNil) - c.Assert(getRange.Val(), Equals, "This is a string") - - getRange = t.client.GetRange("key", 10, 100) - c.Assert(getRange.Err(), IsNil) - c.Assert(getRange.Val(), Equals, "string") -} - -func (t *RedisTest) TestStringsGetSet(c *C) { - incr := t.client.Incr("key") - c.Assert(incr.Err(), IsNil) - c.Assert(incr.Val(), Equals, int64(1)) - - getSet := t.client.GetSet("key", "0") - c.Assert(getSet.Err(), IsNil) - c.Assert(getSet.Val(), Equals, "1") - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "0") -} - -func (t *RedisTest) TestStringsIncr(c *C) { - set := t.client.Set("key", "10") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - incr := t.client.Incr("key") - c.Assert(incr.Err(), IsNil) - c.Assert(incr.Val(), Equals, int64(11)) - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "11") -} - -func (t *RedisTest) TestStringsIncrBy(c *C) { - set := t.client.Set("key", "10") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - incrBy := t.client.IncrBy("key", 5) - c.Assert(incrBy.Err(), IsNil) - c.Assert(incrBy.Val(), Equals, int64(15)) -} - -func (t *RedisTest) TestIncrByFloat(c *C) { - set := t.client.Set("key", "10.50") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - incrByFloat := t.client.IncrByFloat("key", 0.1) - c.Assert(incrByFloat.Err(), IsNil) - c.Assert(incrByFloat.Val(), Equals, 10.6) - - set = t.client.Set("key", "5.0e3") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - incrByFloat = t.client.IncrByFloat("key", 2.0e2) - c.Assert(incrByFloat.Err(), IsNil) - c.Assert(incrByFloat.Val(), Equals, float64(5200)) -} - -func (t *RedisTest) TestIncrByFloatOverflow(c *C) { - incrByFloat := t.client.IncrByFloat("key", 996945661) - c.Assert(incrByFloat.Err(), IsNil) - c.Assert(incrByFloat.Val(), Equals, float64(996945661)) -} - -func (t *RedisTest) TestStringsMSetMGet(c *C) { - mSet := t.client.MSet("key1", "hello1", "key2", "hello2") - c.Assert(mSet.Err(), IsNil) - c.Assert(mSet.Val(), Equals, "OK") - - mGet := t.client.MGet("key1", "key2", "_") - c.Assert(mGet.Err(), IsNil) - c.Assert(mGet.Val(), DeepEquals, []interface{}{"hello1", "hello2", nil}) -} - -func (t *RedisTest) TestStringsMSetNX(c *C) { - mSetNX := t.client.MSetNX("key1", "hello1", "key2", "hello2") - c.Assert(mSetNX.Err(), IsNil) - c.Assert(mSetNX.Val(), Equals, true) - - mSetNX = t.client.MSetNX("key2", "hello1", "key3", "hello2") - c.Assert(mSetNX.Err(), IsNil) - c.Assert(mSetNX.Val(), Equals, false) -} - -func (t *RedisTest) TestStringsPSetEx(c *C) { - expiration := 50 * time.Millisecond - psetex := t.client.PSetEx("key", expiration, "hello") - c.Assert(psetex.Err(), IsNil) - c.Assert(psetex.Val(), Equals, "OK") - - pttl := t.client.PTTL("key") - c.Assert(pttl.Err(), IsNil) - c.Assert(pttl.Val() <= expiration, Equals, true) - c.Assert(pttl.Val() >= expiration-time.Millisecond, Equals, true) - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestStringsSetGet(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestStringsSetEx(c *C) { - setEx := t.client.SetEx("key", 10*time.Second, "hello") - c.Assert(setEx.Err(), IsNil) - c.Assert(setEx.Val(), Equals, "OK") - - ttl := t.client.TTL("key") - c.Assert(ttl.Err(), IsNil) - c.Assert(ttl.Val(), Equals, 10*time.Second) -} - -func (t *RedisTest) TestStringsSetNX(c *C) { - setNX := t.client.SetNX("key", "hello") - c.Assert(setNX.Err(), IsNil) - c.Assert(setNX.Val(), Equals, true) - - setNX = t.client.SetNX("key", "hello2") - c.Assert(setNX.Err(), IsNil) - c.Assert(setNX.Val(), Equals, false) - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestStringsSetRange(c *C) { - set := t.client.Set("key", "Hello World") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - range_ := t.client.SetRange("key", 6, "Redis") - c.Assert(range_.Err(), IsNil) - c.Assert(range_.Val(), Equals, int64(11)) - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "Hello Redis") -} - -func (t *RedisTest) TestStringsStrLen(c *C) { - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - strLen := t.client.StrLen("key") - c.Assert(strLen.Err(), IsNil) - c.Assert(strLen.Val(), Equals, int64(5)) - - strLen = t.client.StrLen("_") - c.Assert(strLen.Err(), IsNil) - c.Assert(strLen.Val(), Equals, int64(0)) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdHDel(c *C) { - hSet := t.client.HSet("hash", "key", "hello") - c.Assert(hSet.Err(), IsNil) - - hDel := t.client.HDel("hash", "key") - c.Assert(hDel.Err(), IsNil) - c.Assert(hDel.Val(), Equals, int64(1)) - - hDel = t.client.HDel("hash", "key") - c.Assert(hDel.Err(), IsNil) - c.Assert(hDel.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestCmdHExists(c *C) { - hSet := t.client.HSet("hash", "key", "hello") - c.Assert(hSet.Err(), IsNil) - - hExists := t.client.HExists("hash", "key") - c.Assert(hExists.Err(), IsNil) - c.Assert(hExists.Val(), Equals, true) - - hExists = t.client.HExists("hash", "key1") - c.Assert(hExists.Err(), IsNil) - c.Assert(hExists.Val(), Equals, false) -} - -func (t *RedisTest) TestCmdHGet(c *C) { - hSet := t.client.HSet("hash", "key", "hello") - c.Assert(hSet.Err(), IsNil) - - hGet := t.client.HGet("hash", "key") - c.Assert(hGet.Err(), IsNil) - c.Assert(hGet.Val(), Equals, "hello") - - hGet = t.client.HGet("hash", "key1") - c.Assert(hGet.Err(), Equals, redis.Nil) - c.Assert(hGet.Val(), Equals, "") -} - -func (t *RedisTest) TestCmdHGetAll(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) - - hGetAll := t.client.HGetAll("hash") - c.Assert(hGetAll.Err(), IsNil) - c.Assert(hGetAll.Val(), DeepEquals, []string{"key1", "hello1", "key2", "hello2"}) -} - -func (t *RedisTest) TestCmdHGetAllMap(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) - - hGetAll := t.client.HGetAllMap("hash") - c.Assert(hGetAll.Err(), IsNil) - c.Assert(hGetAll.Val(), DeepEquals, map[string]string{"key1": "hello1", "key2": "hello2"}) -} - -func (t *RedisTest) TestCmdHIncrBy(c *C) { - hSet := t.client.HSet("hash", "key", "5") - c.Assert(hSet.Err(), IsNil) - - hIncrBy := t.client.HIncrBy("hash", "key", 1) - c.Assert(hIncrBy.Err(), IsNil) - c.Assert(hIncrBy.Val(), Equals, int64(6)) - - hIncrBy = t.client.HIncrBy("hash", "key", -1) - c.Assert(hIncrBy.Err(), IsNil) - c.Assert(hIncrBy.Val(), Equals, int64(5)) - - hIncrBy = t.client.HIncrBy("hash", "key", -10) - c.Assert(hIncrBy.Err(), IsNil) - c.Assert(hIncrBy.Val(), Equals, int64(-5)) -} - -func (t *RedisTest) TestCmdHIncrByFloat(c *C) { - hSet := t.client.HSet("hash", "field", "10.50") - c.Assert(hSet.Err(), IsNil) - c.Assert(hSet.Val(), Equals, true) - - hIncrByFloat := t.client.HIncrByFloat("hash", "field", 0.1) - c.Assert(hIncrByFloat.Err(), IsNil) - c.Assert(hIncrByFloat.Val(), Equals, 10.6) - - hSet = t.client.HSet("hash", "field", "5.0e3") - c.Assert(hSet.Err(), IsNil) - c.Assert(hSet.Val(), Equals, false) - - hIncrByFloat = t.client.HIncrByFloat("hash", "field", 2.0e2) - c.Assert(hIncrByFloat.Err(), IsNil) - c.Assert(hIncrByFloat.Val(), Equals, float64(5200)) -} - -func (t *RedisTest) TestCmdHKeys(c *C) { - hkeys := t.client.HKeys("hash") - c.Assert(hkeys.Err(), IsNil) - c.Assert(hkeys.Val(), DeepEquals, []string{}) - - hset := t.client.HSet("hash", "key1", "hello1") - c.Assert(hset.Err(), IsNil) - hset = t.client.HSet("hash", "key2", "hello2") - c.Assert(hset.Err(), IsNil) - - hkeys = t.client.HKeys("hash") - c.Assert(hkeys.Err(), IsNil) - c.Assert(hkeys.Val(), DeepEquals, []string{"key1", "key2"}) -} - -func (t *RedisTest) TestCmdHLen(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) - - hLen := t.client.HLen("hash") - c.Assert(hLen.Err(), IsNil) - c.Assert(hLen.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestCmdHMGet(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) - - hMGet := t.client.HMGet("hash", "key1", "key2", "_") - c.Assert(hMGet.Err(), IsNil) - c.Assert(hMGet.Val(), DeepEquals, []interface{}{"hello1", "hello2", nil}) -} - -func (t *RedisTest) TestCmdHMSet(c *C) { - hMSet := t.client.HMSet("hash", "key1", "hello1", "key2", "hello2") - c.Assert(hMSet.Err(), IsNil) - c.Assert(hMSet.Val(), Equals, "OK") - - hGet := t.client.HGet("hash", "key1") - c.Assert(hGet.Err(), IsNil) - c.Assert(hGet.Val(), Equals, "hello1") - - hGet = t.client.HGet("hash", "key2") - c.Assert(hGet.Err(), IsNil) - c.Assert(hGet.Val(), Equals, "hello2") -} - -func (t *RedisTest) TestCmdHSet(c *C) { - hSet := t.client.HSet("hash", "key", "hello") - c.Assert(hSet.Err(), IsNil) - c.Assert(hSet.Val(), Equals, true) - - hGet := t.client.HGet("hash", "key") - c.Assert(hGet.Err(), IsNil) - c.Assert(hGet.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdHSetNX(c *C) { - hSetNX := t.client.HSetNX("hash", "key", "hello") - c.Assert(hSetNX.Err(), IsNil) - c.Assert(hSetNX.Val(), Equals, true) - - hSetNX = t.client.HSetNX("hash", "key", "hello") - c.Assert(hSetNX.Err(), IsNil) - c.Assert(hSetNX.Val(), Equals, false) - - hGet := t.client.HGet("hash", "key") - c.Assert(hGet.Err(), IsNil) - c.Assert(hGet.Val(), Equals, "hello") -} - -func (t *RedisTest) TestCmdHVals(c *C) { - hSet := t.client.HSet("hash", "key1", "hello1") - c.Assert(hSet.Err(), IsNil) - hSet = t.client.HSet("hash", "key2", "hello2") - c.Assert(hSet.Err(), IsNil) - - hVals := t.client.HVals("hash") - c.Assert(hVals.Err(), IsNil) - c.Assert(hVals.Val(), DeepEquals, []string{"hello1", "hello2"}) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdListsBLPop(c *C) { - rPush := t.client.RPush("list1", "a", "b", "c") - c.Assert(rPush.Err(), IsNil) - - bLPop := t.client.BLPop(0, "list1", "list2") - c.Assert(bLPop.Err(), IsNil) - c.Assert(bLPop.Val(), DeepEquals, []string{"list1", "a"}) -} - -func (t *RedisTest) TestCmdListsBLPopBlocks(c *C) { - started := make(chan bool) - done := make(chan bool) - go func() { - started <- true - bLPop := t.client.BLPop(0, "list") - c.Assert(bLPop.Err(), IsNil) - c.Assert(bLPop.Val(), DeepEquals, []string{"list", "a"}) - done <- true - }() - <-started - - select { - case <-done: - c.Error("BLPop is not blocked") - case <-time.After(time.Second): - // ok - } - - rPush := t.client.RPush("list", "a") - c.Assert(rPush.Err(), IsNil) - - select { - case <-done: - // ok - case <-time.After(time.Second): - c.Error("BLPop is still blocked") - // ok - } -} - -func (t *RedisTest) TestCmdListsBLPopTimeout(c *C) { - bLPop := t.client.BLPop(1, "list1") - c.Assert(bLPop.Err(), Equals, redis.Nil) - c.Assert(bLPop.Val(), IsNil) -} - -func (t *RedisTest) TestCmdListsBRPop(c *C) { - rPush := t.client.RPush("list1", "a", "b", "c") - c.Assert(rPush.Err(), IsNil) - - bRPop := t.client.BRPop(0, "list1", "list2") - c.Assert(bRPop.Err(), IsNil) - c.Assert(bRPop.Val(), DeepEquals, []string{"list1", "c"}) -} - -func (t *RedisTest) TestCmdListsBRPopBlocks(c *C) { - started := make(chan bool) - done := make(chan bool) - go func() { - started <- true - brpop := t.client.BRPop(0, "list") - c.Assert(brpop.Err(), IsNil) - c.Assert(brpop.Val(), DeepEquals, []string{"list", "a"}) - done <- true - }() - <-started - - select { - case <-done: - c.Error("BRPop is not blocked") - case <-time.After(time.Second): - // ok - } - - rPush := t.client.RPush("list", "a") - c.Assert(rPush.Err(), IsNil) - - select { - case <-done: - // ok - case <-time.After(time.Second): - c.Error("BRPop is still blocked") - // ok - } -} - -func (t *RedisTest) TestCmdListsBRPopLPush(c *C) { - rPush := t.client.RPush("list1", "a", "b", "c") - c.Assert(rPush.Err(), IsNil) - - bRPopLPush := t.client.BRPopLPush("list1", "list2", 0) - c.Assert(bRPopLPush.Err(), IsNil) - c.Assert(bRPopLPush.Val(), Equals, "c") -} - -func (t *RedisTest) TestCmdListsLIndex(c *C) { - lPush := t.client.LPush("list", "World") - c.Assert(lPush.Err(), IsNil) - lPush = t.client.LPush("list", "Hello") - c.Assert(lPush.Err(), IsNil) - - lIndex := t.client.LIndex("list", 0) - c.Assert(lIndex.Err(), IsNil) - c.Assert(lIndex.Val(), Equals, "Hello") - - lIndex = t.client.LIndex("list", -1) - c.Assert(lIndex.Err(), IsNil) - c.Assert(lIndex.Val(), Equals, "World") - - lIndex = t.client.LIndex("list", 3) - c.Assert(lIndex.Err(), Equals, redis.Nil) - c.Assert(lIndex.Val(), Equals, "") -} - -func (t *RedisTest) TestCmdListsLInsert(c *C) { - rPush := t.client.RPush("list", "Hello") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "World") - c.Assert(rPush.Err(), IsNil) - - lInsert := t.client.LInsert("list", "BEFORE", "World", "There") - c.Assert(lInsert.Err(), IsNil) - c.Assert(lInsert.Val(), Equals, int64(3)) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"Hello", "There", "World"}) -} - -func (t *RedisTest) TestCmdListsLLen(c *C) { - lPush := t.client.LPush("list", "World") - c.Assert(lPush.Err(), IsNil) - lPush = t.client.LPush("list", "Hello") - c.Assert(lPush.Err(), IsNil) - - lLen := t.client.LLen("list") - c.Assert(lLen.Err(), IsNil) - c.Assert(lLen.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestCmdListsLPop(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - lPop := t.client.LPop("list") - c.Assert(lPop.Err(), IsNil) - c.Assert(lPop.Val(), Equals, "one") - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"two", "three"}) -} - -func (t *RedisTest) TestCmdListsLPush(c *C) { - lPush := t.client.LPush("list", "World") - c.Assert(lPush.Err(), IsNil) - lPush = t.client.LPush("list", "Hello") - c.Assert(lPush.Err(), IsNil) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"Hello", "World"}) -} - -func (t *RedisTest) TestCmdListsLPushX(c *C) { - lPush := t.client.LPush("list", "World") - c.Assert(lPush.Err(), IsNil) - - lPushX := t.client.LPushX("list", "Hello") - c.Assert(lPushX.Err(), IsNil) - c.Assert(lPushX.Val(), Equals, int64(2)) - - lPushX = t.client.LPushX("list2", "Hello") - c.Assert(lPushX.Err(), IsNil) - c.Assert(lPushX.Val(), Equals, int64(0)) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"Hello", "World"}) - - lRange = t.client.LRange("list2", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{}) -} - -func (t *RedisTest) TestCmdListsLRange(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - lRange := t.client.LRange("list", 0, 0) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"one"}) - - lRange = t.client.LRange("list", -3, 2) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"one", "two", "three"}) - - lRange = t.client.LRange("list", -100, 100) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"one", "two", "three"}) - - lRange = t.client.LRange("list", 5, 10) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{}) -} - -func (t *RedisTest) TestCmdListsLRem(c *C) { - rPush := t.client.RPush("list", "hello") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "hello") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "key") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "hello") - c.Assert(rPush.Err(), IsNil) - - lRem := t.client.LRem("list", -2, "hello") - c.Assert(lRem.Err(), IsNil) - c.Assert(lRem.Val(), Equals, int64(2)) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"hello", "key"}) -} - -func (t *RedisTest) TestCmdListsLSet(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - lSet := t.client.LSet("list", 0, "four") - c.Assert(lSet.Err(), IsNil) - c.Assert(lSet.Val(), Equals, "OK") - - lSet = t.client.LSet("list", -2, "five") - c.Assert(lSet.Err(), IsNil) - c.Assert(lSet.Val(), Equals, "OK") - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"four", "five", "three"}) -} - -func (t *RedisTest) TestCmdListsLTrim(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - lTrim := t.client.LTrim("list", 1, -1) - c.Assert(lTrim.Err(), IsNil) - c.Assert(lTrim.Val(), Equals, "OK") - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"two", "three"}) -} - -func (t *RedisTest) TestCmdListsRPop(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - rPop := t.client.RPop("list") - c.Assert(rPop.Err(), IsNil) - c.Assert(rPop.Val(), Equals, "three") - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"one", "two"}) -} - -func (t *RedisTest) TestCmdListsRPopLPush(c *C) { - rPush := t.client.RPush("list", "one") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "two") - c.Assert(rPush.Err(), IsNil) - rPush = t.client.RPush("list", "three") - c.Assert(rPush.Err(), IsNil) - - rPopLPush := t.client.RPopLPush("list", "list2") - c.Assert(rPopLPush.Err(), IsNil) - c.Assert(rPopLPush.Val(), Equals, "three") - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"one", "two"}) - - lRange = t.client.LRange("list2", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"three"}) -} - -func (t *RedisTest) TestCmdListsRPush(c *C) { - rPush := t.client.RPush("list", "Hello") - c.Assert(rPush.Err(), IsNil) - c.Assert(rPush.Val(), Equals, int64(1)) - - rPush = t.client.RPush("list", "World") - c.Assert(rPush.Err(), IsNil) - c.Assert(rPush.Val(), Equals, int64(2)) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"Hello", "World"}) -} - -func (t *RedisTest) TestCmdListsRPushX(c *C) { - rPush := t.client.RPush("list", "Hello") - c.Assert(rPush.Err(), IsNil) - c.Assert(rPush.Val(), Equals, int64(1)) - - rPushX := t.client.RPushX("list", "World") - c.Assert(rPushX.Err(), IsNil) - c.Assert(rPushX.Val(), Equals, int64(2)) - - rPushX = t.client.RPushX("list2", "World") - c.Assert(rPushX.Err(), IsNil) - c.Assert(rPushX.Val(), Equals, int64(0)) - - lRange := t.client.LRange("list", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{"Hello", "World"}) - - lRange = t.client.LRange("list2", 0, -1) - c.Assert(lRange.Err(), IsNil) - c.Assert(lRange.Val(), DeepEquals, []string{}) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestSAdd(c *C) { - sAdd := t.client.SAdd("set", "Hello") - c.Assert(sAdd.Err(), IsNil) - c.Assert(sAdd.Val(), Equals, int64(1)) - - sAdd = t.client.SAdd("set", "World") - c.Assert(sAdd.Err(), IsNil) - c.Assert(sAdd.Val(), Equals, int64(1)) - - sAdd = t.client.SAdd("set", "World") - c.Assert(sAdd.Err(), IsNil) - c.Assert(sAdd.Val(), Equals, int64(0)) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sortStrings(sMembers.Val()), DeepEquals, []string{"Hello", "World"}) -} - -func (t *RedisTest) TestSCard(c *C) { - sAdd := t.client.SAdd("set", "Hello") - c.Assert(sAdd.Err(), IsNil) - c.Assert(sAdd.Val(), Equals, int64(1)) - - sAdd = t.client.SAdd("set", "World") - c.Assert(sAdd.Err(), IsNil) - c.Assert(sAdd.Val(), Equals, int64(1)) - - sCard := t.client.SCard("set") - c.Assert(sCard.Err(), IsNil) - c.Assert(sCard.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestSDiff(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sDiff := t.client.SDiff("set1", "set2") - c.Assert(sDiff.Err(), IsNil) - c.Assert(sortStrings(sDiff.Val()), DeepEquals, []string{"a", "b"}) -} - -func (t *RedisTest) TestSDiffStore(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sDiffStore := t.client.SDiffStore("set", "set1", "set2") - c.Assert(sDiffStore.Err(), IsNil) - c.Assert(sDiffStore.Val(), Equals, int64(2)) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sortStrings(sMembers.Val()), DeepEquals, []string{"a", "b"}) -} - -func (t *RedisTest) TestSInter(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sInter := t.client.SInter("set1", "set2") - c.Assert(sInter.Err(), IsNil) - c.Assert(sInter.Val(), DeepEquals, []string{"c"}) -} - -func (t *RedisTest) TestSInterStore(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sInterStore := t.client.SInterStore("set", "set1", "set2") - c.Assert(sInterStore.Err(), IsNil) - c.Assert(sInterStore.Val(), Equals, int64(1)) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sMembers.Val(), DeepEquals, []string{"c"}) -} - -func (t *RedisTest) TestIsMember(c *C) { - sAdd := t.client.SAdd("set", "one") - c.Assert(sAdd.Err(), IsNil) - - sIsMember := t.client.SIsMember("set", "one") - c.Assert(sIsMember.Err(), IsNil) - c.Assert(sIsMember.Val(), Equals, true) - - sIsMember = t.client.SIsMember("set", "two") - c.Assert(sIsMember.Err(), IsNil) - c.Assert(sIsMember.Val(), Equals, false) -} - -func (t *RedisTest) TestSMembers(c *C) { - sAdd := t.client.SAdd("set", "Hello") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "World") - c.Assert(sAdd.Err(), IsNil) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sortStrings(sMembers.Val()), DeepEquals, []string{"Hello", "World"}) -} - -func (t *RedisTest) TestSMove(c *C) { - sAdd := t.client.SAdd("set1", "one") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "two") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "three") - c.Assert(sAdd.Err(), IsNil) - - sMove := t.client.SMove("set1", "set2", "two") - c.Assert(sMove.Err(), IsNil) - c.Assert(sMove.Val(), Equals, true) - - sMembers := t.client.SMembers("set1") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sMembers.Val(), DeepEquals, []string{"one"}) - - sMembers = t.client.SMembers("set2") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sortStrings(sMembers.Val()), DeepEquals, []string{"three", "two"}) -} - -func (t *RedisTest) TestSPop(c *C) { - sAdd := t.client.SAdd("set", "one") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "two") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "three") - c.Assert(sAdd.Err(), IsNil) - - sPop := t.client.SPop("set") - c.Assert(sPop.Err(), IsNil) - c.Assert(sPop.Val(), Not(Equals), "") - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sMembers.Val(), HasLen, 2) -} - -func (t *RedisTest) TestSRandMember(c *C) { - sAdd := t.client.SAdd("set", "one") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "two") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "three") - c.Assert(sAdd.Err(), IsNil) - - sRandMember := t.client.SRandMember("set") - c.Assert(sRandMember.Err(), IsNil) - c.Assert(sRandMember.Val(), Not(Equals), "") - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sMembers.Val(), HasLen, 3) -} - -func (t *RedisTest) TestSRem(c *C) { - sAdd := t.client.SAdd("set", "one") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "two") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set", "three") - c.Assert(sAdd.Err(), IsNil) - - sRem := t.client.SRem("set", "one") - c.Assert(sRem.Err(), IsNil) - c.Assert(sRem.Val(), Equals, int64(1)) - - sRem = t.client.SRem("set", "four") - c.Assert(sRem.Err(), IsNil) - c.Assert(sRem.Val(), Equals, int64(0)) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert( - sortStrings(sMembers.Val()), - DeepEquals, - []string{"three", "two"}, - ) -} - -func (t *RedisTest) TestSUnion(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sUnion := t.client.SUnion("set1", "set2") - c.Assert(sUnion.Err(), IsNil) - c.Assert(sUnion.Val(), HasLen, 5) -} - -func (t *RedisTest) TestSUnionStore(c *C) { - sAdd := t.client.SAdd("set1", "a") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "b") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set1", "c") - c.Assert(sAdd.Err(), IsNil) - - sAdd = t.client.SAdd("set2", "c") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "d") - c.Assert(sAdd.Err(), IsNil) - sAdd = t.client.SAdd("set2", "e") - c.Assert(sAdd.Err(), IsNil) - - sUnionStore := t.client.SUnionStore("set", "set1", "set2") - c.Assert(sUnionStore.Err(), IsNil) - c.Assert(sUnionStore.Val(), Equals, int64(5)) - - sMembers := t.client.SMembers("set") - c.Assert(sMembers.Err(), IsNil) - c.Assert(sMembers.Val(), HasLen, 5) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestZAdd(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - c.Assert(zAdd.Val(), Equals, int64(1)) - - zAdd = t.client.ZAdd("zset", redis.Z{1, "uno"}) - c.Assert(zAdd.Err(), IsNil) - c.Assert(zAdd.Val(), Equals, int64(1)) - - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - c.Assert(zAdd.Val(), Equals, int64(1)) - - zAdd = t.client.ZAdd("zset", redis.Z{3, "two"}) - c.Assert(zAdd.Err(), IsNil) - c.Assert(zAdd.Val(), Equals, int64(0)) - - zRange := t.client.ZRangeWithScores("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"one", "1", "uno", "1", "two", "3"}) -} - -func (t *RedisTest) TestZCard(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - - zCard := t.client.ZCard("zset") - c.Assert(zCard.Err(), IsNil) - c.Assert(zCard.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestZCount(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zCount := t.client.ZCount("zset", "-inf", "+inf") - c.Assert(zCount.Err(), IsNil) - c.Assert(zCount.Val(), Equals, int64(3)) - - zCount = t.client.ZCount("zset", "(1", "3") - c.Assert(zCount.Err(), IsNil) - c.Assert(zCount.Val(), Equals, int64(2)) -} - -func (t *RedisTest) TestZIncrBy(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - - zIncrBy := t.client.ZIncrBy("zset", 2, "one") - c.Assert(zIncrBy.Err(), IsNil) - c.Assert(zIncrBy.Val(), Equals, float64(3)) - - zRange := t.client.ZRangeWithScores("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"two", "2", "one", "3"}) -} - -func (t *RedisTest) TestZInterStore(c *C) { - zAdd := t.client.ZAdd("zset1", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset1", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - - zAdd = t.client.ZAdd("zset2", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset2", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset3", redis.Z{3, "two"}) - c.Assert(zAdd.Err(), IsNil) - - zInterStore := t.client.ZInterStore( - "out", redis.ZStore{Weights: []int64{2, 3}}, "zset1", "zset2") - c.Assert(zInterStore.Err(), IsNil) - c.Assert(zInterStore.Val(), Equals, int64(2)) - - zRange := t.client.ZRangeWithScores("out", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"one", "5", "two", "10"}) -} - -func (t *RedisTest) TestZRange(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRange := t.client.ZRange("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"one", "two", "three"}) - - zRange = t.client.ZRange("zset", 2, 3) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"three"}) - - zRange = t.client.ZRange("zset", -2, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"two", "three"}) -} - -func (t *RedisTest) TestZRangeWithScoresMap(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRange := t.client.ZRangeWithScoresMap("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, map[string]float64{"one": 1, "two": 2, "three": 3}) - - zRange = t.client.ZRangeWithScoresMap("zset", 2, 3) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, map[string]float64{"three": 3}) - - zRange = t.client.ZRangeWithScoresMap("zset", -2, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, map[string]float64{"two": 2, "three": 3}) -} - -func (t *RedisTest) TestZRangeByScore(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRangeByScore := t.client.ZRangeByScore("zset", redis.ZRangeByScore{ - Min: "-inf", - Max: "+inf", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "two", "three"}) - - zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ - Min: "1", - Max: "2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"one", "two"}) - - zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ - Min: "(1", - Max: "2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{"two"}) - - zRangeByScore = t.client.ZRangeByScore("zset", redis.ZRangeByScore{ - Min: "(1", - Max: "(2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, []string{}) -} - -func (t *RedisTest) TestZRangeByScoreWithScoresMap(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRangeByScore := t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ - Min: "-inf", - Max: "+inf", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"one": 1, "two": 2, "three": 3}) - - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ - Min: "1", - Max: "2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"one": 1, "two": 2}) - - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ - Min: "(1", - Max: "2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{"two": 2}) - - zRangeByScore = t.client.ZRangeByScoreWithScoresMap("zset", redis.ZRangeByScore{ - Min: "(1", - Max: "(2", - }) - c.Assert(zRangeByScore.Err(), IsNil) - c.Assert(zRangeByScore.Val(), DeepEquals, map[string]float64{}) -} - -func (t *RedisTest) TestZRank(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRank := t.client.ZRank("zset", "three") - c.Assert(zRank.Err(), IsNil) - c.Assert(zRank.Val(), Equals, int64(2)) - - zRank = t.client.ZRank("zset", "four") - c.Assert(zRank.Err(), Equals, redis.Nil) - c.Assert(zRank.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestZRem(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRem := t.client.ZRem("zset", "two") - c.Assert(zRem.Err(), IsNil) - c.Assert(zRem.Val(), Equals, int64(1)) - - zRange := t.client.ZRangeWithScores("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"one", "1", "three", "3"}) -} - -func (t *RedisTest) TestZRemRangeByRank(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRemRangeByRank := t.client.ZRemRangeByRank("zset", 0, 1) - c.Assert(zRemRangeByRank.Err(), IsNil) - c.Assert(zRemRangeByRank.Val(), Equals, int64(2)) - - zRange := t.client.ZRangeWithScores("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"three", "3"}) -} - -func (t *RedisTest) TestZRemRangeByScore(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRemRangeByScore := t.client.ZRemRangeByScore("zset", "-inf", "(2") - c.Assert(zRemRangeByScore.Err(), IsNil) - c.Assert(zRemRangeByScore.Val(), Equals, int64(1)) - - zRange := t.client.ZRangeWithScores("zset", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"two", "2", "three", "3"}) -} - -func (t *RedisTest) TestZRevRange(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRevRange := t.client.ZRevRange("zset", "0", "-1") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, []string{"three", "two", "one"}) - - zRevRange = t.client.ZRevRange("zset", "2", "3") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, []string{"one"}) - - zRevRange = t.client.ZRevRange("zset", "-2", "-1") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, []string{"two", "one"}) -} - -func (t *RedisTest) TestZRevRangeWithScoresMap(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRevRange := t.client.ZRevRangeWithScoresMap("zset", "0", "-1") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, map[string]float64{"three": 3, "two": 2, "one": 1}) - - zRevRange = t.client.ZRevRangeWithScoresMap("zset", "2", "3") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, map[string]float64{"one": 1}) - - zRevRange = t.client.ZRevRangeWithScoresMap("zset", "-2", "-1") - c.Assert(zRevRange.Err(), IsNil) - c.Assert(zRevRange.Val(), DeepEquals, map[string]float64{"two": 2, "one": 1}) -} - -func (t *RedisTest) TestZRevRangeByScore(c *C) { - zadd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zadd.Err(), IsNil) - zadd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zadd.Err(), IsNil) - zadd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zadd.Err(), IsNil) - - vals, err := t.client.ZRevRangeByScore( - "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}).Result() - c.Assert(err, IsNil) - c.Assert(vals, DeepEquals, []string{"three", "two", "one"}) - - vals, err = t.client.ZRevRangeByScore( - "zset", redis.ZRangeByScore{Max: "2", Min: "(1"}).Result() - c.Assert(err, IsNil) - c.Assert(vals, DeepEquals, []string{"two"}) - - vals, err = t.client.ZRevRangeByScore( - "zset", redis.ZRangeByScore{Max: "(2", Min: "(1"}).Result() - c.Assert(err, IsNil) - c.Assert(vals, DeepEquals, []string{}) -} - -func (t *RedisTest) TestZRevRangeByScoreWithScores(c *C) { - zadd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zadd.Err(), IsNil) - zadd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zadd.Err(), IsNil) - zadd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zadd.Err(), IsNil) - - vals, err := t.client.ZRevRangeByScoreWithScores( - "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}).Result() - c.Assert(err, IsNil) - c.Assert(vals, DeepEquals, []string{"three", "3", "two", "2", "one", "1"}) -} - -func (t *RedisTest) TestZRevRangeByScoreWithScoresMap(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRevRangeByScore := t.client.ZRevRangeByScoreWithScoresMap( - "zset", redis.ZRangeByScore{Max: "+inf", Min: "-inf"}) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{"three": 3, "two": 2, "one": 1}) - - zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap( - "zset", redis.ZRangeByScore{Max: "2", Min: "(1"}) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{"two": 2}) - - zRevRangeByScore = t.client.ZRevRangeByScoreWithScoresMap( - "zset", redis.ZRangeByScore{Max: "(2", Min: "(1"}) - c.Assert(zRevRangeByScore.Err(), IsNil) - c.Assert(zRevRangeByScore.Val(), DeepEquals, map[string]float64{}) -} - -func (t *RedisTest) TestZRevRank(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zRevRank := t.client.ZRevRank("zset", "one") - c.Assert(zRevRank.Err(), IsNil) - c.Assert(zRevRank.Val(), Equals, int64(2)) - - zRevRank = t.client.ZRevRank("zset", "four") - c.Assert(zRevRank.Err(), Equals, redis.Nil) - c.Assert(zRevRank.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestZScore(c *C) { - zAdd := t.client.ZAdd("zset", redis.Z{1.001, "one"}) - c.Assert(zAdd.Err(), IsNil) - - zScore := t.client.ZScore("zset", "one") - c.Assert(zScore.Err(), IsNil) - c.Assert(zScore.Val(), Equals, float64(1.001)) -} - -func (t *RedisTest) TestZUnionStore(c *C) { - zAdd := t.client.ZAdd("zset1", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset1", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - - zAdd = t.client.ZAdd("zset2", redis.Z{1, "one"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset2", redis.Z{2, "two"}) - c.Assert(zAdd.Err(), IsNil) - zAdd = t.client.ZAdd("zset2", redis.Z{3, "three"}) - c.Assert(zAdd.Err(), IsNil) - - zUnionStore := t.client.ZUnionStore( - "out", redis.ZStore{Weights: []int64{2, 3}}, "zset1", "zset2") - c.Assert(zUnionStore.Err(), IsNil) - c.Assert(zUnionStore.Val(), Equals, int64(3)) - - zRange := t.client.ZRangeWithScores("out", 0, -1) - c.Assert(zRange.Err(), IsNil) - c.Assert(zRange.Val(), DeepEquals, []string{"one", "5", "three", "9", "two", "10"}) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestPatternPubSub(c *C) { - pubsub := t.client.PubSub() - defer func() { - c.Assert(pubsub.Close(), IsNil) - }() - - c.Assert(pubsub.PSubscribe("mychannel*"), IsNil) - - pub := t.client.Publish("mychannel1", "hello") - c.Assert(pub.Err(), IsNil) - c.Assert(pub.Val(), Equals, int64(1)) - - c.Assert(pubsub.PUnsubscribe("mychannel*"), IsNil) - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "psubscribe") - c.Assert(subscr.Channel, Equals, "mychannel*") - c.Assert(subscr.Count, Equals, 1) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.PMessage) - c.Assert(subscr.Channel, Equals, "mychannel1") - c.Assert(subscr.Pattern, Equals, "mychannel*") - c.Assert(subscr.Payload, Equals, "hello") - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "punsubscribe") - c.Assert(subscr.Channel, Equals, "mychannel*") - c.Assert(subscr.Count, Equals, 0) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err.(net.Error).Timeout(), Equals, true) - c.Assert(msgi, IsNil) - } -} - -func (t *RedisTest) TestPubSub(c *C) { - pubsub := t.client.PubSub() - defer func() { - c.Assert(pubsub.Close(), IsNil) - }() - - c.Assert(pubsub.Subscribe("mychannel", "mychannel2"), IsNil) - - pub := t.client.Publish("mychannel", "hello") - c.Assert(pub.Err(), IsNil) - c.Assert(pub.Val(), Equals, int64(1)) - - pub = t.client.Publish("mychannel2", "hello2") - c.Assert(pub.Err(), IsNil) - c.Assert(pub.Val(), Equals, int64(1)) - - c.Assert(pubsub.Unsubscribe("mychannel", "mychannel2"), IsNil) - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "subscribe") - c.Assert(subscr.Channel, Equals, "mychannel") - c.Assert(subscr.Count, Equals, 1) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "subscribe") - c.Assert(subscr.Channel, Equals, "mychannel2") - c.Assert(subscr.Count, Equals, 2) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Message) - c.Assert(subscr.Channel, Equals, "mychannel") - c.Assert(subscr.Payload, Equals, "hello") - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - msg := msgi.(*redis.Message) - c.Assert(msg.Channel, Equals, "mychannel2") - c.Assert(msg.Payload, Equals, "hello2") - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "unsubscribe") - c.Assert(subscr.Channel, Equals, "mychannel") - c.Assert(subscr.Count, Equals, 1) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err, IsNil) - subscr := msgi.(*redis.Subscription) - c.Assert(subscr.Kind, Equals, "unsubscribe") - c.Assert(subscr.Channel, Equals, "mychannel2") - c.Assert(subscr.Count, Equals, 0) - } - - { - msgi, err := pubsub.ReceiveTimeout(time.Second) - c.Assert(err.(net.Error).Timeout(), Equals, true) - c.Assert(msgi, IsNil) - } -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestPipeline(c *C) { - set := t.client.Set("key2", "hello2") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - pipeline := t.client.Pipeline() - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() - - set = pipeline.Set("key1", "hello1") - get := pipeline.Get("key2") - incr := pipeline.Incr("key3") - getNil := pipeline.Get("key4") - - cmds, err := pipeline.Exec() - c.Assert(err, Equals, redis.Nil) - c.Assert(cmds, HasLen, 4) - - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello2") - - c.Assert(incr.Err(), IsNil) - c.Assert(incr.Val(), Equals, int64(1)) - - c.Assert(getNil.Err(), Equals, redis.Nil) - c.Assert(getNil.Val(), Equals, "") -} - -func (t *RedisTest) TestPipelineDiscardQueued(c *C) { - pipeline := t.client.Pipeline() - - pipeline.Get("key") - pipeline.Discard() - cmds, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 0) - - c.Assert(pipeline.Close(), IsNil) -} - -func (t *RedisTest) TestPipelineFunc(c *C) { - var get *redis.StringCmd - cmds, err := t.client.Pipelined(func(c *redis.Pipeline) { - get = c.Get("foo") - }) - c.Assert(err, Equals, redis.Nil) - c.Assert(cmds, HasLen, 1) - c.Assert(get.Err(), Equals, redis.Nil) - c.Assert(get.Val(), Equals, "") -} - -func (t *RedisTest) TestPipelineErrValNotSet(c *C) { - pipeline := t.client.Pipeline() - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() - - get := pipeline.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "") -} - -func (t *RedisTest) TestPipelineRunQueuedOnEmptyQueue(c *C) { - pipeline := t.client.Pipeline() - defer func() { - c.Assert(pipeline.Close(), IsNil) - }() - - cmds, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 0) -} - -// TODO: make thread safe? -func (t *RedisTest) TestPipelineIncr(c *C) { - const N = 20000 - key := "TestPipelineIncr" - - pipeline := t.client.Pipeline() - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - pipeline.Incr(key) - wg.Done() - } - wg.Wait() - - cmds, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(len(cmds), Equals, 20000) - for _, cmd := range cmds { - if cmd.Err() != nil { - c.Errorf("got %v, expected nil", cmd.Err()) - } - } - - get := t.client.Get(key) - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, strconv.Itoa(N)) - - c.Assert(pipeline.Close(), IsNil) -} - -func (t *RedisTest) TestPipelineEcho(c *C) { - const N = 1000 - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - go func(i int) { - pipeline := t.client.Pipeline() - - msg1 := "echo" + strconv.Itoa(i) - msg2 := "echo" + strconv.Itoa(i+1) - - echo1 := pipeline.Echo(msg1) - echo2 := pipeline.Echo(msg2) - - cmds, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 2) - - c.Assert(echo1.Err(), IsNil) - c.Assert(echo1.Val(), Equals, msg1) - - c.Assert(echo2.Err(), IsNil) - c.Assert(echo2.Val(), Equals, msg2) - - c.Assert(pipeline.Close(), IsNil) - - wg.Done() - }(i) - } - wg.Wait() -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestMultiExec(c *C) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - var ( - set *redis.StatusCmd - get *redis.StringCmd - ) - cmds, err := multi.Exec(func() { - set = multi.Set("key", "hello") - get = multi.Get("key") - }) - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 2) - - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello") -} - -func (t *RedisTest) TestMultiExecDiscard(c *C) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - cmds, err := multi.Exec(func() { - multi.Set("key1", "hello1") - multi.Discard() - multi.Set("key2", "hello2") - }) - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 1) - - get := t.client.Get("key1") - c.Assert(get.Err(), Equals, redis.Nil) - c.Assert(get.Val(), Equals, "") - - get = t.client.Get("key2") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "hello2") -} - -func (t *RedisTest) TestMultiExecEmpty(c *C) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - cmds, err := multi.Exec(func() {}) - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 0) - - ping := multi.Ping() - c.Check(ping.Err(), IsNil) - c.Check(ping.Val(), Equals, "PONG") -} - -func (t *RedisTest) TestMultiExecOnEmptyQueue(c *C) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - cmds, err := multi.Exec(func() {}) - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 0) -} - -func (t *RedisTest) TestMultiExecIncr(c *C) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - cmds, err := multi.Exec(func() { - for i := int64(0); i < 20000; i++ { - multi.Incr("key") - } - }) - c.Assert(err, IsNil) - c.Assert(len(cmds), Equals, 20000) - for _, cmd := range cmds { - if cmd.Err() != nil { - c.Errorf("got %v, expected nil", cmd.Err()) - } - } - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "20000") -} - -func (t *RedisTest) transactionalIncr(c *C) ([]redis.Cmder, error) { - multi := t.client.Multi() - defer func() { - c.Assert(multi.Close(), IsNil) - }() - - watch := multi.Watch("key") - c.Assert(watch.Err(), IsNil) - c.Assert(watch.Val(), Equals, "OK") - - get := multi.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Not(Equals), redis.Nil) - - v, err := strconv.ParseInt(get.Val(), 10, 64) - c.Assert(err, IsNil) - - return multi.Exec(func() { - multi.Set("key", strconv.FormatInt(v+1, 10)) - }) -} - -func (t *RedisTest) TestWatchUnwatch(c *C) { - set := t.client.Set("key", "0") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - wg := &sync.WaitGroup{} - for i := 0; i < 1000; i++ { - wg.Add(1) - go func() { - for { - cmds, err := t.transactionalIncr(c) - if err == redis.TxFailedErr { - continue - } - c.Assert(err, IsNil) - c.Assert(cmds, HasLen, 1) - c.Assert(cmds[0].Err(), IsNil) - break - } - wg.Done() - }() - } - wg.Wait() - - get := t.client.Get("key") - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, "1000") -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestRaceEcho(c *C) { - const N = 10000 - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := 0; i < N; i++ { - go func(i int) { - msg := "echo" + strconv.Itoa(i) - echo := t.client.Echo(msg) - c.Assert(echo.Err(), IsNil) - c.Assert(echo.Val(), Equals, msg) - wg.Done() - }(i) - } - wg.Wait() -} - -func (t *RedisTest) TestRaceIncr(c *C) { - const N = 10000 - key := "TestIncrFromGoroutines" - - wg := &sync.WaitGroup{} - wg.Add(N) - for i := int64(0); i < N; i++ { - go func() { - incr := t.client.Incr(key) - if err := incr.Err(); err != nil { - panic(err) - } - wg.Done() - }() - } - wg.Wait() - - get := t.client.Get(key) - c.Assert(get.Err(), IsNil) - c.Assert(get.Val(), Equals, strconv.Itoa(N)) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdBgRewriteAOF(c *C) { - r := t.client.BgRewriteAOF() - c.Assert(r.Err(), IsNil) - c.Assert(r.Val(), Equals, "Background append only file rewriting started") -} - -func (t *RedisTest) TestCmdBgSave(c *C) { - // workaround for "ERR Can't BGSAVE while AOF log rewriting is in progress" - time.Sleep(time.Second) - - r := t.client.BgSave() - c.Assert(r.Err(), IsNil) - c.Assert(r.Val(), Equals, "Background saving started") -} - -func (t *RedisTest) TestCmdClientKill(c *C) { - r := t.client.ClientKill("1.1.1.1:1111") - c.Assert(r.Err(), ErrorMatches, "ERR No such client") - c.Assert(r.Val(), Equals, "") -} - -func (t *RedisTest) TestCmdConfigGet(c *C) { - r := t.client.ConfigGet("*") - c.Assert(r.Err(), IsNil) - c.Assert(len(r.Val()) > 0, Equals, true) -} - -func (t *RedisTest) TestCmdConfigResetStat(c *C) { - r := t.client.ConfigResetStat() - c.Assert(r.Err(), IsNil) - c.Assert(r.Val(), Equals, "OK") -} - -func (t *RedisTest) TestCmdConfigSet(c *C) { - configGet := t.client.ConfigGet("maxmemory") - c.Assert(configGet.Err(), IsNil) - c.Assert(configGet.Val(), HasLen, 2) - c.Assert(configGet.Val()[0], Equals, "maxmemory") - - configSet := t.client.ConfigSet("maxmemory", configGet.Val()[1].(string)) - c.Assert(configSet.Err(), IsNil) - c.Assert(configSet.Val(), Equals, "OK") -} - -func (t *RedisTest) TestCmdDbSize(c *C) { - dbSize := t.client.DbSize() - c.Assert(dbSize.Err(), IsNil) - c.Assert(dbSize.Val(), Equals, int64(0)) -} - -func (t *RedisTest) TestCmdFlushAll(c *C) { - // TODO -} - -func (t *RedisTest) TestCmdFlushDb(c *C) { - // TODO -} - -func (t *RedisTest) TestCmdInfo(c *C) { - info := t.client.Info() - c.Assert(info.Err(), IsNil) - c.Assert(info.Val(), Not(Equals), "") -} - -func (t *RedisTest) TestCmdLastSave(c *C) { - lastSave := t.client.LastSave() - c.Assert(lastSave.Err(), IsNil) - c.Assert(lastSave.Val(), Not(Equals), 0) -} - -func (t *RedisTest) TestCmdSave(c *C) { - save := t.client.Save() - c.Assert(save.Err(), IsNil) - c.Assert(save.Val(), Equals, "OK") -} - -func (t *RedisTest) TestSlaveOf(c *C) { - slaveOf := t.client.SlaveOf("localhost", "8888") - c.Assert(slaveOf.Err(), IsNil) - c.Assert(slaveOf.Val(), Equals, "OK") - - slaveOf = t.client.SlaveOf("NO", "ONE") - c.Assert(slaveOf.Err(), IsNil) - c.Assert(slaveOf.Val(), Equals, "OK") -} - -func (t *RedisTest) TestTime(c *C) { - time := t.client.Time() - c.Assert(time.Err(), IsNil) - c.Assert(time.Val(), HasLen, 2) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestScriptingEval(c *C) { - eval := t.client.Eval( - "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", - []string{"key1", "key2"}, - []string{"first", "second"}, - ) - c.Assert(eval.Err(), IsNil) - c.Assert(eval.Val(), DeepEquals, []interface{}{"key1", "key2", "first", "second"}) - - eval = t.client.Eval( - "return redis.call('set',KEYS[1],'bar')", - []string{"foo"}, - []string{}, - ) - c.Assert(eval.Err(), IsNil) - c.Assert(eval.Val(), Equals, "OK") - - eval = t.client.Eval("return 10", []string{}, []string{}) - c.Assert(eval.Err(), IsNil) - c.Assert(eval.Val(), Equals, int64(10)) - - eval = t.client.Eval("return {1,2,{3,'Hello World!'}}", []string{}, []string{}) - c.Assert(eval.Err(), IsNil) - // DeepEquals can't compare nested slices. - c.Assert( - fmt.Sprintf("%#v", eval.Val()), - Equals, - `[]interface {}{1, 2, []interface {}{3, "Hello World!"}}`, - ) -} - -func (t *RedisTest) TestScriptingEvalSha(c *C) { - set := t.client.Set("foo", "bar") - c.Assert(set.Err(), IsNil) - c.Assert(set.Val(), Equals, "OK") - - eval := t.client.Eval("return redis.call('get','foo')", nil, nil) - c.Assert(eval.Err(), IsNil) - c.Assert(eval.Val(), Equals, "bar") - - evalSha := t.client.EvalSha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791", nil, nil) - c.Assert(evalSha.Err(), IsNil) - c.Assert(evalSha.Val(), Equals, "bar") - - evalSha = t.client.EvalSha("ffffffffffffffffffffffffffffffffffffffff", nil, nil) - c.Assert(evalSha.Err(), ErrorMatches, "NOSCRIPT No matching script. Please use EVAL.") - c.Assert(evalSha.Val(), Equals, nil) -} - -func (t *RedisTest) TestScriptingScriptExists(c *C) { - scriptLoad := t.client.ScriptLoad("return 1") - c.Assert(scriptLoad.Err(), IsNil) - c.Assert(scriptLoad.Val(), Equals, "e0e1f9fabfc9d4800c877a703b823ac0578ff8db") - - scriptExists := t.client.ScriptExists( - "e0e1f9fabfc9d4800c877a703b823ac0578ff8db", - "ffffffffffffffffffffffffffffffffffffffff", - ) - c.Assert(scriptExists.Err(), IsNil) - c.Assert(scriptExists.Val(), DeepEquals, []bool{true, false}) -} - -func (t *RedisTest) TestScriptingScriptFlush(c *C) { - scriptFlush := t.client.ScriptFlush() - c.Assert(scriptFlush.Err(), IsNil) - c.Assert(scriptFlush.Val(), Equals, "OK") -} - -func (t *RedisTest) TestScriptingScriptKill(c *C) { - scriptKill := t.client.ScriptKill() - c.Assert(scriptKill.Err(), ErrorMatches, ".*No scripts in execution right now.") - c.Assert(scriptKill.Val(), Equals, "") -} - -func (t *RedisTest) TestScriptingScriptLoad(c *C) { - scriptLoad := t.client.ScriptLoad("return redis.call('get','foo')") - c.Assert(scriptLoad.Err(), IsNil) - c.Assert(scriptLoad.Val(), Equals, "6b1bf486c81ceb7edf3c093f4c48582e38c0e791") -} - -func (t *RedisTest) TestScriptingNewScript(c *C) { - s := redis.NewScript("return 1") - run := s.Run(t.client, nil, nil) - c.Assert(run.Err(), IsNil) - c.Assert(run.Val(), Equals, int64(1)) -} - -func (t *RedisTest) TestScriptingEvalAndPipeline(c *C) { - pipeline := t.client.Pipeline() - s := redis.NewScript("return 1") - run := s.Eval(pipeline, nil, nil) - _, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(run.Err(), IsNil) - c.Assert(run.Val(), Equals, int64(1)) -} - -func (t *RedisTest) TestScriptingEvalShaAndPipeline(c *C) { - s := redis.NewScript("return 1") - c.Assert(s.Load(t.client).Err(), IsNil) - - pipeline := t.client.Pipeline() - run := s.Eval(pipeline, nil, nil) - _, err := pipeline.Exec() - c.Assert(err, IsNil) - c.Assert(run.Err(), IsNil) - c.Assert(run.Val(), Equals, int64(1)) -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) TestCmdDebugObject(c *C) { - { - debug := t.client.DebugObject("foo") - c.Assert(debug.Err(), Not(IsNil)) - c.Assert(debug.Err().Error(), Equals, "ERR no such key") - } - - { - t.client.Set("foo", "bar") - debug := t.client.DebugObject("foo") - c.Assert(debug.Err(), IsNil) - c.Assert(debug.Val(), FitsTypeOf, "") - c.Assert(debug.Val(), Not(Equals), "") - } -} - -//------------------------------------------------------------------------------ - -func (t *RedisTest) BenchmarkRedisPing(c *C) { - for i := 0; i < c.N; i++ { - if err := t.client.Ping().Err(); err != nil { - panic(err) - } - } -} - -func (t *RedisTest) BenchmarkRedisSet(c *C) { - for i := 0; i < c.N; i++ { - if err := t.client.Set("key", "hello").Err(); err != nil { - panic(err) - } - } -} - -func (t *RedisTest) BenchmarkRedisGetNil(c *C) { - for i := 0; i < c.N; i++ { - if err := t.client.Get("key").Err(); err != redis.Nil { - panic(err) - } - } -} - -func (t *RedisTest) BenchmarkRedisGet(c *C) { - c.StopTimer() - - set := t.client.Set("key", "hello") - c.Assert(set.Err(), IsNil) - - c.StartTimer() - - for i := 0; i < c.N; i++ { - if err := t.client.Get("key").Err(); err != nil { - panic(err) - } - } -} - -func (t *RedisTest) BenchmarkRedisMGet(c *C) { - c.StopTimer() - - mset := t.client.MSet("key1", "hello1", "key2", "hello2") - c.Assert(mset.Err(), IsNil) - - c.StartTimer() - - for i := 0; i < c.N; i++ { - if err := t.client.MGet("key1", "key2").Err(); err != nil { - panic(err) - } - } -} diff --git a/v2/script.go b/v2/script.go deleted file mode 100644 index 96c35f5..0000000 --- a/v2/script.go +++ /dev/null @@ -1,52 +0,0 @@ -package redis - -import ( - "crypto/sha1" - "encoding/hex" - "io" - "strings" -) - -type scripter interface { - Eval(script string, keys []string, args []string) *Cmd - EvalSha(sha1 string, keys []string, args []string) *Cmd - ScriptExists(scripts ...string) *BoolSliceCmd - ScriptLoad(script string) *StringCmd -} - -type Script struct { - src, hash string -} - -func NewScript(src string) *Script { - h := sha1.New() - io.WriteString(h, src) - return &Script{ - src: src, - hash: hex.EncodeToString(h.Sum(nil)), - } -} - -func (s *Script) Load(c scripter) *StringCmd { - return c.ScriptLoad(s.src) -} - -func (s *Script) Exists(c scripter) *BoolSliceCmd { - return c.ScriptExists(s.src) -} - -func (s *Script) Eval(c scripter, keys []string, args []string) *Cmd { - return c.Eval(s.src, keys, args) -} - -func (s *Script) EvalSha(c scripter, keys []string, args []string) *Cmd { - return c.EvalSha(s.hash, keys, args) -} - -func (s *Script) Run(c *Client, keys []string, args []string) *Cmd { - r := s.EvalSha(c, keys, args) - if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") { - return s.Eval(c, keys, args) - } - return r -}