redis 2.0.0-rc.1

Redis driver for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Generate implementation for function skeleton, we use this for `AsyncTypedCommands` because we want to be able to handle having a return type specified or unspecified with a fallback

/// Selects a value depending on whether the first argument is `RedisResult`
///
/// The following `$action`s (second argument) are supported:
///
/// * `strip_redisresult` - If `$selector` is a `RedisResult<SomeType>`, yield `SomeType`.
///   Otherwise, yield the unmodified `$selector`.
///
///   This action does not take a `$target` argument, as it operates directly on `$selector`.
/// * `try` - If `$selector` is a `RedisResult<...>`, yield `$target?`, otherwise `$target`.
/// * `wrap_ok` - If `$selector` is a `RedisResult<...>`, yield `Ok($target)`, otherwise `$target`.
/// * `wrap_redisresult` - If `$selector` is a `RedisResult<...>`, yield `RedisResult<$target>`,
///   otherwise `$target`.
///
/// # Arguments
///
/// * `$selector` -  If it's a `RedisResult`, yield the result of executing `$action` on `$target`.
///   Otherwise, yield the unmodified `$target`.
/// * `$action` - The action to take. See this function's description for available actions.
/// * `$target` - The target `tt` to take the action on.
macro_rules! if_redisresult {
    ((RedisResult<$type:ty>), strip_redisresult) => {
        ($type)
    };
    ((RedisResult<$unused:ty>), try, $target:tt) => {
        (($target)?)
    };
    ((RedisResult<$unused:ty>), wrap_ok, $target:tt) => {
        (Ok($target))
    };
    ((RedisResult<$unused:ty>), wrap_redisresult, $target:tt) => {
        (RedisResult<$target>)
    };
    ($other_type:ty, $i:ident, $target:tt) => {
        $target
    };
    ($other_type:ty, $i:ident) => {
        $other_type
    };
}

/// Converts the returned value for typed commands
///
/// This macro is used to resolve the `via` for typed commands
///
/// For typed commands without a `via`, the `$body` is used as is. (The `$body` return value is
/// converted by `$rettype`'s [`FromRedisValue`](crate::FromRedisValue) implementation)
///
/// For typed commands with `via`, the `$ret_conv_fn` gets applied to `$body`.
///
/// # Arguments
///
/// * `$ret_conv_fn` - (optional) If present, convert `$body`'s output  using this function. It
///   has to take a `Value` as input and map it to `Result<T, ParsingError>`, where `T` is the typed
///   commands final output type. If missing, `$body` is returned as is.
/// * `$body` - The command's implementation. It has to yield a `Value`
macro_rules! convert_ret {
    ($ret_conv_fn:ident, { $($body:tt)* }) => {
        Ok($ret_conv_fn({ $($body)* }?)?)
    };
    (, { $($body:tt)* }) => {
        $($body)*
    };
}

#[cfg(feature = "aio")]
macro_rules! implement_command_async {
    // Expand the `Generic` return type to `RV`
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> Generic $(via $ret_conv_fn:ident)?
    ) => {
        implement_command_async!(
            $(#[$attr])+
            fn $name<$($tyargs : $ty,)* RV: FromRedisValue>(
                $($argname: $argty),*) -> RV $(via $ret_conv_fn)?
        );
    };

    // Expand the `RedisResult<Generic>` return type to `RedisResult<RV>`
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> (RedisResult<Generic>) $(via $ret_conv_fn:ident)?
    ) => {
        implement_command_async!(
            $(#[$attr])+
            fn $name<$($tyargs : $ty,)* RV: FromRedisValue>(
                $($argname: $argty),*) -> (RedisResult<RV>) $(via $ret_conv_fn)?
        );
    };

    // Actual implementation of the command
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> $rettype:tt $(via $ret_conv_fn:ident)?
    ) => {
        $(#[$attr])*
        #[inline]
        #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
        fn $name<$($tyargs: $ty + Send + Sync,)*>(
            &mut self
            $(, $argname: $argty)*
        ) -> impl Future<Output = RedisResult<if_redisresult!($rettype, strip_redisresult)>> + Send

        {
            async move {
                convert_ret!($($ret_conv_fn)?, {
                    if_redisresult!($rettype, try, (Cmd::$name($($argname),*)))
                        .query_async(self)
                        .await
                    })
            }
        }
    };
}

