Skip to main content

redis_tower_commands/
keys.rs

1//! Key lifecycle, expiry, migration, and metadata commands.
2//!
3//! Prefer [`Scan`](crate::scan::Scan) to [`Keys`] on production keyspaces.
4//! Multi-key commands must use one hash slot in Redis Cluster unless the
5//! higher-level cluster client explicitly splits them. Expiry and lookup
6//! commands use typed integer or optional responses rather than collapsing
7//! missing keys into empty values.
8//!
9//! ```
10//! use redis_tower_commands::{Expire, Ttl};
11//! use redis_tower_core::Command;
12//!
13//! let expire = Expire::new("session:1", 60);
14//! let ttl = Ttl::new("session:1");
15//! assert_eq!((expire.name(), ttl.name()), ("EXPIRE", "TTL"));
16//! ```
17//!
18//! See the [command cookbook] for Cluster and cursor guidance.
19//!
20//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#pipelines-transactions-and-cluster-slots
21
22use crate::CommandArg;
23use bytes::Bytes;
24use redis_tower_core::{Command, Frame, RedisError};
25use redis_tower_protocol::helpers::{array, bulk};
26
27/// DEL key [key ...]
28///
29/// Removes the specified keys. Returns the number of keys removed.
30#[derive(Clone)]
31pub struct Del {
32    keys: Vec<CommandArg>,
33}
34
35impl Del {
36    /// Create a new [`Del`] command.
37    pub fn new(key: impl Into<CommandArg>) -> Self {
38        Self {
39            keys: vec![key.into()],
40        }
41    }
42
43    /// Create the [`Del`] command for the supplied keys.
44    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
45        Self {
46            keys: keys.into_iter().map(Into::into).collect(),
47        }
48    }
49}
50
51impl Command for Del {
52    type Response = i64;
53
54    fn to_frame(&self) -> Frame {
55        let mut args = vec![bulk("DEL")];
56        for key in &self.keys {
57            args.push(bulk(key));
58        }
59        array(args)
60    }
61
62    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
63        match frame {
64            Frame::Integer(n) => Ok(n),
65            other => Err(RedisError::UnexpectedResponse {
66                expected: "integer",
67                actual: format!("{other:?}"),
68            }),
69        }
70    }
71
72    fn name(&self) -> &str {
73        "DEL"
74    }
75}
76
77/// EXISTS key [key ...]
78///
79/// Returns the number of specified keys that exist.
80#[derive(Clone)]
81pub struct Exists {
82    keys: Vec<CommandArg>,
83}
84
85impl Exists {
86    /// Create a new [`Exists`] command.
87    pub fn new(key: impl Into<CommandArg>) -> Self {
88        Self {
89            keys: vec![key.into()],
90        }
91    }
92
93    /// Create the [`Exists`] command for the supplied keys.
94    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
95        Self {
96            keys: keys.into_iter().map(Into::into).collect(),
97        }
98    }
99}
100
101impl Command for Exists {
102    type Response = i64;
103
104    fn to_frame(&self) -> Frame {
105        let mut args = vec![bulk("EXISTS")];
106        for key in &self.keys {
107            args.push(bulk(key));
108        }
109        array(args)
110    }
111
112    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
113        match frame {
114            Frame::Integer(n) => Ok(n),
115            other => Err(RedisError::UnexpectedResponse {
116                expected: "integer",
117                actual: format!("{other:?}"),
118            }),
119        }
120    }
121
122    fn name(&self) -> &str {
123        "EXISTS"
124    }
125
126    fn idempotent(&self) -> bool {
127        true
128    }
129}
130
131/// Condition flag for the EXPIRE family of commands (Redis 7.0+).
132#[derive(Debug, Clone, Copy)]
133pub enum ExpireCondition {
134    /// Set expiry only when the key has no existing expiry.
135    Nx,
136    /// Set expiry only when the key already has an expiry.
137    Xx,
138    /// Set expiry only when the new TTL is greater than the current one.
139    Gt,
140    /// Set expiry only when the new TTL is less than the current one.
141    Lt,
142}
143
144impl ExpireCondition {
145    fn as_str(&self) -> &str {
146        match self {
147            ExpireCondition::Nx => "NX",
148            ExpireCondition::Xx => "XX",
149            ExpireCondition::Gt => "GT",
150            ExpireCondition::Lt => "LT",
151        }
152    }
153}
154
155/// EXPIRE key seconds \[NX | XX | GT | LT\]
156///
157/// Sets a timeout on `key`. Returns `true` if the timeout was set.
158#[derive(Clone)]
159pub struct Expire {
160    key: CommandArg,
161    seconds: u64,
162    condition: Option<ExpireCondition>,
163}
164
165impl Expire {
166    /// Create a new [`Expire`] command.
167    pub fn new(key: impl Into<CommandArg>, seconds: u64) -> Self {
168        Self {
169            key: key.into(),
170            seconds,
171            condition: None,
172        }
173    }
174
175    /// Set the condition flag (NX, XX, GT, or LT).
176    pub fn condition(mut self, condition: ExpireCondition) -> Self {
177        self.condition = Some(condition);
178        self
179    }
180}
181
182impl Command for Expire {
183    type Response = bool;
184
185    fn to_frame(&self) -> Frame {
186        let mut args = vec![
187            bulk("EXPIRE"),
188            bulk(&self.key),
189            bulk(self.seconds.to_string()),
190        ];
191        if let Some(condition) = self.condition {
192            args.push(bulk(condition.as_str()));
193        }
194        array(args)
195    }
196
197    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
198        match frame {
199            Frame::Integer(n) => Ok(n == 1),
200            Frame::Boolean(b) => Ok(b),
201            other => Err(RedisError::UnexpectedResponse {
202                expected: "integer or boolean",
203                actual: format!("{other:?}"),
204            }),
205        }
206    }
207
208    fn name(&self) -> &str {
209        "EXPIRE"
210    }
211}
212
213/// TTL key
214///
215/// Returns the remaining time to live of a key in seconds.
216/// Returns -2 if the key does not exist, -1 if no expiry is set.
217#[derive(Clone)]
218pub struct Ttl {
219    key: CommandArg,
220}
221
222impl Ttl {
223    /// Create a new [`Ttl`] command.
224    pub fn new(key: impl Into<CommandArg>) -> Self {
225        Self { key: key.into() }
226    }
227}
228
229impl Command for Ttl {
230    type Response = i64;
231
232    fn to_frame(&self) -> Frame {
233        array(vec![bulk("TTL"), bulk(&self.key)])
234    }
235
236    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
237        match frame {
238            Frame::Integer(n) => Ok(n),
239            other => Err(RedisError::UnexpectedResponse {
240                expected: "integer",
241                actual: format!("{other:?}"),
242            }),
243        }
244    }
245
246    fn name(&self) -> &str {
247        "TTL"
248    }
249
250    fn idempotent(&self) -> bool {
251        true
252    }
253}
254
255/// RENAME key newkey
256///
257/// Renames `key` to `newkey`. Errors if `key` does not exist.
258#[derive(Clone)]
259pub struct Rename {
260    key: CommandArg,
261    new_key: CommandArg,
262}
263
264impl Rename {
265    /// Create a new [`Rename`] command.
266    pub fn new(key: impl Into<CommandArg>, new_key: impl Into<CommandArg>) -> Self {
267        Self {
268            key: key.into(),
269            new_key: new_key.into(),
270        }
271    }
272}
273
274impl Command for Rename {
275    type Response = ();
276
277    fn to_frame(&self) -> Frame {
278        array(vec![bulk("RENAME"), bulk(&self.key), bulk(&self.new_key)])
279    }
280
281    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
282        match frame {
283            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
284            other => Err(RedisError::UnexpectedResponse {
285                expected: "OK",
286                actual: format!("{other:?}"),
287            }),
288        }
289    }
290
291    fn name(&self) -> &str {
292        "RENAME"
293    }
294}
295
296/// TYPE key
297///
298/// Returns the type of the value stored at `key` as a string
299/// (e.g., "string", "list", "set", "zset", "hash", "none").
300#[derive(Clone)]
301pub struct Type {
302    key: CommandArg,
303}
304
305impl Type {
306    /// Create a new [`Type`] command.
307    pub fn new(key: impl Into<CommandArg>) -> Self {
308        Self { key: key.into() }
309    }
310}
311
312impl Command for Type {
313    type Response = String;
314
315    fn to_frame(&self) -> Frame {
316        array(vec![bulk("TYPE"), bulk(&self.key)])
317    }
318
319    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
320        match frame {
321            Frame::SimpleString(s) => Ok(String::from_utf8_lossy(&s).into_owned()),
322            other => Err(RedisError::UnexpectedResponse {
323                expected: "simple string",
324                actual: format!("{other:?}"),
325            }),
326        }
327    }
328
329    fn name(&self) -> &str {
330        "TYPE"
331    }
332
333    fn idempotent(&self) -> bool {
334        true
335    }
336}
337
338/// UNLINK key [key ...]
339///
340/// Removes the specified keys without blocking the server.
341/// Returns the number of keys removed.
342#[derive(Clone)]
343pub struct Unlink {
344    keys: Vec<CommandArg>,
345}
346
347impl Unlink {
348    /// Create a new [`Unlink`] command.
349    pub fn new(key: impl Into<CommandArg>) -> Self {
350        Self {
351            keys: vec![key.into()],
352        }
353    }
354
355    /// Create the [`Unlink`] command for the supplied keys.
356    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
357        Self {
358            keys: keys.into_iter().map(Into::into).collect(),
359        }
360    }
361}
362
363impl Command for Unlink {
364    type Response = i64;
365
366    fn to_frame(&self) -> Frame {
367        let mut args = vec![bulk("UNLINK")];
368        for key in &self.keys {
369            args.push(bulk(key));
370        }
371        array(args)
372    }
373
374    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
375        match frame {
376            Frame::Integer(n) => Ok(n),
377            other => Err(RedisError::UnexpectedResponse {
378                expected: "integer",
379                actual: format!("{other:?}"),
380            }),
381        }
382    }
383
384    fn name(&self) -> &str {
385        "UNLINK"
386    }
387}
388
389/// PERSIST key
390///
391/// Removes the existing timeout on `key`. Returns `true` if the timeout was removed.
392#[derive(Clone)]
393pub struct Persist {
394    key: CommandArg,
395}
396
397impl Persist {
398    /// Create a new [`Persist`] command.
399    pub fn new(key: impl Into<CommandArg>) -> Self {
400        Self { key: key.into() }
401    }
402}
403
404impl Command for Persist {
405    type Response = bool;
406
407    fn to_frame(&self) -> Frame {
408        array(vec![bulk("PERSIST"), bulk(&self.key)])
409    }
410
411    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
412        match frame {
413            Frame::Integer(n) => Ok(n == 1),
414            Frame::Boolean(b) => Ok(b),
415            other => Err(RedisError::UnexpectedResponse {
416                expected: "integer or boolean",
417                actual: format!("{other:?}"),
418            }),
419        }
420    }
421
422    fn name(&self) -> &str {
423        "PERSIST"
424    }
425
426    fn idempotent(&self) -> bool {
427        true
428    }
429}
430
431/// PEXPIRE key milliseconds \[NX | XX | GT | LT\]
432///
433/// Sets a timeout on `key` in milliseconds. Returns `true` if the timeout was set.
434#[derive(Clone)]
435pub struct PExpire {
436    key: CommandArg,
437    milliseconds: u64,
438    condition: Option<ExpireCondition>,
439}
440
441impl PExpire {
442    /// Create a new [`PExpire`] command.
443    pub fn new(key: impl Into<CommandArg>, milliseconds: u64) -> Self {
444        Self {
445            key: key.into(),
446            milliseconds,
447            condition: None,
448        }
449    }
450
451    /// Set the condition flag (NX, XX, GT, or LT).
452    pub fn condition(mut self, condition: ExpireCondition) -> Self {
453        self.condition = Some(condition);
454        self
455    }
456}
457
458impl Command for PExpire {
459    type Response = bool;
460
461    fn to_frame(&self) -> Frame {
462        let mut args = vec![
463            bulk("PEXPIRE"),
464            bulk(&self.key),
465            bulk(self.milliseconds.to_string()),
466        ];
467        if let Some(condition) = self.condition {
468            args.push(bulk(condition.as_str()));
469        }
470        array(args)
471    }
472
473    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
474        match frame {
475            Frame::Integer(n) => Ok(n == 1),
476            Frame::Boolean(b) => Ok(b),
477            other => Err(RedisError::UnexpectedResponse {
478                expected: "integer or boolean",
479                actual: format!("{other:?}"),
480            }),
481        }
482    }
483
484    fn name(&self) -> &str {
485        "PEXPIRE"
486    }
487}
488
489/// PEXPIREAT key ms-timestamp \[NX | XX | GT | LT\]
490///
491/// Sets an expiry on `key` as an absolute Unix timestamp in milliseconds.
492/// Returns `true` if the timeout was set.
493#[derive(Clone)]
494pub struct PExpireAt {
495    key: CommandArg,
496    ms_timestamp: i64,
497    condition: Option<ExpireCondition>,
498}
499
500impl PExpireAt {
501    /// Create a new [`PExpireAt`] command.
502    pub fn new(key: impl Into<CommandArg>, ms_timestamp: i64) -> Self {
503        Self {
504            key: key.into(),
505            ms_timestamp,
506            condition: None,
507        }
508    }
509
510    /// Set the condition flag (NX, XX, GT, or LT).
511    pub fn condition(mut self, condition: ExpireCondition) -> Self {
512        self.condition = Some(condition);
513        self
514    }
515}
516
517impl Command for PExpireAt {
518    type Response = bool;
519
520    fn to_frame(&self) -> Frame {
521        let mut args = vec![
522            bulk("PEXPIREAT"),
523            bulk(&self.key),
524            bulk(self.ms_timestamp.to_string()),
525        ];
526        if let Some(condition) = self.condition {
527            args.push(bulk(condition.as_str()));
528        }
529        array(args)
530    }
531
532    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
533        match frame {
534            Frame::Integer(n) => Ok(n == 1),
535            Frame::Boolean(b) => Ok(b),
536            other => Err(RedisError::UnexpectedResponse {
537                expected: "integer or boolean",
538                actual: format!("{other:?}"),
539            }),
540        }
541    }
542
543    fn name(&self) -> &str {
544        "PEXPIREAT"
545    }
546}
547
548/// COPY source destination \[REPLACE\]
549///
550/// Copies the value stored at `source` to `destination`.
551/// Returns `true` if the key was copied.
552#[derive(Clone)]
553pub struct Copy {
554    source: CommandArg,
555    destination: CommandArg,
556    replace: bool,
557}
558
559impl Copy {
560    /// Create a new [`struct@Copy`] command.
561    pub fn new(source: impl Into<CommandArg>, destination: impl Into<CommandArg>) -> Self {
562        Self {
563            source: source.into(),
564            destination: destination.into(),
565            replace: false,
566        }
567    }
568
569    /// Configure the `replace` option.
570    pub fn replace(mut self) -> Self {
571        self.replace = true;
572        self
573    }
574}
575
576impl Command for Copy {
577    type Response = bool;
578
579    fn to_frame(&self) -> Frame {
580        let mut args = vec![bulk("COPY"), bulk(&self.source), bulk(&self.destination)];
581        if self.replace {
582            args.push(bulk("REPLACE"));
583        }
584        array(args)
585    }
586
587    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
588        match frame {
589            Frame::Integer(n) => Ok(n == 1),
590            Frame::Boolean(b) => Ok(b),
591            other => Err(RedisError::UnexpectedResponse {
592                expected: "integer or boolean",
593                actual: format!("{other:?}"),
594            }),
595        }
596    }
597
598    fn name(&self) -> &str {
599        "COPY"
600    }
601}
602
603/// KEYS pattern
604///
605/// Returns all keys matching `pattern`.
606#[derive(Clone)]
607pub struct Keys {
608    pattern: CommandArg,
609}
610
611impl Keys {
612    /// Create a new [`Keys`] command.
613    pub fn new(pattern: impl Into<CommandArg>) -> Self {
614        Self {
615            pattern: pattern.into(),
616        }
617    }
618}
619
620impl Command for Keys {
621    type Response = Vec<Bytes>;
622
623    fn to_frame(&self) -> Frame {
624        array(vec![bulk("KEYS"), bulk(&self.pattern)])
625    }
626
627    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
628        match frame {
629            Frame::Array(Some(frames)) => frames
630                .into_iter()
631                .map(|f| match f {
632                    Frame::BulkString(Some(data)) => Ok(data),
633                    other => Err(RedisError::UnexpectedResponse {
634                        expected: "bulk string",
635                        actual: format!("{other:?}"),
636                    }),
637                })
638                .collect(),
639            other => Err(RedisError::UnexpectedResponse {
640                expected: "array",
641                actual: format!("{other:?}"),
642            }),
643        }
644    }
645
646    fn name(&self) -> &str {
647        "KEYS"
648    }
649
650    fn idempotent(&self) -> bool {
651        true
652    }
653}
654
655/// RANDOMKEY
656///
657/// Returns a random key from the keyspace, or `None` if the database is empty.
658#[derive(Clone)]
659pub struct RandomKey;
660
661impl RandomKey {
662    /// Create a new [`RandomKey`] command.
663    pub fn new() -> Self {
664        Self
665    }
666}
667
668impl Default for RandomKey {
669    fn default() -> Self {
670        Self::new()
671    }
672}
673
674impl Command for RandomKey {
675    type Response = Option<Bytes>;
676
677    fn to_frame(&self) -> Frame {
678        array(vec![bulk("RANDOMKEY")])
679    }
680
681    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
682        match frame {
683            Frame::BulkString(data) => Ok(data),
684            Frame::Null => Ok(None),
685            other => Err(RedisError::UnexpectedResponse {
686                expected: "bulk string or null",
687                actual: format!("{other:?}"),
688            }),
689        }
690    }
691
692    fn name(&self) -> &str {
693        "RANDOMKEY"
694    }
695
696    fn idempotent(&self) -> bool {
697        true
698    }
699}
700
701/// TOUCH key [key ...]
702///
703/// Alters the last access time of the specified keys.
704/// Returns the number of keys that were touched.
705#[derive(Clone)]
706pub struct Touch {
707    keys: Vec<CommandArg>,
708}
709
710impl Touch {
711    /// Create a new [`Touch`] command.
712    pub fn new(key: impl Into<CommandArg>) -> Self {
713        Self {
714            keys: vec![key.into()],
715        }
716    }
717
718    /// Create the [`Touch`] command for the supplied keys.
719    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
720        Self {
721            keys: keys.into_iter().map(Into::into).collect(),
722        }
723    }
724}
725
726impl Command for Touch {
727    type Response = i64;
728
729    fn to_frame(&self) -> Frame {
730        let mut args = vec![bulk("TOUCH")];
731        for key in &self.keys {
732            args.push(bulk(key));
733        }
734        array(args)
735    }
736
737    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
738        match frame {
739            Frame::Integer(n) => Ok(n),
740            other => Err(RedisError::UnexpectedResponse {
741                expected: "integer",
742                actual: format!("{other:?}"),
743            }),
744        }
745    }
746
747    fn name(&self) -> &str {
748        "TOUCH"
749    }
750}
751
752/// EXPIRETIME key
753///
754/// Returns the absolute Unix timestamp (in seconds) at which the key will expire.
755/// Returns -1 if the key exists but has no expiry, -2 if the key does not exist.
756#[derive(Clone)]
757pub struct ExpireTime {
758    key: CommandArg,
759}
760
761impl ExpireTime {
762    /// Create a new [`ExpireTime`] command.
763    pub fn new(key: impl Into<CommandArg>) -> Self {
764        Self { key: key.into() }
765    }
766}
767
768impl Command for ExpireTime {
769    type Response = i64;
770
771    fn to_frame(&self) -> Frame {
772        array(vec![bulk("EXPIRETIME"), bulk(&self.key)])
773    }
774
775    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
776        match frame {
777            Frame::Integer(n) => Ok(n),
778            other => Err(RedisError::UnexpectedResponse {
779                expected: "integer",
780                actual: format!("{other:?}"),
781            }),
782        }
783    }
784
785    fn name(&self) -> &str {
786        "EXPIRETIME"
787    }
788
789    fn idempotent(&self) -> bool {
790        true
791    }
792}
793
794/// PEXPIRETIME key
795///
796/// Returns the absolute Unix timestamp (in milliseconds) at which the key will expire.
797/// Returns -1 if the key exists but has no expiry, -2 if the key does not exist.
798#[derive(Clone)]
799pub struct PExpireTime {
800    key: CommandArg,
801}
802
803impl PExpireTime {
804    /// Create a new [`PExpireTime`] command.
805    pub fn new(key: impl Into<CommandArg>) -> Self {
806        Self { key: key.into() }
807    }
808}
809
810impl Command for PExpireTime {
811    type Response = i64;
812
813    fn to_frame(&self) -> Frame {
814        array(vec![bulk("PEXPIRETIME"), bulk(&self.key)])
815    }
816
817    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
818        match frame {
819            Frame::Integer(n) => Ok(n),
820            other => Err(RedisError::UnexpectedResponse {
821                expected: "integer",
822                actual: format!("{other:?}"),
823            }),
824        }
825    }
826
827    fn name(&self) -> &str {
828        "PEXPIRETIME"
829    }
830
831    fn idempotent(&self) -> bool {
832        true
833    }
834}
835
836/// DUMP key
837///
838/// Returns a serialized version of the value stored at the specified key.
839/// Returns `None` if the key does not exist.
840#[derive(Clone)]
841pub struct Dump {
842    key: CommandArg,
843}
844
845impl Dump {
846    /// Create a new [`Dump`] command.
847    pub fn new(key: impl Into<CommandArg>) -> Self {
848        Self { key: key.into() }
849    }
850}
851
852impl Command for Dump {
853    type Response = Option<Bytes>;
854
855    fn to_frame(&self) -> Frame {
856        array(vec![bulk("DUMP"), bulk(&self.key)])
857    }
858
859    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
860        match frame {
861            Frame::BulkString(data) => Ok(data),
862            Frame::Null => Ok(None),
863            other => Err(RedisError::UnexpectedResponse {
864                expected: "bulk string or null",
865                actual: format!("{other:?}"),
866            }),
867        }
868    }
869
870    fn name(&self) -> &str {
871        "DUMP"
872    }
873
874    fn idempotent(&self) -> bool {
875        true
876    }
877}
878
879/// RESTORE key ttl serialized-value \[REPLACE\] \[ABSTTL\] \[IDLETIME seconds\] \[FREQ frequency\]
880///
881/// Deserializes a previously-dumped value and associates it with a key.
882/// The `ttl_ms` argument sets the time-to-live in milliseconds (0 for no expiry).
883#[derive(Clone)]
884pub struct Restore {
885    key: CommandArg,
886    ttl_ms: u64,
887    serialized_value: Bytes,
888    replace: bool,
889    absttl: bool,
890    idletime: Option<u64>,
891    freq: Option<u64>,
892}
893
894impl Restore {
895    /// Create a new [`Restore`] command.
896    pub fn new(
897        key: impl Into<CommandArg>,
898        ttl_ms: u64,
899        serialized_value: impl Into<Bytes>,
900    ) -> Self {
901        Self {
902            key: key.into(),
903            ttl_ms,
904            serialized_value: serialized_value.into(),
905            replace: false,
906            absttl: false,
907            idletime: None,
908            freq: None,
909        }
910    }
911
912    /// Configure the `replace` option.
913    pub fn replace(mut self) -> Self {
914        self.replace = true;
915        self
916    }
917
918    /// Configure the `absttl` option.
919    pub fn absttl(mut self) -> Self {
920        self.absttl = true;
921        self
922    }
923
924    /// Configure the `idletime` option.
925    pub fn idletime(mut self, seconds: u64) -> Self {
926        self.idletime = Some(seconds);
927        self
928    }
929
930    /// Configure the `freq` option.
931    pub fn freq(mut self, frequency: u64) -> Self {
932        self.freq = Some(frequency);
933        self
934    }
935}
936
937impl Command for Restore {
938    type Response = ();
939
940    fn to_frame(&self) -> Frame {
941        let mut args = vec![
942            bulk("RESTORE"),
943            bulk(&self.key),
944            bulk(self.ttl_ms.to_string()),
945            bulk(&self.serialized_value),
946        ];
947        if self.replace {
948            args.push(bulk("REPLACE"));
949        }
950        if self.absttl {
951            args.push(bulk("ABSTTL"));
952        }
953        if let Some(idle) = self.idletime {
954            args.push(bulk("IDLETIME"));
955            args.push(bulk(idle.to_string()));
956        }
957        if let Some(f) = self.freq {
958            args.push(bulk("FREQ"));
959            args.push(bulk(f.to_string()));
960        }
961        array(args)
962    }
963
964    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
965        match frame {
966            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
967            other => Err(RedisError::UnexpectedResponse {
968                expected: "OK",
969                actual: format!("{other:?}"),
970            }),
971        }
972    }
973
974    fn name(&self) -> &str {
975        "RESTORE"
976    }
977}
978
979/// Authentication used by [`Migrate`].
980#[derive(Debug, Clone, PartialEq, Eq)]
981enum MigrateAuth {
982    Password(Bytes),
983    UsernamePassword(Bytes, Bytes),
984}
985
986#[derive(Debug, Clone, PartialEq, Eq)]
987enum MigrateKeySelection {
988    Single(Bytes),
989    Multiple(Vec<Bytes>),
990}
991
992/// Result returned by [`Migrate`].
993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
994pub enum MigrateResult {
995    /// The selected keys were transferred successfully.
996    Ok,
997    /// None of the selected keys existed on the source server.
998    NoKey,
999}
1000
1001/// MIGRATE host port key destination-db timeout \[COPY\] \[REPLACE\]
1002/// \[AUTH password | AUTH2 username password\] \[KEYS key \[key ...\]\]
1003///
1004/// Atomically transfers one or more keys to another Redis server. Use
1005/// [`keys`](Self::keys) for the multi-key form; it emits the required empty
1006/// key argument followed by `KEYS` and the selected keys.
1007#[derive(Debug, Clone)]
1008pub struct Migrate {
1009    host: Bytes,
1010    port: u16,
1011    key_selection: MigrateKeySelection,
1012    destination_db: u64,
1013    timeout_ms: u64,
1014    copy: bool,
1015    replace: bool,
1016    auth: Option<MigrateAuth>,
1017}
1018
1019impl Migrate {
1020    /// Construct the single-key form of `MIGRATE`.
1021    ///
1022    /// Redis reserves the positional empty key as the marker for its multi-key
1023    /// syntax. An actual empty key is therefore encoded as `KEYS ""` so it
1024    /// retains its normal Redis key semantics.
1025    pub fn new(
1026        host: impl AsRef<[u8]>,
1027        port: u16,
1028        key: impl AsRef<[u8]>,
1029        destination_db: u64,
1030        timeout_ms: u64,
1031    ) -> Self {
1032        let key = Bytes::copy_from_slice(key.as_ref());
1033        let key_selection = if key.is_empty() {
1034            MigrateKeySelection::Multiple(vec![key])
1035        } else {
1036            MigrateKeySelection::Single(key)
1037        };
1038        Self {
1039            host: Bytes::copy_from_slice(host.as_ref()),
1040            port,
1041            key_selection,
1042            destination_db,
1043            timeout_ms,
1044            copy: false,
1045            replace: false,
1046            auth: None,
1047        }
1048    }
1049
1050    /// Construct the multi-key form of `MIGRATE` with one required key.
1051    ///
1052    /// Append further keys with [`key`](Self::key).
1053    pub fn keys(
1054        host: impl AsRef<[u8]>,
1055        port: u16,
1056        first_key: impl AsRef<[u8]>,
1057        destination_db: u64,
1058        timeout_ms: u64,
1059    ) -> Self {
1060        Self {
1061            host: Bytes::copy_from_slice(host.as_ref()),
1062            port,
1063            key_selection: MigrateKeySelection::Multiple(vec![Bytes::copy_from_slice(
1064                first_key.as_ref(),
1065            )]),
1066            destination_db,
1067            timeout_ms,
1068            copy: false,
1069            replace: false,
1070            auth: None,
1071        }
1072    }
1073
1074    /// Append another key to the multi-key `KEYS` form.
1075    ///
1076    /// When called on a single-key request, the builder transparently switches
1077    /// to the equivalent `KEYS` form and retains the original key first.
1078    pub fn key(mut self, key: impl AsRef<[u8]>) -> Self {
1079        let key = Bytes::copy_from_slice(key.as_ref());
1080        self.key_selection = match self.key_selection {
1081            MigrateKeySelection::Single(first) => MigrateKeySelection::Multiple(vec![first, key]),
1082            MigrateKeySelection::Multiple(mut keys) => {
1083                keys.push(key);
1084                MigrateKeySelection::Multiple(keys)
1085            }
1086        };
1087        self
1088    }
1089
1090    /// Leave the source keys in place after transferring them.
1091    pub fn copy(mut self) -> Self {
1092        self.copy = true;
1093        self
1094    }
1095
1096    /// Replace destination keys that already exist.
1097    pub fn replace(mut self) -> Self {
1098        self.replace = true;
1099        self
1100    }
1101
1102    /// Authenticate to the destination with a password.
1103    pub fn auth(mut self, password: impl AsRef<[u8]>) -> Self {
1104        self.auth = Some(MigrateAuth::Password(Bytes::copy_from_slice(
1105            password.as_ref(),
1106        )));
1107        self
1108    }
1109
1110    /// Authenticate to the destination with a username and password.
1111    pub fn auth2(mut self, username: impl AsRef<[u8]>, password: impl AsRef<[u8]>) -> Self {
1112        self.auth = Some(MigrateAuth::UsernamePassword(
1113            Bytes::copy_from_slice(username.as_ref()),
1114            Bytes::copy_from_slice(password.as_ref()),
1115        ));
1116        self
1117    }
1118}
1119
1120impl Command for Migrate {
1121    type Response = MigrateResult;
1122
1123    fn to_frame(&self) -> Frame {
1124        let positional_key = match &self.key_selection {
1125            MigrateKeySelection::Single(key) => bulk(key),
1126            MigrateKeySelection::Multiple(_) => bulk(""),
1127        };
1128        let mut args = vec![
1129            bulk("MIGRATE"),
1130            bulk(&self.host),
1131            bulk(self.port.to_string()),
1132            positional_key,
1133            bulk(self.destination_db.to_string()),
1134            bulk(self.timeout_ms.to_string()),
1135        ];
1136        if self.copy {
1137            args.push(bulk("COPY"));
1138        }
1139        if self.replace {
1140            args.push(bulk("REPLACE"));
1141        }
1142        match &self.auth {
1143            Some(MigrateAuth::Password(password)) => {
1144                args.push(bulk("AUTH"));
1145                args.push(bulk(password));
1146            }
1147            Some(MigrateAuth::UsernamePassword(username, password)) => {
1148                args.push(bulk("AUTH2"));
1149                args.push(bulk(username));
1150                args.push(bulk(password));
1151            }
1152            None => {}
1153        }
1154        if let MigrateKeySelection::Multiple(keys) = &self.key_selection {
1155            args.push(bulk("KEYS"));
1156            args.extend(keys.iter().map(bulk));
1157        }
1158        array(args)
1159    }
1160
1161    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1162        match frame {
1163            Frame::SimpleString(value) if value.eq_ignore_ascii_case(b"OK") => {
1164                Ok(MigrateResult::Ok)
1165            }
1166            Frame::SimpleString(value) if value.eq_ignore_ascii_case(b"NOKEY") => {
1167                Ok(MigrateResult::NoKey)
1168            }
1169            other => Err(RedisError::UnexpectedResponse {
1170                expected: "OK or NOKEY",
1171                actual: format!("{other:?}"),
1172            }),
1173        }
1174    }
1175
1176    fn name(&self) -> &str {
1177        "MIGRATE"
1178    }
1179}
1180
1181/// Sort order for SORT and SORT_RO commands.
1182#[derive(Clone)]
1183pub enum SortOrder {
1184    /// Select the `Asc` mode.
1185    Asc,
1186    /// Select the `Desc` mode.
1187    Desc,
1188}
1189
1190/// SORT key \[BY pattern\] \[GET pattern ...\] \[LIMIT offset count\] \[ASC|DESC\] \[ALPHA\] \[STORE destination\]
1191///
1192/// Sorts the elements in a list, set, or sorted set. When STORE is used, the
1193/// response is an integer (number of elements stored); otherwise it is an array
1194/// of bulk strings. The response type is `Frame` to accommodate both cases.
1195#[derive(Clone)]
1196pub struct Sort {
1197    key: CommandArg,
1198    by: Option<CommandArg>,
1199    get: Vec<CommandArg>,
1200    limit: Option<(i64, i64)>,
1201    order: Option<SortOrder>,
1202    alpha: bool,
1203    store: Option<CommandArg>,
1204}
1205
1206impl Sort {
1207    /// Create a new [`Sort`] command.
1208    pub fn new(key: impl Into<CommandArg>) -> Self {
1209        Self {
1210            key: key.into(),
1211            by: None,
1212            get: Vec::new(),
1213            limit: None,
1214            order: None,
1215            alpha: false,
1216            store: None,
1217        }
1218    }
1219
1220    /// Configure the `by` option.
1221    pub fn by(mut self, pattern: impl Into<CommandArg>) -> Self {
1222        self.by = Some(pattern.into());
1223        self
1224    }
1225
1226    /// Configure the `get` option.
1227    pub fn get(mut self, pattern: impl Into<CommandArg>) -> Self {
1228        self.get.push(pattern.into());
1229        self
1230    }
1231
1232    /// Configure the `limit` option.
1233    pub fn limit(mut self, offset: i64, count: i64) -> Self {
1234        self.limit = Some((offset, count));
1235        self
1236    }
1237
1238    /// Configure the `order` option.
1239    pub fn order(mut self, order: SortOrder) -> Self {
1240        self.order = Some(order);
1241        self
1242    }
1243
1244    /// Configure the `alpha` option.
1245    pub fn alpha(mut self) -> Self {
1246        self.alpha = true;
1247        self
1248    }
1249
1250    /// Configure the `store` option.
1251    pub fn store(mut self, destination: impl Into<CommandArg>) -> Self {
1252        self.store = Some(destination.into());
1253        self
1254    }
1255}
1256
1257impl Command for Sort {
1258    type Response = Frame;
1259
1260    fn to_frame(&self) -> Frame {
1261        let mut args = vec![bulk("SORT"), bulk(&self.key)];
1262        if let Some(ref pattern) = self.by {
1263            args.push(bulk("BY"));
1264            args.push(bulk(pattern));
1265        }
1266        for pattern in &self.get {
1267            args.push(bulk("GET"));
1268            args.push(bulk(pattern));
1269        }
1270        if let Some((offset, count)) = self.limit {
1271            args.push(bulk("LIMIT"));
1272            args.push(bulk(offset.to_string()));
1273            args.push(bulk(count.to_string()));
1274        }
1275        if let Some(ref order) = self.order {
1276            match order {
1277                SortOrder::Asc => args.push(bulk("ASC")),
1278                SortOrder::Desc => args.push(bulk("DESC")),
1279            }
1280        }
1281        if self.alpha {
1282            args.push(bulk("ALPHA"));
1283        }
1284        if let Some(ref dest) = self.store {
1285            args.push(bulk("STORE"));
1286            args.push(bulk(dest));
1287        }
1288        array(args)
1289    }
1290
1291    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1292        Ok(frame)
1293    }
1294
1295    fn name(&self) -> &str {
1296        "SORT"
1297    }
1298}
1299
1300/// SORT_RO key \[BY pattern\] \[GET pattern ...\] \[LIMIT offset count\] \[ASC|DESC\] \[ALPHA\]
1301///
1302/// Read-only variant of SORT. Returns the sorted elements without the STORE
1303/// option. Each element is returned as an `Option<Bytes>` (nil for missing
1304/// GET references).
1305#[derive(Clone)]
1306pub struct SortRo {
1307    key: CommandArg,
1308    by: Option<CommandArg>,
1309    get: Vec<CommandArg>,
1310    limit: Option<(i64, i64)>,
1311    order: Option<SortOrder>,
1312    alpha: bool,
1313}
1314
1315impl SortRo {
1316    /// Create a new [`SortRo`] command.
1317    pub fn new(key: impl Into<CommandArg>) -> Self {
1318        Self {
1319            key: key.into(),
1320            by: None,
1321            get: Vec::new(),
1322            limit: None,
1323            order: None,
1324            alpha: false,
1325        }
1326    }
1327
1328    /// Configure the `by` option.
1329    pub fn by(mut self, pattern: impl Into<CommandArg>) -> Self {
1330        self.by = Some(pattern.into());
1331        self
1332    }
1333
1334    /// Configure the `get` option.
1335    pub fn get(mut self, pattern: impl Into<CommandArg>) -> Self {
1336        self.get.push(pattern.into());
1337        self
1338    }
1339
1340    /// Configure the `limit` option.
1341    pub fn limit(mut self, offset: i64, count: i64) -> Self {
1342        self.limit = Some((offset, count));
1343        self
1344    }
1345
1346    /// Configure the `order` option.
1347    pub fn order(mut self, order: SortOrder) -> Self {
1348        self.order = Some(order);
1349        self
1350    }
1351
1352    /// Configure the `alpha` option.
1353    pub fn alpha(mut self) -> Self {
1354        self.alpha = true;
1355        self
1356    }
1357}
1358
1359impl Command for SortRo {
1360    type Response = Vec<Option<Bytes>>;
1361
1362    fn to_frame(&self) -> Frame {
1363        let mut args = vec![bulk("SORT_RO"), bulk(&self.key)];
1364        if let Some(ref pattern) = self.by {
1365            args.push(bulk("BY"));
1366            args.push(bulk(pattern));
1367        }
1368        for pattern in &self.get {
1369            args.push(bulk("GET"));
1370            args.push(bulk(pattern));
1371        }
1372        if let Some((offset, count)) = self.limit {
1373            args.push(bulk("LIMIT"));
1374            args.push(bulk(offset.to_string()));
1375            args.push(bulk(count.to_string()));
1376        }
1377        if let Some(ref order) = self.order {
1378            match order {
1379                SortOrder::Asc => args.push(bulk("ASC")),
1380                SortOrder::Desc => args.push(bulk("DESC")),
1381            }
1382        }
1383        if self.alpha {
1384            args.push(bulk("ALPHA"));
1385        }
1386        array(args)
1387    }
1388
1389    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1390        match frame {
1391            Frame::Array(Some(frames)) => frames
1392                .into_iter()
1393                .map(|f| match f {
1394                    Frame::BulkString(data) => Ok(data),
1395                    Frame::Null => Ok(None),
1396                    other => Err(RedisError::UnexpectedResponse {
1397                        expected: "bulk string or null",
1398                        actual: format!("{other:?}"),
1399                    }),
1400                })
1401                .collect(),
1402            other => Err(RedisError::UnexpectedResponse {
1403                expected: "array",
1404                actual: format!("{other:?}"),
1405            }),
1406        }
1407    }
1408
1409    fn name(&self) -> &str {
1410        "SORT_RO"
1411    }
1412
1413    fn idempotent(&self) -> bool {
1414        true
1415    }
1416}
1417
1418/// OBJECT ENCODING key
1419///
1420/// Returns the internal encoding of the Redis object stored at the key.
1421#[derive(Clone)]
1422pub struct ObjectEncoding {
1423    key: CommandArg,
1424}
1425
1426impl ObjectEncoding {
1427    /// Create a new [`ObjectEncoding`] command.
1428    pub fn new(key: impl Into<CommandArg>) -> Self {
1429        Self { key: key.into() }
1430    }
1431}
1432
1433impl Command for ObjectEncoding {
1434    type Response = String;
1435
1436    fn to_frame(&self) -> Frame {
1437        array(vec![bulk("OBJECT"), bulk("ENCODING"), bulk(&self.key)])
1438    }
1439
1440    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1441        match frame {
1442            Frame::BulkString(Some(s)) => Ok(String::from_utf8_lossy(&s).into_owned()),
1443            other => Err(RedisError::UnexpectedResponse {
1444                expected: "bulk string",
1445                actual: format!("{other:?}"),
1446            }),
1447        }
1448    }
1449
1450    fn name(&self) -> &str {
1451        "OBJECT ENCODING"
1452    }
1453
1454    fn idempotent(&self) -> bool {
1455        true
1456    }
1457}
1458
1459/// OBJECT FREQ key
1460///
1461/// Returns the logarithmic access frequency counter of a key (requires
1462/// maxmemory-policy to be set to an LFU policy).
1463#[derive(Clone)]
1464pub struct ObjectFreq {
1465    key: CommandArg,
1466}
1467
1468impl ObjectFreq {
1469    /// Create a new [`ObjectFreq`] command.
1470    pub fn new(key: impl Into<CommandArg>) -> Self {
1471        Self { key: key.into() }
1472    }
1473}
1474
1475impl Command for ObjectFreq {
1476    type Response = i64;
1477
1478    fn to_frame(&self) -> Frame {
1479        array(vec![bulk("OBJECT"), bulk("FREQ"), bulk(&self.key)])
1480    }
1481
1482    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1483        match frame {
1484            Frame::Integer(n) => Ok(n),
1485            other => Err(RedisError::UnexpectedResponse {
1486                expected: "integer",
1487                actual: format!("{other:?}"),
1488            }),
1489        }
1490    }
1491
1492    fn name(&self) -> &str {
1493        "OBJECT FREQ"
1494    }
1495
1496    fn idempotent(&self) -> bool {
1497        true
1498    }
1499}
1500
1501/// OBJECT HELP
1502///
1503/// Returns helpful text about the OBJECT subcommands.
1504#[derive(Clone)]
1505pub struct ObjectHelp;
1506
1507impl ObjectHelp {
1508    /// Create a new [`ObjectHelp`] command.
1509    pub fn new() -> Self {
1510        Self
1511    }
1512}
1513
1514impl Default for ObjectHelp {
1515    fn default() -> Self {
1516        Self::new()
1517    }
1518}
1519
1520impl Command for ObjectHelp {
1521    type Response = Vec<Bytes>;
1522
1523    fn to_frame(&self) -> Frame {
1524        array(vec![bulk("OBJECT"), bulk("HELP")])
1525    }
1526
1527    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1528        crate::help::parse_help_lines(frame)
1529    }
1530
1531    fn name(&self) -> &str {
1532        "OBJECT HELP"
1533    }
1534
1535    fn idempotent(&self) -> bool {
1536        true
1537    }
1538}
1539
1540/// OBJECT IDLETIME key
1541///
1542/// Returns the number of seconds since the object stored at the key is idle
1543/// (not accessed by read or write operations).
1544#[derive(Clone)]
1545pub struct ObjectIdleTime {
1546    key: CommandArg,
1547}
1548
1549impl ObjectIdleTime {
1550    /// Create a new [`ObjectIdleTime`] command.
1551    pub fn new(key: impl Into<CommandArg>) -> Self {
1552        Self { key: key.into() }
1553    }
1554}
1555
1556impl Command for ObjectIdleTime {
1557    type Response = i64;
1558
1559    fn to_frame(&self) -> Frame {
1560        array(vec![bulk("OBJECT"), bulk("IDLETIME"), bulk(&self.key)])
1561    }
1562
1563    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1564        match frame {
1565            Frame::Integer(n) => Ok(n),
1566            other => Err(RedisError::UnexpectedResponse {
1567                expected: "integer",
1568                actual: format!("{other:?}"),
1569            }),
1570        }
1571    }
1572
1573    fn name(&self) -> &str {
1574        "OBJECT IDLETIME"
1575    }
1576
1577    fn idempotent(&self) -> bool {
1578        true
1579    }
1580}
1581
1582/// OBJECT REFCOUNT key
1583///
1584/// Returns the number of references of the object stored at the key.
1585#[derive(Clone)]
1586pub struct ObjectRefCount {
1587    key: CommandArg,
1588}
1589
1590impl ObjectRefCount {
1591    /// Create a new [`ObjectRefCount`] command.
1592    pub fn new(key: impl Into<CommandArg>) -> Self {
1593        Self { key: key.into() }
1594    }
1595}
1596
1597impl Command for ObjectRefCount {
1598    type Response = i64;
1599
1600    fn to_frame(&self) -> Frame {
1601        array(vec![bulk("OBJECT"), bulk("REFCOUNT"), bulk(&self.key)])
1602    }
1603
1604    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1605        match frame {
1606            Frame::Integer(n) => Ok(n),
1607            other => Err(RedisError::UnexpectedResponse {
1608                expected: "integer",
1609                actual: format!("{other:?}"),
1610            }),
1611        }
1612    }
1613
1614    fn name(&self) -> &str {
1615        "OBJECT REFCOUNT"
1616    }
1617
1618    fn idempotent(&self) -> bool {
1619        true
1620    }
1621}
1622
1623/// EXPIREAT key unix-time-seconds \[NX | XX | GT | LT\]
1624///
1625/// Sets an expiry on `key` as an absolute Unix timestamp in seconds.
1626/// Returns `true` if the timeout was set.
1627#[derive(Clone)]
1628pub struct ExpireAt {
1629    key: CommandArg,
1630    timestamp: i64,
1631    condition: Option<ExpireCondition>,
1632}
1633
1634impl ExpireAt {
1635    /// Create a new [`ExpireAt`] command.
1636    pub fn new(key: impl Into<CommandArg>, timestamp: i64) -> Self {
1637        Self {
1638            key: key.into(),
1639            timestamp,
1640            condition: None,
1641        }
1642    }
1643
1644    /// Set the condition flag (NX, XX, GT, or LT).
1645    pub fn condition(mut self, condition: ExpireCondition) -> Self {
1646        self.condition = Some(condition);
1647        self
1648    }
1649}
1650
1651impl Command for ExpireAt {
1652    type Response = bool;
1653
1654    fn to_frame(&self) -> Frame {
1655        let mut args = vec![
1656            bulk("EXPIREAT"),
1657            bulk(&self.key),
1658            bulk(self.timestamp.to_string()),
1659        ];
1660        if let Some(condition) = self.condition {
1661            args.push(bulk(condition.as_str()));
1662        }
1663        array(args)
1664    }
1665
1666    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1667        match frame {
1668            Frame::Integer(n) => Ok(n == 1),
1669            Frame::Boolean(b) => Ok(b),
1670            other => Err(RedisError::UnexpectedResponse {
1671                expected: "integer or boolean",
1672                actual: format!("{other:?}"),
1673            }),
1674        }
1675    }
1676
1677    fn name(&self) -> &str {
1678        "EXPIREAT"
1679    }
1680}
1681
1682/// PTTL key
1683///
1684/// Returns the remaining time to live of a key in milliseconds.
1685/// Returns -2 if the key does not exist, -1 if no expiry is set.
1686#[derive(Clone)]
1687pub struct Pttl {
1688    key: CommandArg,
1689}
1690
1691impl Pttl {
1692    /// Create a new [`Pttl`] command.
1693    pub fn new(key: impl Into<CommandArg>) -> Self {
1694        Self { key: key.into() }
1695    }
1696}
1697
1698impl Command for Pttl {
1699    type Response = i64;
1700
1701    fn to_frame(&self) -> Frame {
1702        array(vec![bulk("PTTL"), bulk(&self.key)])
1703    }
1704
1705    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1706        match frame {
1707            Frame::Integer(n) => Ok(n),
1708            other => Err(RedisError::UnexpectedResponse {
1709                expected: "integer",
1710                actual: format!("{other:?}"),
1711            }),
1712        }
1713    }
1714
1715    fn name(&self) -> &str {
1716        "PTTL"
1717    }
1718
1719    fn idempotent(&self) -> bool {
1720        true
1721    }
1722}
1723
1724/// RENAMENX key newkey
1725///
1726/// Renames `key` to `newkey`, only if `newkey` does not yet exist.
1727/// Returns `true` if the key was renamed.
1728#[derive(Clone)]
1729pub struct RenameNx {
1730    key: CommandArg,
1731    new_key: CommandArg,
1732}
1733
1734impl RenameNx {
1735    /// Create a new [`RenameNx`] command.
1736    pub fn new(key: impl Into<CommandArg>, new_key: impl Into<CommandArg>) -> Self {
1737        Self {
1738            key: key.into(),
1739            new_key: new_key.into(),
1740        }
1741    }
1742}
1743
1744impl Command for RenameNx {
1745    type Response = bool;
1746
1747    fn to_frame(&self) -> Frame {
1748        array(vec![bulk("RENAMENX"), bulk(&self.key), bulk(&self.new_key)])
1749    }
1750
1751    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1752        match frame {
1753            Frame::Integer(n) => Ok(n == 1),
1754            Frame::Boolean(b) => Ok(b),
1755            other => Err(RedisError::UnexpectedResponse {
1756                expected: "integer or boolean",
1757                actual: format!("{other:?}"),
1758            }),
1759        }
1760    }
1761
1762    fn name(&self) -> &str {
1763        "RENAMENX"
1764    }
1765}
1766
1767/// MOVE key db
1768///
1769/// Moves `key` from the currently selected database to the specified
1770/// destination database. Returns `true` if the key was moved.
1771#[derive(Clone)]
1772pub struct Move {
1773    key: CommandArg,
1774    db: u16,
1775}
1776
1777impl Move {
1778    /// Create a new [`Move`] command.
1779    pub fn new(key: impl Into<CommandArg>, db: u16) -> Self {
1780        Self {
1781            key: key.into(),
1782            db,
1783        }
1784    }
1785}
1786
1787impl Command for Move {
1788    type Response = bool;
1789
1790    fn to_frame(&self) -> Frame {
1791        array(vec![
1792            bulk("MOVE"),
1793            bulk(&self.key),
1794            bulk(self.db.to_string()),
1795        ])
1796    }
1797
1798    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1799        match frame {
1800            Frame::Integer(n) => Ok(n == 1),
1801            Frame::Boolean(b) => Ok(b),
1802            other => Err(RedisError::UnexpectedResponse {
1803                expected: "integer or boolean",
1804                actual: format!("{other:?}"),
1805            }),
1806        }
1807    }
1808
1809    fn name(&self) -> &str {
1810        "MOVE"
1811    }
1812}
1813
1814#[cfg(test)]
1815mod tests {
1816    use super::*;
1817    use redis_tower_core::Command;
1818    use redis_tower_protocol::Frame;
1819    use redis_tower_protocol::helpers::{array, bulk};
1820
1821    // -- Del --
1822
1823    #[test]
1824    fn del_single_to_frame() {
1825        let cmd = Del::new("mykey");
1826        assert_eq!(cmd.to_frame(), array(vec![bulk("DEL"), bulk("mykey")]));
1827    }
1828
1829    #[test]
1830    fn del_multiple_to_frame() {
1831        let cmd = Del::keys(vec!["a", "b", "c"]);
1832        assert_eq!(
1833            cmd.to_frame(),
1834            array(vec![bulk("DEL"), bulk("a"), bulk("b"), bulk("c")])
1835        );
1836    }
1837
1838    #[test]
1839    fn del_parse_integer() {
1840        let cmd = Del::new("mykey");
1841        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
1842    }
1843
1844    #[test]
1845    fn del_parse_error_on_string() {
1846        let cmd = Del::new("mykey");
1847        assert!(
1848            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1849                .is_err()
1850        );
1851    }
1852
1853    // -- Exists --
1854
1855    #[test]
1856    fn exists_to_frame() {
1857        let cmd = Exists::new("k");
1858        assert_eq!(cmd.to_frame(), array(vec![bulk("EXISTS"), bulk("k")]));
1859    }
1860
1861    #[test]
1862    fn exists_multiple_to_frame() {
1863        let cmd = Exists::keys(vec!["a", "b"]);
1864        assert_eq!(
1865            cmd.to_frame(),
1866            array(vec![bulk("EXISTS"), bulk("a"), bulk("b")])
1867        );
1868    }
1869
1870    #[test]
1871    fn exists_parse_integer() {
1872        let cmd = Exists::new("k");
1873        assert_eq!(cmd.parse_response(Frame::Integer(2)).unwrap(), 2);
1874    }
1875
1876    // -- Expire --
1877
1878    #[test]
1879    fn expire_to_frame() {
1880        let cmd = Expire::new("k", 60);
1881        assert_eq!(
1882            cmd.to_frame(),
1883            array(vec![bulk("EXPIRE"), bulk("k"), bulk("60")])
1884        );
1885    }
1886
1887    #[test]
1888    fn expire_parse_true() {
1889        let cmd = Expire::new("k", 60);
1890        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
1891    }
1892
1893    #[test]
1894    fn expire_parse_false() {
1895        let cmd = Expire::new("k", 60);
1896        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
1897    }
1898
1899    #[test]
1900    fn expire_parse_boolean() {
1901        let cmd = Expire::new("k", 60);
1902        assert!(cmd.parse_response(Frame::Boolean(true)).unwrap());
1903    }
1904
1905    // -- Ttl --
1906
1907    #[test]
1908    fn ttl_to_frame() {
1909        let cmd = Ttl::new("k");
1910        assert_eq!(cmd.to_frame(), array(vec![bulk("TTL"), bulk("k")]));
1911    }
1912
1913    #[test]
1914    fn ttl_parse_integer() {
1915        let cmd = Ttl::new("k");
1916        assert_eq!(cmd.parse_response(Frame::Integer(-2)).unwrap(), -2);
1917    }
1918
1919    // -- Type --
1920
1921    #[test]
1922    fn type_to_frame() {
1923        let cmd = Type::new("k");
1924        assert_eq!(cmd.to_frame(), array(vec![bulk("TYPE"), bulk("k")]));
1925    }
1926
1927    #[test]
1928    fn type_parse_simple_string() {
1929        let cmd = Type::new("k");
1930        let frame = Frame::SimpleString(Bytes::from("string"));
1931        assert_eq!(cmd.parse_response(frame).unwrap(), "string");
1932    }
1933
1934    #[test]
1935    fn type_parse_error_on_integer() {
1936        let cmd = Type::new("k");
1937        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
1938    }
1939
1940    // -- Rename --
1941
1942    #[test]
1943    fn rename_to_frame() {
1944        let cmd = Rename::new("old", "new");
1945        assert_eq!(
1946            cmd.to_frame(),
1947            array(vec![bulk("RENAME"), bulk("old"), bulk("new")])
1948        );
1949    }
1950
1951    #[test]
1952    fn rename_parse_ok() {
1953        let cmd = Rename::new("old", "new");
1954        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1955            .unwrap();
1956    }
1957
1958    // -- Copy --
1959
1960    #[test]
1961    fn copy_to_frame() {
1962        let cmd = Copy::new("src", "dst");
1963        assert_eq!(
1964            cmd.to_frame(),
1965            array(vec![bulk("COPY"), bulk("src"), bulk("dst")])
1966        );
1967    }
1968
1969    #[test]
1970    fn copy_replace_to_frame() {
1971        let cmd = Copy::new("src", "dst").replace();
1972        assert_eq!(
1973            cmd.to_frame(),
1974            array(vec![
1975                bulk("COPY"),
1976                bulk("src"),
1977                bulk("dst"),
1978                bulk("REPLACE")
1979            ])
1980        );
1981    }
1982
1983    #[test]
1984    fn copy_parse_true() {
1985        let cmd = Copy::new("src", "dst");
1986        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
1987    }
1988
1989    // -- Keys --
1990
1991    #[test]
1992    fn keys_to_frame() {
1993        let cmd = Keys::new("user:*");
1994        assert_eq!(cmd.to_frame(), array(vec![bulk("KEYS"), bulk("user:*")]));
1995    }
1996
1997    #[test]
1998    fn keys_parse_array() {
1999        let cmd = Keys::new("*");
2000        let frame = array(vec![
2001            Frame::BulkString(Some(Bytes::from("k1"))),
2002            Frame::BulkString(Some(Bytes::from("k2"))),
2003        ]);
2004        let result = cmd.parse_response(frame).unwrap();
2005        assert_eq!(result, vec![Bytes::from("k1"), Bytes::from("k2")]);
2006    }
2007
2008    // -- Sort --
2009
2010    #[test]
2011    fn sort_with_options_to_frame() {
2012        let cmd = Sort::new("mylist")
2013            .by("weight_*")
2014            .limit(0, 10)
2015            .order(SortOrder::Desc)
2016            .alpha();
2017        match cmd.to_frame() {
2018            Frame::Array(Some(args)) => {
2019                assert_eq!(args[0], bulk("SORT"));
2020                assert_eq!(args[1], bulk("mylist"));
2021                assert_eq!(args[2], bulk("BY"));
2022                assert_eq!(args[3], bulk("weight_*"));
2023                assert!(args.contains(&bulk("DESC")));
2024                assert!(args.contains(&bulk("ALPHA")));
2025            }
2026            _ => panic!("expected array"),
2027        }
2028    }
2029
2030    // -- ObjectEncoding --
2031
2032    #[test]
2033    fn object_encoding_to_frame() {
2034        let cmd = ObjectEncoding::new("mykey");
2035        assert_eq!(
2036            cmd.to_frame(),
2037            array(vec![bulk("OBJECT"), bulk("ENCODING"), bulk("mykey")])
2038        );
2039    }
2040
2041    #[test]
2042    fn object_encoding_parse_response() {
2043        let cmd = ObjectEncoding::new("mykey");
2044        let frame = Frame::BulkString(Some(Bytes::from("ziplist")));
2045        assert_eq!(cmd.parse_response(frame).unwrap(), "ziplist");
2046    }
2047
2048    // -- Persist --
2049
2050    #[test]
2051    fn persist_to_frame() {
2052        let cmd = Persist::new("k");
2053        assert_eq!(cmd.to_frame(), array(vec![bulk("PERSIST"), bulk("k")]));
2054    }
2055
2056    // -- RandomKey --
2057
2058    #[test]
2059    fn randomkey_to_frame() {
2060        let cmd = RandomKey::new();
2061        assert_eq!(cmd.to_frame(), array(vec![bulk("RANDOMKEY")]));
2062    }
2063
2064    #[test]
2065    fn randomkey_parse_null() {
2066        let cmd = RandomKey::new();
2067        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
2068    }
2069
2070    // -- Expire with condition --
2071
2072    #[test]
2073    fn expire_with_condition_to_frame() {
2074        let cmd = Expire::new("k", 60).condition(ExpireCondition::Nx);
2075        assert_eq!(
2076            cmd.to_frame(),
2077            array(vec![bulk("EXPIRE"), bulk("k"), bulk("60"), bulk("NX")])
2078        );
2079    }
2080
2081    #[test]
2082    fn pexpire_with_condition_to_frame() {
2083        let cmd = PExpire::new("k", 1000).condition(ExpireCondition::Gt);
2084        assert_eq!(
2085            cmd.to_frame(),
2086            array(vec![bulk("PEXPIRE"), bulk("k"), bulk("1000"), bulk("GT")])
2087        );
2088    }
2089
2090    #[test]
2091    fn pexpireat_with_condition_to_frame() {
2092        let cmd = PExpireAt::new("k", 99999).condition(ExpireCondition::Lt);
2093        assert_eq!(
2094            cmd.to_frame(),
2095            array(vec![
2096                bulk("PEXPIREAT"),
2097                bulk("k"),
2098                bulk("99999"),
2099                bulk("LT")
2100            ])
2101        );
2102    }
2103
2104    // -- ExpireAt --
2105
2106    #[test]
2107    fn expireat_to_frame() {
2108        let cmd = ExpireAt::new("k", 1700000000);
2109        assert_eq!(
2110            cmd.to_frame(),
2111            array(vec![bulk("EXPIREAT"), bulk("k"), bulk("1700000000")])
2112        );
2113    }
2114
2115    #[test]
2116    fn expireat_with_condition_to_frame() {
2117        let cmd = ExpireAt::new("k", 1700000000).condition(ExpireCondition::Xx);
2118        assert_eq!(
2119            cmd.to_frame(),
2120            array(vec![
2121                bulk("EXPIREAT"),
2122                bulk("k"),
2123                bulk("1700000000"),
2124                bulk("XX")
2125            ])
2126        );
2127    }
2128
2129    #[test]
2130    fn expireat_parse_true() {
2131        let cmd = ExpireAt::new("k", 1700000000);
2132        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2133    }
2134
2135    // -- Pttl --
2136
2137    #[test]
2138    fn pttl_to_frame() {
2139        let cmd = Pttl::new("k");
2140        assert_eq!(cmd.to_frame(), array(vec![bulk("PTTL"), bulk("k")]));
2141    }
2142
2143    #[test]
2144    fn pttl_parse_integer() {
2145        let cmd = Pttl::new("k");
2146        assert_eq!(cmd.parse_response(Frame::Integer(1500)).unwrap(), 1500);
2147    }
2148
2149    // -- RenameNx --
2150
2151    #[test]
2152    fn renamenx_to_frame() {
2153        let cmd = RenameNx::new("old", "new");
2154        assert_eq!(
2155            cmd.to_frame(),
2156            array(vec![bulk("RENAMENX"), bulk("old"), bulk("new")])
2157        );
2158    }
2159
2160    #[test]
2161    fn renamenx_parse_true() {
2162        let cmd = RenameNx::new("old", "new");
2163        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2164    }
2165
2166    #[test]
2167    fn renamenx_parse_false() {
2168        let cmd = RenameNx::new("old", "new");
2169        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
2170    }
2171
2172    // -- Move --
2173
2174    #[test]
2175    fn move_to_frame() {
2176        let cmd = Move::new("k", 1);
2177        assert_eq!(
2178            cmd.to_frame(),
2179            array(vec![bulk("MOVE"), bulk("k"), bulk("1")])
2180        );
2181    }
2182
2183    #[test]
2184    fn move_parse_true() {
2185        let cmd = Move::new("k", 1);
2186        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2187    }
2188
2189    // -- Migrate --
2190
2191    #[test]
2192    fn migrate_single_key_with_options_is_binary_safe() {
2193        let cmd = Migrate::new(b"127.0.0.1", 6380, b"source\0key", 2, 5_000)
2194            .copy()
2195            .replace()
2196            .auth(b"secret\0password");
2197        assert_eq!(
2198            cmd.to_frame(),
2199            array(vec![
2200                bulk("MIGRATE"),
2201                bulk("127.0.0.1"),
2202                bulk("6380"),
2203                bulk(b"source\0key"),
2204                bulk("2"),
2205                bulk("5000"),
2206                bulk("COPY"),
2207                bulk("REPLACE"),
2208                bulk("AUTH"),
2209                bulk(b"secret\0password"),
2210            ])
2211        );
2212        assert_eq!(cmd.name(), "MIGRATE");
2213        assert!(!cmd.idempotent());
2214    }
2215
2216    #[test]
2217    fn migrate_multiple_keys_and_auth2() {
2218        let cmd = Migrate::keys("redis.internal", 6379, b"key\0one", 0, 750)
2219            .key(b"key\0two")
2220            .auth2(b"user\0name", b"pass\0word");
2221        assert_eq!(
2222            cmd.to_frame(),
2223            array(vec![
2224                bulk("MIGRATE"),
2225                bulk("redis.internal"),
2226                bulk("6379"),
2227                bulk(""),
2228                bulk("0"),
2229                bulk("750"),
2230                bulk("AUTH2"),
2231                bulk(b"user\0name"),
2232                bulk(b"pass\0word"),
2233                bulk("KEYS"),
2234                bulk(b"key\0one"),
2235                bulk(b"key\0two"),
2236            ])
2237        );
2238    }
2239
2240    #[test]
2241    fn migrate_empty_key_uses_the_explicit_keys_form() {
2242        let cmd = Migrate::new("127.0.0.1", 6380, b"", 0, 5_000);
2243        assert_eq!(
2244            cmd.to_frame(),
2245            array(vec![
2246                bulk("MIGRATE"),
2247                bulk("127.0.0.1"),
2248                bulk("6380"),
2249                bulk(""),
2250                bulk("0"),
2251                bulk("5000"),
2252                bulk("KEYS"),
2253                bulk(""),
2254            ])
2255        );
2256    }
2257
2258    #[test]
2259    fn migrate_parses_ok_and_nokey() {
2260        let cmd = Migrate::new("localhost", 6379, "key", 0, 1_000);
2261        assert_eq!(
2262            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2263                .unwrap(),
2264            MigrateResult::Ok
2265        );
2266        assert_eq!(
2267            cmd.parse_response(Frame::SimpleString(Bytes::from("NOKEY")))
2268                .unwrap(),
2269            MigrateResult::NoKey
2270        );
2271        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2272    }
2273}