macro_rules! implement_command_sync {
    // Expand the `Generic` return type to `RV`
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> Generic $(via $ret_conv_fn:ident)?
    ) => {
        implement_command_sync!(
            $(#[$attr])+
            fn $name<$($tyargs : $ty,)* RV: FromRedisValue>(
                $($argname: $argty),*) -> RV $(via $ret_conv_fn)?
        );
    };

    // Expand the `Generic` return type to `RedisResult<RV>`
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> (RedisResult<Generic>) $(via $ret_conv_fn:ident)?
    ) => {
        implement_command_sync!(
            $(#[$attr])+
            fn $name<$($tyargs : $ty,)* RV: FromRedisValue>(
                $($argname: $argty),*) -> (RedisResult<RV>) $(via $ret_conv_fn)?
        );
    };

    // Actual implementation of the command
    (
        $(#[$attr:meta])+
        fn $name:ident<$($tyargs:ident : $ty:ident),*>(
            $($argname:ident: $argty:ty),*) -> $rettype:tt $(via $ret_conv_fn:ident)?
    ) => {
        $(#[$attr])*
        #[inline]
        #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
        fn $name<$($tyargs: $ty + Send + Sync,)*>(
            &mut self
            $(, $argname: $argty)*
        ) -> RedisResult<if_redisresult!($rettype, strip_redisresult)>

        {
            convert_ret!($($ret_conv_fn)?, {
                if_redisresult!($rettype, try, { (Cmd::$name($($argname),*)) })
                .query(self)
            })
        }
    };
}

macro_rules! ready_cmd {
    ($name:expr $(, $arg:expr)*) => {{
        let name = $name;
        let args_count = 1usize;
        let args_size = name.len();
        $(
            let (next_args_count, next_args_size) = $arg.num_of_args_and_size();
            let args_count = args_count + next_args_count;
            let args_size = args_size + next_args_size;
        )*
        let mut cmd = Cmd::with_capacity(args_count, args_size);
        cmd.arg(name);
        $(cmd.arg($arg);)*
        cmd
    }};
}

macro_rules! write_pipeline_command {
    ($self:expr, { ready_cmd!($name:expr $(, $arg:expr)*).take() }) => {{
        let name = $name;
        let args_count = 1usize;
        let args_size = name.len();
        $(
            let (next_args_count, next_args_size) = $arg.num_of_args_and_size();
            let args_count = args_count + next_args_count;
            let args_size = args_size + next_args_size;
        )*
        $self.reserve_for_args(args_count)
          .reserve_for_data(args_size);
        $self.start_command();
        $crate::types::RedisWrite::write_arg($self, name.as_bytes());
        $($self.arg($arg);)*
        $self
    }};

    ($self:expr, $cmd:expr) => {{
        $self.add_command($cmd)
    }};
}

macro_rules! implement_iterators {
    ($lifetime: lifetime, $iter:expr, $ret:ty) => {
        /// Incrementally iterate the keys space.
        #[inline]
        fn scan<$lifetime, RV: FromRedisValue + $lifetime>(&$lifetime mut self) -> $ret {
            let mut c = cmd("SCAN");
            c.cursor_arg(0);
            $iter(c, self)
        }

        /// Incrementally iterate the keys space with options.
        #[inline]
        fn scan_options<$lifetime, RV: FromRedisValue + $lifetime>(&$lifetime mut self, opts: ScanOptions) -> $ret {
            let mut c = cmd("SCAN");
            c.cursor_arg(0).arg(opts);
            $iter(c, self)
        }

        /// Incrementally iterate the keys space for keys matching a pattern.
        #[inline]
        fn scan_match<$lifetime, P: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(&$lifetime mut self, pattern: P) -> $ret {
            let mut c = cmd("SCAN");
            c.cursor_arg(0).arg("MATCH").arg(pattern);
            $iter(c, self)
        }

        /// Incrementally iterate hash fields and associated values.
        #[inline]
        fn hscan<$lifetime, K: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(&$lifetime mut self, key: K) -> $ret {
            let mut c = cmd("HSCAN");
            c.arg(key).cursor_arg(0);
            $iter(c, self)
        }

        /// Incrementally iterate hash fields and associated values for
        /// field names matching a pattern.
        #[inline]
        fn hscan_match<$lifetime, K: ToSingleRedisArg, P: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(
            &$lifetime mut self,
            key: K,
            pattern: P,
        ) -> $ret {
            let mut c = cmd("HSCAN");
            c.arg(key).cursor_arg(0).arg("MATCH").arg(pattern);
            $iter(c, self)
        }

        /// Incrementally iterate set elements.
        #[inline]
        fn sscan<$lifetime, K: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(&$lifetime mut self, key: K) -> $ret {
            let mut c = cmd("SSCAN");
            c.arg(key).cursor_arg(0);
            $iter(c, self)
        }

        /// Incrementally iterate set elements for elements matching a pattern.
        #[inline]
        fn sscan_match<$lifetime, K: ToSingleRedisArg, P: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(
            &$lifetime mut self,
            key: K,
            pattern: P,
        ) -> $ret {
            let mut c = cmd("SSCAN");
            c.arg(key).cursor_arg(0).arg("MATCH").arg(pattern);
            $iter(c, self)
        }

        /// Incrementally iterate sorted set elements.
        #[inline]
        fn zscan<$lifetime, K: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(&$lifetime mut self, key: K) -> $ret {
            let mut c = cmd("ZSCAN");
            c.arg(key).cursor_arg(0);
            $iter(c, self)
        }

        /// Incrementally iterate sorted set elements for elements matching a pattern.
        #[inline]
        fn zscan_match<$lifetime, K: ToSingleRedisArg, P: ToSingleRedisArg, RV: FromRedisValue + $lifetime>(
            &$lifetime mut self,
            key: K,
            pattern: P,
        ) -> $ret {
            let mut c = cmd("ZSCAN");
            c.arg(key).cursor_arg(0).arg("MATCH").arg(pattern);
            $iter(c, self)
        }
    };
}

macro_rules! implement_commands {
    (
        $(
            $(#[$attr:meta])+
            fn $name:ident<$($tyargs:ident : $ty:ident),*>(
                $($argname:ident: $argty:ty),*) -> $rettype:tt $(via $ret_conv_fn:ident)? { $($body:tt)* }
        )*
    ) =>
    (
        /// Implements common redis commands for connection like objects.
        ///
        /// This allows you to send commands straight to a connection or client.
        /// It is also implemented for redis results of clients which makes for
        /// very convenient access in some basic cases.
        ///
        /// This allows you to use nicer syntax for some common operations.
        /// For instance this code:
        ///
        /// ```rust,no_run
        /// # fn do_something() -> redis::RedisResult<()> {
        /// let client = redis::Client::open("redis://127.0.0.1/")?;
        /// let mut con = client.get_connection()?;
        /// redis::cmd("SET").arg("my_key").arg(42).exec(&mut con).unwrap();
        /// assert_eq!(redis::cmd("GET").arg("my_key").query(&mut con), Ok(42));
        /// # Ok(()) }
        /// ```
        ///
        /// Will become this:
        ///
        /// ```rust,no_run
        /// # fn do_something() -> redis::RedisResult<()> {
        /// use redis::Commands;
        /// let client = redis::Client::open("redis://127.0.0.1/")?;
        /// let mut con = client.get_connection()?;
        /// let _: () = con.set("my_key", 42)?;
        /// assert_eq!(con.get("my_key"), Ok(42));
        /// # Ok(()) }
        /// ```
        pub trait Commands : ConnectionLike+Sized {
            $(
                $(#[$attr])*
                #[inline]
                #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
                fn $name<$($tyargs: $ty, )* RV: FromRedisValue>(
                    &mut self $(, $argname: $argty)*) -> RedisResult<RV>
                    {
                        if_redisresult!($rettype, try, (Cmd::$name($($argname),*)))
                            .query(self)
                    }
            )*

            implement_iterators! {
                'a,
                |c: Cmd, this| c.iter(this),
                RedisResult<Iter<'a, RV>>
            }
        }

        impl Cmd {
            $(
                $(#[$attr])*
                #[inline]
                #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
                pub fn $name<$($tyargs: $ty),*>($($argname: $argty),*) -> if_redisresult!($rettype, wrap_redisresult, Self) {
                    if_redisresult!($rettype, wrap_ok, { $($body)* })
                }
            )*
        }

        /// Implements common redis commands over asynchronous connections.
        ///
        /// This allows you to send commands straight to a connection or client.
        ///
        /// This allows you to use nicer syntax for some common operations.
        /// For instance this code:
        ///
        /// ```rust,no_run
        /// use redis::AsyncCommands;
        /// # async fn do_something() -> redis::RedisResult<()> {
        /// let client = redis::Client::open("redis://127.0.0.1/")?;
        /// let mut con = client.get_multiplexed_async_connection().await?;
        /// redis::cmd("SET").arg("my_key").arg(42i32).exec_async(&mut con).await?;
        /// assert_eq!(redis::cmd("GET").arg("my_key").query_async(&mut con).await, Ok(42i32));
        /// # Ok(()) }
        /// ```
        ///
        /// Will become this:
        ///
        /// ```rust,no_run
        /// use redis::AsyncCommands;
        /// # async fn do_something() -> redis::RedisResult<()> {
        /// use redis::Commands;
        /// let client = redis::Client::open("redis://127.0.0.1/")?;
        /// let mut con = client.get_multiplexed_async_connection().await?;
        /// let _: () = con.set("my_key", 42i32).await?;
        /// assert_eq!(con.get("my_key").await, Ok(42i32));
        /// # Ok(()) }
        /// ```
        #[cfg(feature = "aio")]
        pub trait AsyncCommands : crate::aio::ConnectionLike + Send + Sized {
            $(
                $(#[$attr])*
                #[inline]
                #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
                fn $name<$($tyargs: $ty + Send + Sync,)* RV>(
                    &mut self
                    $(, $argname: $argty)*
                ) -> impl Future<Output = RedisResult<RV>> + Send
                where
                    RV: FromRedisValue,
                {
                    async move {
                        if_redisresult!($rettype, try, (Cmd::$name($($argname),*)))
                            .query_async(self)
                            .await
                    }
                }
            )*

            implement_iterators! {
                'a,
                |c: Cmd, this| async move { c.iter_async(this).await },
                impl Future<Output = RedisResult<crate::cmd::AsyncIter<'a, RV>>> + Send
            }
        }

        /// Implements common redis commands.
        /// The return types are concrete and opinionated. If you want to choose the return type you should use the `Commands` trait.
        pub trait TypedCommands : ConnectionLike+Sized {
            $(
                implement_command_sync! {
                    $(#[$attr])*
                    fn $name<$($tyargs: $ty),*>(
                        $($argname: $argty),*
                    ) -> $rettype $(via $ret_conv_fn)?
                }
            )*

            implement_iterators! {
                'a,
                |c: Cmd, this| c.iter(this),
                RedisResult<Iter<'a, RV>>
            }

            /// Get a value from Redis and convert it to an `Option<isize>`.
            fn get_int<K: ToSingleRedisArg>(&mut self, key: K) -> RedisResult<Option<isize>> {
                cmd("GET").arg(key).query(self)
            }

            /// Get values from Redis and convert them to `Option<isize>`s.
            fn mget_ints<K: ToRedisArgs>(&mut self, key: K) -> RedisResult<Vec<Option<isize>>> {
                cmd("MGET").arg(key).query(self)
            }
        }

        /// Implements common redis commands over asynchronous connections.
        /// The return types are concrete and opinionated. If you want to choose the return type you should use the `AsyncCommands` trait.
        #[cfg(feature = "aio")]
        pub trait AsyncTypedCommands : crate::aio::ConnectionLike + Send + Sized {
            $(
                implement_command_async! {
                    $(#[$attr])*
                    fn $name<$($tyargs: $ty),*>(
                        $($argname: $argty),*
                    ) -> $rettype $(via $ret_conv_fn)?
                }
            )*

            implement_iterators! {
                'a,
                |c: Cmd, this| async move { c.iter_async(this).await },
                impl Future<Output = RedisResult<crate::cmd::AsyncIter<'a, RV>>>
            }

            /// Get a value from Redis and convert it to an `Option<isize>`.
            fn get_int<K: ToSingleRedisArg + Send + Sync>(&mut self, key: K) -> impl Future<Output = RedisResult<Option<isize>>> + Send {
                async move { cmd("GET").arg(key).query_async(self).await }
            }

            /// Get values from Redis and convert them to `Option<isize>`s.
            fn mget_ints<K: ToRedisArgs + Send + Sync>(&mut self, key: K) -> impl Future<Output = RedisResult<Vec<Option<isize>>>> + Send {
                async move { cmd("MGET").arg(key).query_async(self).await }
            }
        }

        /// Implements common redis commands for pipelines.  Unlike the regular
        /// commands trait, this returns the pipeline rather than a result
        /// directly.  Other than that it works the same however.
        impl Pipeline {
            $(
                $(#[$attr])*
                #[inline]
                #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
                pub fn $name<$($tyargs: $ty),*>(
                    &mut self $(, $argname: $argty)*
                ) -> if_redisresult!($rettype, wrap_redisresult, (&mut Self)) {
                    if_redisresult!($rettype, wrap_ok, (write_pipeline_command!(self, { $($body)* })))
                }
            )*
        }

        // Implements common redis commands for cluster pipelines.  Unlike the regular
        // commands trait, this returns the cluster pipeline rather than a result
        // directly.  Other than that it works the same however.
        #[cfg(feature = "cluster")]
        impl ClusterPipeline {
            $(
                $(#[$attr])*
                #[inline]
                #[allow(clippy::extra_unused_lifetimes, clippy::needless_lifetimes)]
                pub fn $name<$($tyargs: $ty),*>(
                    &mut self $(, $argname: $argty)*
                ) -> if_redisresult!($rettype, wrap_redisresult, (&mut Self)) {
                    if_redisresult!($rettype, wrap_ok, (write_pipeline_command!(self, { $($body)* })))
                }
            )*
        }
    );
}