Skip to main content

redis_tower_commands/
hashes.rs

1//! Hash fields, field expiry, and numeric updates.
2//!
3//! Single-field reads such as [`HGet`] return `Option<Bytes>`; collection
4//! reads preserve Redis's field/value structure, and mutation/count commands
5//! return typed integers or booleans. Field-expiry commands require a Redis
6//! version that implements them.
7//!
8//! ```
9//! use redis_tower_commands::{HGet, HSet};
10//! use redis_tower_core::Command;
11//!
12//! let set = HSet::new("user:1", "name", "Ada");
13//! let get = HGet::new("user:1", "name");
14//! assert_eq!((set.name(), get.name()), ("HSET", "HGET"));
15//! ```
16//!
17//! See the [command cookbook] for nil, empty, and binary response handling.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#typed-commands-and-response-shapes
20
21use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25use crate::CommandArg;
26
27/// HGET key field
28///
29/// Returns the value associated with `field` in the hash stored at `key`,
30/// or `None` if the field or key does not exist.
31#[derive(Clone)]
32pub struct HGet {
33    key: CommandArg,
34    field: CommandArg,
35}
36
37impl HGet {
38    /// Create a new [`HGet`] command.
39    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>) -> Self {
40        Self {
41            key: key.into(),
42            field: field.into(),
43        }
44    }
45}
46
47impl Command for HGet {
48    type Response = Option<Bytes>;
49
50    fn to_frame(&self) -> Frame {
51        array(vec![
52            bulk("HGET"),
53            bulk(self.key.as_bytes()),
54            bulk(self.field.as_bytes()),
55        ])
56    }
57
58    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
59        match frame {
60            Frame::BulkString(data) => Ok(data),
61            Frame::Null => Ok(None),
62            other => Err(RedisError::UnexpectedResponse {
63                expected: "bulk string or null",
64                actual: format!("{other:?}"),
65            }),
66        }
67    }
68
69    fn name(&self) -> &str {
70        "HGET"
71    }
72
73    fn idempotent(&self) -> bool {
74        true
75    }
76}
77
78/// HSET key field value \[field value ...\]
79///
80/// Sets one or more field-value pairs in the hash stored at `key`.
81/// Returns the number of fields that were added (not updated).
82#[derive(Clone)]
83pub struct HSet {
84    key: CommandArg,
85    fields: Vec<(CommandArg, CommandArg)>,
86}
87
88impl HSet {
89    /// Create a new [`HSet`] command.
90    pub fn new(
91        key: impl Into<CommandArg>,
92        field: impl Into<CommandArg>,
93        value: impl Into<CommandArg>,
94    ) -> Self {
95        Self {
96            key: key.into(),
97            fields: vec![(field.into(), value.into())],
98        }
99    }
100
101    /// Constructs an [`HSet`] from an iterator of `(field, value)` pairs.
102    ///
103    /// This is the bulk-insert constructor: equivalent to calling `.field()` for every
104    /// pair in the iterator. Accepts any `IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>`,
105    /// including `HashMap`, `Vec<(&str, &str)>`, and similar collections.
106    ///
107    /// Produces the same wire frame as the incremental builder:
108    ///
109    /// ```no_run
110    /// use redis_tower_commands::HSet;
111    /// use redis_tower_core::Command;
112    ///
113    /// // These two are equivalent:
114    /// let a = HSet::new("h", "f1", "v1").field("f2", "v2");
115    /// let b = HSet::from_fields("h", [("f1", "v1"), ("f2", "v2")]);
116    /// assert_eq!(a.to_frame(), b.to_frame());
117    /// ```
118    pub fn from_fields(
119        key: impl Into<CommandArg>,
120        fields: impl IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>,
121    ) -> Self {
122        Self {
123            key: key.into(),
124            fields: fields
125                .into_iter()
126                .map(|(f, v)| (f.into(), v.into()))
127                .collect(),
128        }
129    }
130
131    /// Add an additional field-value pair.
132    pub fn field(mut self, name: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
133        self.fields.push((name.into(), value.into()));
134        self
135    }
136}
137
138impl Command for HSet {
139    type Response = i64;
140
141    fn to_frame(&self) -> Frame {
142        let mut args = vec![bulk("HSET"), bulk(self.key.as_bytes())];
143        for (field, value) in &self.fields {
144            args.push(bulk(field.as_bytes()));
145            args.push(bulk(value.as_bytes()));
146        }
147        array(args)
148    }
149
150    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
151        match frame {
152            Frame::Integer(n) => Ok(n),
153            other => Err(RedisError::UnexpectedResponse {
154                expected: "integer",
155                actual: format!("{other:?}"),
156            }),
157        }
158    }
159
160    fn name(&self) -> &str {
161        "HSET"
162    }
163}
164
165/// HDEL key field \[field ...\]
166///
167/// Removes the specified fields from the hash stored at `key`.
168/// Returns the number of fields that were removed.
169#[derive(Clone)]
170pub struct HDel {
171    key: CommandArg,
172    fields: Vec<CommandArg>,
173}
174
175impl HDel {
176    /// Create a new [`HDel`] command.
177    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>) -> Self {
178        Self {
179            key: key.into(),
180            fields: vec![field.into()],
181        }
182    }
183
184    /// Create the [`HDel`] command for the supplied fields.
185    pub fn fields(
186        key: impl Into<CommandArg>,
187        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
188    ) -> Self {
189        Self {
190            key: key.into(),
191            fields: fields.into_iter().map(Into::into).collect(),
192        }
193    }
194}
195
196impl Command for HDel {
197    type Response = i64;
198
199    fn to_frame(&self) -> Frame {
200        let mut args = vec![bulk("HDEL"), bulk(self.key.as_bytes())];
201        for field in &self.fields {
202            args.push(bulk(field.as_bytes()));
203        }
204        array(args)
205    }
206
207    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
208        match frame {
209            Frame::Integer(n) => Ok(n),
210            other => Err(RedisError::UnexpectedResponse {
211                expected: "integer",
212                actual: format!("{other:?}"),
213            }),
214        }
215    }
216
217    fn name(&self) -> &str {
218        "HDEL"
219    }
220}
221
222/// HEXISTS key field
223///
224/// Returns `true` if `field` exists in the hash stored at `key`.
225#[derive(Clone)]
226pub struct HExists {
227    key: CommandArg,
228    field: CommandArg,
229}
230
231impl HExists {
232    /// Create a new [`HExists`] command.
233    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>) -> Self {
234        Self {
235            key: key.into(),
236            field: field.into(),
237        }
238    }
239}
240
241impl Command for HExists {
242    type Response = bool;
243
244    fn to_frame(&self) -> Frame {
245        array(vec![
246            bulk("HEXISTS"),
247            bulk(self.key.as_bytes()),
248            bulk(self.field.as_bytes()),
249        ])
250    }
251
252    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
253        match frame {
254            Frame::Integer(n) => Ok(n == 1),
255            Frame::Boolean(b) => Ok(b),
256            other => Err(RedisError::UnexpectedResponse {
257                expected: "integer or boolean",
258                actual: format!("{other:?}"),
259            }),
260        }
261    }
262
263    fn name(&self) -> &str {
264        "HEXISTS"
265    }
266
267    fn idempotent(&self) -> bool {
268        true
269    }
270}
271
272/// HGETALL key
273///
274/// Returns all fields and values of the hash stored at `key` as a list
275/// of `(field, value)` pairs.
276#[derive(Clone)]
277pub struct HGetAll {
278    key: CommandArg,
279}
280
281impl HGetAll {
282    /// Create a new [`HGetAll`] command.
283    pub fn new(key: impl Into<CommandArg>) -> Self {
284        Self { key: key.into() }
285    }
286}
287
288impl Command for HGetAll {
289    type Response = Vec<(Bytes, Bytes)>;
290
291    fn to_frame(&self) -> Frame {
292        array(vec![bulk("HGETALL"), bulk(self.key.as_bytes())])
293    }
294
295    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
296        match frame {
297            Frame::Array(Some(frames)) => {
298                if frames.len() % 2 != 0 {
299                    return Err(RedisError::UnexpectedResponse {
300                        expected: "array with even number of elements",
301                        actual: format!("array with {} elements", frames.len()),
302                    });
303                }
304                let mut pairs = Vec::with_capacity(frames.len() / 2);
305                let mut iter = frames.into_iter();
306                while let (Some(field), Some(value)) = (iter.next(), iter.next()) {
307                    let field = match field {
308                        Frame::BulkString(Some(data)) => data,
309                        other => {
310                            return Err(RedisError::UnexpectedResponse {
311                                expected: "bulk string",
312                                actual: format!("{other:?}"),
313                            });
314                        }
315                    };
316                    let value = match value {
317                        Frame::BulkString(Some(data)) => data,
318                        other => {
319                            return Err(RedisError::UnexpectedResponse {
320                                expected: "bulk string",
321                                actual: format!("{other:?}"),
322                            });
323                        }
324                    };
325                    pairs.push((field, value));
326                }
327                Ok(pairs)
328            }
329            Frame::Map(entries) => {
330                let mut pairs = Vec::with_capacity(entries.len());
331                for (k, v) in entries {
332                    let field = match k {
333                        Frame::BulkString(Some(data)) => data,
334                        other => {
335                            return Err(RedisError::UnexpectedResponse {
336                                expected: "bulk string",
337                                actual: format!("{other:?}"),
338                            });
339                        }
340                    };
341                    let value = match v {
342                        Frame::BulkString(Some(data)) => data,
343                        other => {
344                            return Err(RedisError::UnexpectedResponse {
345                                expected: "bulk string",
346                                actual: format!("{other:?}"),
347                            });
348                        }
349                    };
350                    pairs.push((field, value));
351                }
352                Ok(pairs)
353            }
354            other => Err(RedisError::UnexpectedResponse {
355                expected: "array or map",
356                actual: format!("{other:?}"),
357            }),
358        }
359    }
360
361    fn name(&self) -> &str {
362        "HGETALL"
363    }
364
365    fn idempotent(&self) -> bool {
366        true
367    }
368}
369
370/// HINCRBY key field increment
371///
372/// Increments the integer value of `field` in the hash stored at `key`
373/// by `increment`. Returns the new value.
374#[derive(Clone)]
375pub struct HIncrBy {
376    key: CommandArg,
377    field: CommandArg,
378    increment: i64,
379}
380
381impl HIncrBy {
382    /// Create a new [`HIncrBy`] command.
383    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>, increment: i64) -> Self {
384        Self {
385            key: key.into(),
386            field: field.into(),
387            increment,
388        }
389    }
390}
391
392impl Command for HIncrBy {
393    type Response = i64;
394
395    fn to_frame(&self) -> Frame {
396        array(vec![
397            bulk("HINCRBY"),
398            bulk(self.key.as_bytes()),
399            bulk(self.field.as_bytes()),
400            bulk(self.increment.to_string()),
401        ])
402    }
403
404    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
405        match frame {
406            Frame::Integer(n) => Ok(n),
407            other => Err(RedisError::UnexpectedResponse {
408                expected: "integer",
409                actual: format!("{other:?}"),
410            }),
411        }
412    }
413
414    fn name(&self) -> &str {
415        "HINCRBY"
416    }
417}
418
419/// HKEYS key
420///
421/// Returns all field names in the hash stored at `key`.
422#[derive(Clone)]
423pub struct HKeys {
424    key: CommandArg,
425}
426
427impl HKeys {
428    /// Create a new [`HKeys`] command.
429    pub fn new(key: impl Into<CommandArg>) -> Self {
430        Self { key: key.into() }
431    }
432}
433
434impl Command for HKeys {
435    type Response = Vec<Bytes>;
436
437    fn to_frame(&self) -> Frame {
438        array(vec![bulk("HKEYS"), bulk(self.key.as_bytes())])
439    }
440
441    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
442        match frame {
443            Frame::Array(Some(frames)) => frames
444                .into_iter()
445                .map(|f| match f {
446                    Frame::BulkString(Some(data)) => Ok(data),
447                    other => Err(RedisError::UnexpectedResponse {
448                        expected: "bulk string",
449                        actual: format!("{other:?}"),
450                    }),
451                })
452                .collect(),
453            other => Err(RedisError::UnexpectedResponse {
454                expected: "array",
455                actual: format!("{other:?}"),
456            }),
457        }
458    }
459
460    fn name(&self) -> &str {
461        "HKEYS"
462    }
463
464    fn idempotent(&self) -> bool {
465        true
466    }
467}
468
469/// HVALS key
470///
471/// Returns all values in the hash stored at `key`.
472#[derive(Clone)]
473pub struct HVals {
474    key: CommandArg,
475}
476
477impl HVals {
478    /// Create a new [`HVals`] command.
479    pub fn new(key: impl Into<CommandArg>) -> Self {
480        Self { key: key.into() }
481    }
482}
483
484impl Command for HVals {
485    type Response = Vec<Bytes>;
486
487    fn to_frame(&self) -> Frame {
488        array(vec![bulk("HVALS"), bulk(self.key.as_bytes())])
489    }
490
491    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
492        match frame {
493            Frame::Array(Some(frames)) => frames
494                .into_iter()
495                .map(|f| match f {
496                    Frame::BulkString(Some(data)) => Ok(data),
497                    other => Err(RedisError::UnexpectedResponse {
498                        expected: "bulk string",
499                        actual: format!("{other:?}"),
500                    }),
501                })
502                .collect(),
503            other => Err(RedisError::UnexpectedResponse {
504                expected: "array",
505                actual: format!("{other:?}"),
506            }),
507        }
508    }
509
510    fn name(&self) -> &str {
511        "HVALS"
512    }
513
514    fn idempotent(&self) -> bool {
515        true
516    }
517}
518
519/// HLEN key
520///
521/// Returns the number of fields contained in the hash stored at `key`.
522#[derive(Clone)]
523pub struct HLen {
524    key: CommandArg,
525}
526
527impl HLen {
528    /// Create a new [`HLen`] command.
529    pub fn new(key: impl Into<CommandArg>) -> Self {
530        Self { key: key.into() }
531    }
532}
533
534impl Command for HLen {
535    type Response = i64;
536
537    fn to_frame(&self) -> Frame {
538        array(vec![bulk("HLEN"), bulk(self.key.as_bytes())])
539    }
540
541    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
542        match frame {
543            Frame::Integer(n) => Ok(n),
544            other => Err(RedisError::UnexpectedResponse {
545                expected: "integer",
546                actual: format!("{other:?}"),
547            }),
548        }
549    }
550
551    fn name(&self) -> &str {
552        "HLEN"
553    }
554
555    fn idempotent(&self) -> bool {
556        true
557    }
558}
559
560// ---------------------------------------------------------------------------
561// Hash field expiration commands (Redis 7.4+)
562// ---------------------------------------------------------------------------
563
564/// Parse a response that returns one integer per field (used by all hash
565/// field expiration commands).
566fn parse_per_field_response(frame: Frame) -> Result<Vec<i64>, RedisError> {
567    match frame {
568        Frame::Array(Some(frames)) => frames
569            .into_iter()
570            .map(|f| match f {
571                Frame::Integer(n) => Ok(n),
572                other => Err(RedisError::UnexpectedResponse {
573                    expected: "integer",
574                    actual: format!("{other:?}"),
575                }),
576            })
577            .collect(),
578        other => Err(RedisError::UnexpectedResponse {
579            expected: "array",
580            actual: format!("{other:?}"),
581        }),
582    }
583}
584
585/// HEXPIRE key seconds FIELDS numfields field [field ...]
586///
587/// Sets an expiration (in seconds) on the specified hash fields.
588/// Returns one status code per field.
589#[derive(Clone)]
590pub struct HExpire {
591    key: CommandArg,
592    seconds: i64,
593    fields: Vec<CommandArg>,
594}
595
596impl HExpire {
597    /// Create a new [`HExpire`] command.
598    pub fn new(
599        key: impl Into<CommandArg>,
600        seconds: i64,
601        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
602    ) -> Self {
603        Self {
604            key: key.into(),
605            seconds,
606            fields: fields.into_iter().map(Into::into).collect(),
607        }
608    }
609}
610
611impl Command for HExpire {
612    type Response = Vec<i64>;
613
614    fn to_frame(&self) -> Frame {
615        let mut args = vec![
616            bulk("HEXPIRE"),
617            bulk(self.key.as_bytes()),
618            bulk(self.seconds.to_string()),
619            bulk("FIELDS"),
620            bulk(self.fields.len().to_string()),
621        ];
622        for f in &self.fields {
623            args.push(bulk(f.as_bytes()));
624        }
625        array(args)
626    }
627
628    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
629        parse_per_field_response(frame)
630    }
631
632    fn name(&self) -> &str {
633        "HEXPIRE"
634    }
635}
636
637/// HEXPIREAT key unix-time-seconds FIELDS numfields field [field ...]
638///
639/// Sets an expiration on hash fields using an absolute Unix timestamp (seconds).
640/// Returns one status code per field.
641#[derive(Clone)]
642pub struct HExpireAt {
643    key: CommandArg,
644    timestamp: i64,
645    fields: Vec<CommandArg>,
646}
647
648impl HExpireAt {
649    /// Create a new [`HExpireAt`] command.
650    pub fn new(
651        key: impl Into<CommandArg>,
652        timestamp: i64,
653        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
654    ) -> Self {
655        Self {
656            key: key.into(),
657            timestamp,
658            fields: fields.into_iter().map(Into::into).collect(),
659        }
660    }
661}
662
663impl Command for HExpireAt {
664    type Response = Vec<i64>;
665
666    fn to_frame(&self) -> Frame {
667        let mut args = vec![
668            bulk("HEXPIREAT"),
669            bulk(self.key.as_bytes()),
670            bulk(self.timestamp.to_string()),
671            bulk("FIELDS"),
672            bulk(self.fields.len().to_string()),
673        ];
674        for f in &self.fields {
675            args.push(bulk(f.as_bytes()));
676        }
677        array(args)
678    }
679
680    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
681        parse_per_field_response(frame)
682    }
683
684    fn name(&self) -> &str {
685        "HEXPIREAT"
686    }
687}
688
689/// HPEXPIRE key milliseconds FIELDS numfields field [field ...]
690///
691/// Sets an expiration (in milliseconds) on the specified hash fields.
692/// Returns one status code per field.
693#[derive(Clone)]
694pub struct HPExpire {
695    key: CommandArg,
696    milliseconds: i64,
697    fields: Vec<CommandArg>,
698}
699
700impl HPExpire {
701    /// Create a new [`HPExpire`] command.
702    pub fn new(
703        key: impl Into<CommandArg>,
704        milliseconds: i64,
705        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
706    ) -> Self {
707        Self {
708            key: key.into(),
709            milliseconds,
710            fields: fields.into_iter().map(Into::into).collect(),
711        }
712    }
713}
714
715impl Command for HPExpire {
716    type Response = Vec<i64>;
717
718    fn to_frame(&self) -> Frame {
719        let mut args = vec![
720            bulk("HPEXPIRE"),
721            bulk(self.key.as_bytes()),
722            bulk(self.milliseconds.to_string()),
723            bulk("FIELDS"),
724            bulk(self.fields.len().to_string()),
725        ];
726        for f in &self.fields {
727            args.push(bulk(f.as_bytes()));
728        }
729        array(args)
730    }
731
732    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
733        parse_per_field_response(frame)
734    }
735
736    fn name(&self) -> &str {
737        "HPEXPIRE"
738    }
739}
740
741/// HPEXPIREAT key unix-time-milliseconds FIELDS numfields field [field ...]
742///
743/// Sets an expiration on hash fields using an absolute Unix timestamp (milliseconds).
744/// Returns one status code per field.
745#[derive(Clone)]
746pub struct HPExpireAt {
747    key: CommandArg,
748    timestamp: i64,
749    fields: Vec<CommandArg>,
750}
751
752impl HPExpireAt {
753    /// Create a new [`HPExpireAt`] command.
754    pub fn new(
755        key: impl Into<CommandArg>,
756        timestamp: i64,
757        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
758    ) -> Self {
759        Self {
760            key: key.into(),
761            timestamp,
762            fields: fields.into_iter().map(Into::into).collect(),
763        }
764    }
765}
766
767impl Command for HPExpireAt {
768    type Response = Vec<i64>;
769
770    fn to_frame(&self) -> Frame {
771        let mut args = vec![
772            bulk("HPEXPIREAT"),
773            bulk(self.key.as_bytes()),
774            bulk(self.timestamp.to_string()),
775            bulk("FIELDS"),
776            bulk(self.fields.len().to_string()),
777        ];
778        for f in &self.fields {
779            args.push(bulk(f.as_bytes()));
780        }
781        array(args)
782    }
783
784    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
785        parse_per_field_response(frame)
786    }
787
788    fn name(&self) -> &str {
789        "HPEXPIREAT"
790    }
791}
792
793/// HTTL key FIELDS numfields field [field ...]
794///
795/// Returns the remaining TTL (in seconds) for the specified hash fields.
796/// Returns one value per field.
797#[derive(Clone)]
798pub struct HTtl {
799    key: CommandArg,
800    fields: Vec<CommandArg>,
801}
802
803impl HTtl {
804    /// Create a new [`HTtl`] command.
805    pub fn new(
806        key: impl Into<CommandArg>,
807        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
808    ) -> Self {
809        Self {
810            key: key.into(),
811            fields: fields.into_iter().map(Into::into).collect(),
812        }
813    }
814}
815
816impl Command for HTtl {
817    type Response = Vec<i64>;
818
819    fn to_frame(&self) -> Frame {
820        let mut args = vec![
821            bulk("HTTL"),
822            bulk(self.key.as_bytes()),
823            bulk("FIELDS"),
824            bulk(self.fields.len().to_string()),
825        ];
826        for f in &self.fields {
827            args.push(bulk(f.as_bytes()));
828        }
829        array(args)
830    }
831
832    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
833        parse_per_field_response(frame)
834    }
835
836    fn name(&self) -> &str {
837        "HTTL"
838    }
839
840    fn idempotent(&self) -> bool {
841        true
842    }
843}
844
845/// HPTTL key FIELDS numfields field [field ...]
846///
847/// Returns the remaining TTL (in milliseconds) for the specified hash fields.
848/// Returns one value per field.
849#[derive(Clone)]
850pub struct HPTtl {
851    key: CommandArg,
852    fields: Vec<CommandArg>,
853}
854
855impl HPTtl {
856    /// Create a new [`HPTtl`] command.
857    pub fn new(
858        key: impl Into<CommandArg>,
859        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
860    ) -> Self {
861        Self {
862            key: key.into(),
863            fields: fields.into_iter().map(Into::into).collect(),
864        }
865    }
866}
867
868impl Command for HPTtl {
869    type Response = Vec<i64>;
870
871    fn to_frame(&self) -> Frame {
872        let mut args = vec![
873            bulk("HPTTL"),
874            bulk(self.key.as_bytes()),
875            bulk("FIELDS"),
876            bulk(self.fields.len().to_string()),
877        ];
878        for f in &self.fields {
879            args.push(bulk(f.as_bytes()));
880        }
881        array(args)
882    }
883
884    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
885        parse_per_field_response(frame)
886    }
887
888    fn name(&self) -> &str {
889        "HPTTL"
890    }
891
892    fn idempotent(&self) -> bool {
893        true
894    }
895}
896
897/// HPERSIST key FIELDS numfields field [field ...]
898///
899/// Removes the expiration from the specified hash fields.
900/// Returns one status code per field.
901#[derive(Clone)]
902pub struct HPersist {
903    key: CommandArg,
904    fields: Vec<CommandArg>,
905}
906
907impl HPersist {
908    /// Create a new [`HPersist`] command.
909    pub fn new(
910        key: impl Into<CommandArg>,
911        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
912    ) -> Self {
913        Self {
914            key: key.into(),
915            fields: fields.into_iter().map(Into::into).collect(),
916        }
917    }
918}
919
920impl Command for HPersist {
921    type Response = Vec<i64>;
922
923    fn to_frame(&self) -> Frame {
924        let mut args = vec![
925            bulk("HPERSIST"),
926            bulk(self.key.as_bytes()),
927            bulk("FIELDS"),
928            bulk(self.fields.len().to_string()),
929        ];
930        for f in &self.fields {
931            args.push(bulk(f.as_bytes()));
932        }
933        array(args)
934    }
935
936    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
937        parse_per_field_response(frame)
938    }
939
940    fn name(&self) -> &str {
941        "HPERSIST"
942    }
943}
944
945/// HSETNX key field value
946///
947/// Sets `field` in the hash stored at `key` to `value`, only if `field`
948/// does not yet exist. Returns `true` if the field was set, `false` if it
949/// already existed.
950#[derive(Clone)]
951pub struct HSetNx {
952    key: CommandArg,
953    field: CommandArg,
954    value: CommandArg,
955}
956
957impl HSetNx {
958    /// Create a new [`HSetNx`] command.
959    pub fn new(
960        key: impl Into<CommandArg>,
961        field: impl Into<CommandArg>,
962        value: impl Into<CommandArg>,
963    ) -> Self {
964        Self {
965            key: key.into(),
966            field: field.into(),
967            value: value.into(),
968        }
969    }
970}
971
972impl Command for HSetNx {
973    type Response = bool;
974
975    fn to_frame(&self) -> Frame {
976        array(vec![
977            bulk("HSETNX"),
978            bulk(self.key.as_bytes()),
979            bulk(self.field.as_bytes()),
980            bulk(self.value.as_bytes()),
981        ])
982    }
983
984    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
985        match frame {
986            Frame::Integer(n) => Ok(n == 1),
987            Frame::Boolean(b) => Ok(b),
988            other => Err(RedisError::UnexpectedResponse {
989                expected: "integer or boolean",
990                actual: format!("{other:?}"),
991            }),
992        }
993    }
994
995    fn name(&self) -> &str {
996        "HSETNX"
997    }
998}
999
1000/// HINCRBYFLOAT key field increment
1001///
1002/// Increments the floating-point value of `field` in the hash stored at
1003/// `key` by `increment`. Returns the new value as `f64`.
1004#[derive(Clone)]
1005pub struct HIncrByFloat {
1006    key: CommandArg,
1007    field: CommandArg,
1008    increment: f64,
1009}
1010
1011impl HIncrByFloat {
1012    /// Create a new [`HIncrByFloat`] command.
1013    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>, increment: f64) -> Self {
1014        Self {
1015            key: key.into(),
1016            field: field.into(),
1017            increment,
1018        }
1019    }
1020}
1021
1022impl Command for HIncrByFloat {
1023    type Response = f64;
1024
1025    fn to_frame(&self) -> Frame {
1026        array(vec![
1027            bulk("HINCRBYFLOAT"),
1028            bulk(self.key.as_bytes()),
1029            bulk(self.field.as_bytes()),
1030            bulk(self.increment.to_string()),
1031        ])
1032    }
1033
1034    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1035        match frame {
1036            Frame::BulkString(Some(data)) => {
1037                let s = String::from_utf8_lossy(&data);
1038                s.parse::<f64>()
1039                    .map_err(|_| RedisError::UnexpectedResponse {
1040                        expected: "float string",
1041                        actual: format!("{s}"),
1042                    })
1043            }
1044            Frame::Double(d) => Ok(d),
1045            other => Err(RedisError::UnexpectedResponse {
1046                expected: "bulk string or double",
1047                actual: format!("{other:?}"),
1048            }),
1049        }
1050    }
1051
1052    fn name(&self) -> &str {
1053        "HINCRBYFLOAT"
1054    }
1055}
1056
1057/// HRANDFIELD key \[count\]
1058///
1059/// Returns one or more random field names from the hash stored at `key`.
1060/// Without `count`, returns a single random field; with `count`, returns
1061/// up to that many fields. The result is always returned as a `Vec<Bytes>`.
1062#[derive(Clone)]
1063pub struct HRandField {
1064    key: CommandArg,
1065    count: Option<i64>,
1066}
1067
1068impl HRandField {
1069    /// Create a new [`HRandField`] command.
1070    pub fn new(key: impl Into<CommandArg>) -> Self {
1071        Self {
1072            key: key.into(),
1073            count: None,
1074        }
1075    }
1076
1077    /// Request `count` random fields. A negative count allows duplicates.
1078    pub fn count(mut self, count: i64) -> Self {
1079        self.count = Some(count);
1080        self
1081    }
1082}
1083
1084impl Command for HRandField {
1085    type Response = Vec<Bytes>;
1086
1087    fn to_frame(&self) -> Frame {
1088        let mut args = vec![bulk("HRANDFIELD"), bulk(self.key.as_bytes())];
1089        if let Some(count) = self.count {
1090            args.push(bulk(count.to_string()));
1091        }
1092        array(args)
1093    }
1094
1095    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1096        match frame {
1097            // Single field returned when no count argument was sent.
1098            Frame::BulkString(Some(data)) => Ok(vec![data]),
1099            Frame::BulkString(None) | Frame::Null => Ok(vec![]),
1100            // Multiple fields returned when count argument was sent.
1101            Frame::Array(Some(frames)) => frames
1102                .into_iter()
1103                .map(|f| match f {
1104                    Frame::BulkString(Some(data)) => Ok(data),
1105                    other => Err(RedisError::UnexpectedResponse {
1106                        expected: "bulk string",
1107                        actual: format!("{other:?}"),
1108                    }),
1109                })
1110                .collect(),
1111            other => Err(RedisError::UnexpectedResponse {
1112                expected: "bulk string or array",
1113                actual: format!("{other:?}"),
1114            }),
1115        }
1116    }
1117
1118    fn name(&self) -> &str {
1119        "HRANDFIELD"
1120    }
1121
1122    fn idempotent(&self) -> bool {
1123        true
1124    }
1125}
1126
1127/// HEXPIRETIME key FIELDS numfields field [field ...]
1128///
1129/// Returns the absolute Unix expiration timestamp (in seconds) for the
1130/// specified hash fields. Returns one value per field.
1131#[derive(Clone)]
1132pub struct HExpireTime {
1133    key: CommandArg,
1134    fields: Vec<CommandArg>,
1135}
1136
1137impl HExpireTime {
1138    /// Create a new [`HExpireTime`] command.
1139    pub fn new(
1140        key: impl Into<CommandArg>,
1141        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
1142    ) -> Self {
1143        Self {
1144            key: key.into(),
1145            fields: fields.into_iter().map(Into::into).collect(),
1146        }
1147    }
1148}
1149
1150impl Command for HExpireTime {
1151    type Response = Vec<i64>;
1152
1153    fn to_frame(&self) -> Frame {
1154        let mut args = vec![
1155            bulk("HEXPIRETIME"),
1156            bulk(self.key.as_bytes()),
1157            bulk("FIELDS"),
1158            bulk(self.fields.len().to_string()),
1159        ];
1160        for f in &self.fields {
1161            args.push(bulk(f.as_bytes()));
1162        }
1163        array(args)
1164    }
1165
1166    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1167        parse_per_field_response(frame)
1168    }
1169
1170    fn name(&self) -> &str {
1171        "HEXPIRETIME"
1172    }
1173
1174    fn idempotent(&self) -> bool {
1175        true
1176    }
1177}
1178
1179/// HMGET key field [field ...]
1180///
1181/// Returns the values associated with the specified fields in the hash stored
1182/// at `key`. For each field, returns `Some(value)` if it exists, or `None` if
1183/// the field is missing.
1184#[derive(Clone)]
1185pub struct HMGet {
1186    key: CommandArg,
1187    fields: Vec<CommandArg>,
1188}
1189
1190impl HMGet {
1191    /// Create a new [`HMGet`] command.
1192    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>) -> Self {
1193        Self {
1194            key: key.into(),
1195            fields: vec![field.into()],
1196        }
1197    }
1198
1199    /// Create the [`HMGet`] command for the supplied fields.
1200    pub fn fields(
1201        key: impl Into<CommandArg>,
1202        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
1203    ) -> Self {
1204        Self {
1205            key: key.into(),
1206            fields: fields.into_iter().map(Into::into).collect(),
1207        }
1208    }
1209
1210    /// Add another field to request.
1211    pub fn field(mut self, f: impl Into<CommandArg>) -> Self {
1212        self.fields.push(f.into());
1213        self
1214    }
1215}
1216
1217impl Command for HMGet {
1218    type Response = Vec<Option<Bytes>>;
1219
1220    fn to_frame(&self) -> Frame {
1221        let mut args = vec![bulk("HMGET"), bulk(self.key.as_bytes())];
1222        for f in &self.fields {
1223            args.push(bulk(f.as_bytes()));
1224        }
1225        array(args)
1226    }
1227
1228    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1229        match frame {
1230            Frame::Array(Some(frames)) => frames
1231                .into_iter()
1232                .map(|f| match f {
1233                    Frame::BulkString(data) => Ok(data),
1234                    Frame::Null => Ok(None),
1235                    other => Err(RedisError::UnexpectedResponse {
1236                        expected: "bulk string or null",
1237                        actual: format!("{other:?}"),
1238                    }),
1239                })
1240                .collect(),
1241            other => Err(RedisError::UnexpectedResponse {
1242                expected: "array",
1243                actual: format!("{other:?}"),
1244            }),
1245        }
1246    }
1247
1248    fn name(&self) -> &str {
1249        "HMGET"
1250    }
1251
1252    fn idempotent(&self) -> bool {
1253        true
1254    }
1255}
1256
1257/// HSTRLEN key field
1258///
1259/// Returns the string length of the value associated with `field` in the hash
1260/// stored at `key`, or 0 if the field or key does not exist.
1261#[derive(Clone)]
1262pub struct HStrLen {
1263    key: CommandArg,
1264    field: CommandArg,
1265}
1266
1267impl HStrLen {
1268    /// Create a new [`HStrLen`] command.
1269    pub fn new(key: impl Into<CommandArg>, field: impl Into<CommandArg>) -> Self {
1270        Self {
1271            key: key.into(),
1272            field: field.into(),
1273        }
1274    }
1275}
1276
1277impl Command for HStrLen {
1278    type Response = i64;
1279
1280    fn to_frame(&self) -> Frame {
1281        array(vec![
1282            bulk("HSTRLEN"),
1283            bulk(self.key.as_bytes()),
1284            bulk(self.field.as_bytes()),
1285        ])
1286    }
1287
1288    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1289        match frame {
1290            Frame::Integer(n) => Ok(n),
1291            other => Err(RedisError::UnexpectedResponse {
1292                expected: "integer",
1293                actual: format!("{other:?}"),
1294            }),
1295        }
1296    }
1297
1298    fn name(&self) -> &str {
1299        "HSTRLEN"
1300    }
1301
1302    fn idempotent(&self) -> bool {
1303        true
1304    }
1305}
1306
1307/// HPEXPIRETIME key FIELDS numfields field [field ...]
1308///
1309/// Returns the absolute Unix expiration timestamp (in milliseconds) for the
1310/// specified hash fields. Returns one value per field.
1311#[derive(Clone)]
1312pub struct HPExpireTime {
1313    key: CommandArg,
1314    fields: Vec<CommandArg>,
1315}
1316
1317impl HPExpireTime {
1318    /// Create a new [`HPExpireTime`] command.
1319    pub fn new(
1320        key: impl Into<CommandArg>,
1321        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
1322    ) -> Self {
1323        Self {
1324            key: key.into(),
1325            fields: fields.into_iter().map(Into::into).collect(),
1326        }
1327    }
1328}
1329
1330impl Command for HPExpireTime {
1331    type Response = Vec<i64>;
1332
1333    fn to_frame(&self) -> Frame {
1334        let mut args = vec![
1335            bulk("HPEXPIRETIME"),
1336            bulk(self.key.as_bytes()),
1337            bulk("FIELDS"),
1338            bulk(self.fields.len().to_string()),
1339        ];
1340        for f in &self.fields {
1341            args.push(bulk(f.as_bytes()));
1342        }
1343        array(args)
1344    }
1345
1346    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1347        parse_per_field_response(frame)
1348    }
1349
1350    fn name(&self) -> &str {
1351        "HPEXPIRETIME"
1352    }
1353
1354    fn idempotent(&self) -> bool {
1355        true
1356    }
1357}
1358
1359/// HGETDEL key FIELDS numfields field \[field ...\]
1360///
1361/// Gets the values of the given hash fields and deletes them in one atomic
1362/// operation (Redis 8.0+). Returns one bulk-or-nil entry per requested field,
1363/// in request order; missing fields yield `None`.
1364///
1365/// # Example
1366///
1367/// ```no_run
1368/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1369/// use redis_tower_commands::HGetDel;
1370/// use redis_tower_core::RedisConnection;
1371///
1372/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1373///
1374/// let values = conn.execute(HGetDel::new("h", vec!["f1", "f2"])).await?;
1375/// # let _ = values;
1376/// # Ok(())
1377/// # }
1378/// ```
1379#[derive(Clone)]
1380pub struct HGetDel {
1381    key: CommandArg,
1382    fields: Vec<CommandArg>,
1383}
1384
1385impl HGetDel {
1386    /// Create a new [`HGetDel`] command.
1387    pub fn new(
1388        key: impl Into<CommandArg>,
1389        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
1390    ) -> Self {
1391        Self {
1392            key: key.into(),
1393            fields: fields.into_iter().map(Into::into).collect(),
1394        }
1395    }
1396}
1397
1398impl Command for HGetDel {
1399    type Response = Vec<Option<Bytes>>;
1400
1401    fn to_frame(&self) -> Frame {
1402        let mut args = vec![
1403            bulk("HGETDEL"),
1404            bulk(self.key.as_bytes()),
1405            bulk("FIELDS"),
1406            bulk(self.fields.len().to_string()),
1407        ];
1408        for f in &self.fields {
1409            args.push(bulk(f.as_bytes()));
1410        }
1411        array(args)
1412    }
1413
1414    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1415        match frame {
1416            Frame::Array(Some(frames)) => frames
1417                .into_iter()
1418                .map(|f| match f {
1419                    Frame::BulkString(data) => Ok(data),
1420                    Frame::Null => Ok(None),
1421                    other => Err(RedisError::UnexpectedResponse {
1422                        expected: "bulk string or null",
1423                        actual: format!("{other:?}"),
1424                    }),
1425                })
1426                .collect(),
1427            other => Err(RedisError::UnexpectedResponse {
1428                expected: "array",
1429                actual: format!("{other:?}"),
1430            }),
1431        }
1432    }
1433
1434    fn name(&self) -> &str {
1435        "HGETDEL"
1436    }
1437}
1438
1439/// HGETEX key \[EX s | PX ms | EXAT ts | PXAT ts | PERSIST\] FIELDS numfields field \[field ...\]
1440///
1441/// Gets the values of the given hash fields and optionally sets or clears their
1442/// TTL in the same call (Redis 8.0+). With no TTL option the fields' TTLs are
1443/// left unchanged. Returns one bulk-or-nil entry per requested field.
1444///
1445/// # Example
1446///
1447/// ```no_run
1448/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1449/// use redis_tower_commands::HGetEx;
1450/// use redis_tower_core::RedisConnection;
1451///
1452/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1453///
1454/// let values = conn
1455///     .execute(HGetEx::new("h", vec!["f1", "f2"]).ex(60))
1456///     .await?;
1457/// # let _ = values;
1458/// # Ok(())
1459/// # }
1460/// ```
1461#[derive(Clone)]
1462pub struct HGetEx {
1463    key: CommandArg,
1464    ex: Option<u64>,
1465    px: Option<u64>,
1466    exat: Option<u64>,
1467    pxat: Option<u64>,
1468    persist: bool,
1469    fields: Vec<CommandArg>,
1470}
1471
1472impl HGetEx {
1473    /// Create a new [`HGetEx`] command.
1474    pub fn new(
1475        key: impl Into<CommandArg>,
1476        fields: impl IntoIterator<Item = impl Into<CommandArg>>,
1477    ) -> Self {
1478        Self {
1479            key: key.into(),
1480            ex: None,
1481            px: None,
1482            exat: None,
1483            pxat: None,
1484            persist: false,
1485            fields: fields.into_iter().map(Into::into).collect(),
1486        }
1487    }
1488
1489    /// Set the fields' expiration in seconds.
1490    pub fn ex(mut self, seconds: u64) -> Self {
1491        self.ex = Some(seconds);
1492        self.px = None;
1493        self.exat = None;
1494        self.pxat = None;
1495        self.persist = false;
1496        self
1497    }
1498
1499    /// Set the fields' expiration in milliseconds.
1500    pub fn px(mut self, milliseconds: u64) -> Self {
1501        self.px = Some(milliseconds);
1502        self.ex = None;
1503        self.exat = None;
1504        self.pxat = None;
1505        self.persist = false;
1506        self
1507    }
1508
1509    /// Set the fields' expiration as a Unix timestamp in seconds.
1510    pub fn exat(mut self, timestamp: u64) -> Self {
1511        self.exat = Some(timestamp);
1512        self.ex = None;
1513        self.px = None;
1514        self.pxat = None;
1515        self.persist = false;
1516        self
1517    }
1518
1519    /// Set the fields' expiration as a Unix timestamp in milliseconds.
1520    pub fn pxat(mut self, timestamp: u64) -> Self {
1521        self.pxat = Some(timestamp);
1522        self.ex = None;
1523        self.px = None;
1524        self.exat = None;
1525        self.persist = false;
1526        self
1527    }
1528
1529    /// Remove the existing expiration on the fields.
1530    pub fn persist(mut self) -> Self {
1531        self.persist = true;
1532        self.ex = None;
1533        self.px = None;
1534        self.exat = None;
1535        self.pxat = None;
1536        self
1537    }
1538}
1539
1540impl Command for HGetEx {
1541    type Response = Vec<Option<Bytes>>;
1542
1543    fn to_frame(&self) -> Frame {
1544        let mut args = vec![bulk("HGETEX"), bulk(self.key.as_bytes())];
1545        if let Some(ex) = self.ex {
1546            args.push(bulk("EX"));
1547            args.push(bulk(ex.to_string()));
1548        }
1549        if let Some(px) = self.px {
1550            args.push(bulk("PX"));
1551            args.push(bulk(px.to_string()));
1552        }
1553        if let Some(exat) = self.exat {
1554            args.push(bulk("EXAT"));
1555            args.push(bulk(exat.to_string()));
1556        }
1557        if let Some(pxat) = self.pxat {
1558            args.push(bulk("PXAT"));
1559            args.push(bulk(pxat.to_string()));
1560        }
1561        if self.persist {
1562            args.push(bulk("PERSIST"));
1563        }
1564        args.push(bulk("FIELDS"));
1565        args.push(bulk(self.fields.len().to_string()));
1566        for f in &self.fields {
1567            args.push(bulk(f.as_bytes()));
1568        }
1569        array(args)
1570    }
1571
1572    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1573        match frame {
1574            Frame::Array(Some(frames)) => frames
1575                .into_iter()
1576                .map(|f| match f {
1577                    Frame::BulkString(data) => Ok(data),
1578                    Frame::Null => Ok(None),
1579                    other => Err(RedisError::UnexpectedResponse {
1580                        expected: "bulk string or null",
1581                        actual: format!("{other:?}"),
1582                    }),
1583                })
1584                .collect(),
1585            other => Err(RedisError::UnexpectedResponse {
1586                expected: "array",
1587                actual: format!("{other:?}"),
1588            }),
1589        }
1590    }
1591
1592    fn name(&self) -> &str {
1593        "HGETEX"
1594    }
1595}
1596
1597/// Condition for HSETEX (FNX or FXX).
1598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1599pub enum HSetExCondition {
1600    /// Only set if none of the fields already exist.
1601    Fnx,
1602    /// Only set if all of the fields already exist.
1603    Fxx,
1604}
1605
1606/// HSETEX key \[FNX|FXX\] \[EX s | PX ms | EXAT ts | PXAT ts | KEEPTTL\]
1607/// FIELDS numfields field value \[field value ...\]
1608///
1609/// Sets the given hash field/value pairs and their TTL in one atomic operation
1610/// (Redis 8.0+). Returns `1` if the fields were set, `0` otherwise (for example
1611/// when a `FNX`/`FXX` condition is not met).
1612///
1613/// # Example
1614///
1615/// ```no_run
1616/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1617/// use redis_tower_commands::HSetEx;
1618/// use redis_tower_core::RedisConnection;
1619///
1620/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1621///
1622/// let set = conn
1623///     .execute(HSetEx::new("h", vec![("f1", "v1"), ("f2", "v2")]).ex(60))
1624///     .await?;
1625/// # let _ = set;
1626/// # Ok(())
1627/// # }
1628/// ```
1629#[derive(Clone)]
1630pub struct HSetEx {
1631    key: CommandArg,
1632    condition: Option<HSetExCondition>,
1633    ex: Option<u64>,
1634    px: Option<u64>,
1635    exat: Option<u64>,
1636    pxat: Option<u64>,
1637    keep_ttl: bool,
1638    fields: Vec<(CommandArg, CommandArg)>,
1639}
1640
1641impl HSetEx {
1642    /// Create a new [`HSetEx`] command.
1643    pub fn new(
1644        key: impl Into<CommandArg>,
1645        fields: impl IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>,
1646    ) -> Self {
1647        Self {
1648            key: key.into(),
1649            condition: None,
1650            ex: None,
1651            px: None,
1652            exat: None,
1653            pxat: None,
1654            keep_ttl: false,
1655            fields: fields
1656                .into_iter()
1657                .map(|(f, v)| (f.into(), v.into()))
1658                .collect(),
1659        }
1660    }
1661
1662    /// Only set if none of the fields already exist.
1663    pub fn fnx(mut self) -> Self {
1664        self.condition = Some(HSetExCondition::Fnx);
1665        self
1666    }
1667
1668    /// Only set if all of the fields already exist.
1669    pub fn fxx(mut self) -> Self {
1670        self.condition = Some(HSetExCondition::Fxx);
1671        self
1672    }
1673
1674    /// Set the fields' expiration in seconds.
1675    pub fn ex(mut self, seconds: u64) -> Self {
1676        self.ex = Some(seconds);
1677        self.px = None;
1678        self.exat = None;
1679        self.pxat = None;
1680        self.keep_ttl = false;
1681        self
1682    }
1683
1684    /// Set the fields' expiration in milliseconds.
1685    pub fn px(mut self, milliseconds: u64) -> Self {
1686        self.px = Some(milliseconds);
1687        self.ex = None;
1688        self.exat = None;
1689        self.pxat = None;
1690        self.keep_ttl = false;
1691        self
1692    }
1693
1694    /// Set the fields' expiration as a Unix timestamp in seconds.
1695    pub fn exat(mut self, timestamp: u64) -> Self {
1696        self.exat = Some(timestamp);
1697        self.ex = None;
1698        self.px = None;
1699        self.pxat = None;
1700        self.keep_ttl = false;
1701        self
1702    }
1703
1704    /// Set the fields' expiration as a Unix timestamp in milliseconds.
1705    pub fn pxat(mut self, timestamp: u64) -> Self {
1706        self.pxat = Some(timestamp);
1707        self.ex = None;
1708        self.px = None;
1709        self.exat = None;
1710        self.keep_ttl = false;
1711        self
1712    }
1713
1714    /// Retain the existing TTL on the fields.
1715    pub fn keep_ttl(mut self) -> Self {
1716        self.keep_ttl = true;
1717        self.ex = None;
1718        self.px = None;
1719        self.exat = None;
1720        self.pxat = None;
1721        self
1722    }
1723}
1724
1725impl Command for HSetEx {
1726    type Response = i64;
1727
1728    fn to_frame(&self) -> Frame {
1729        let mut args = vec![bulk("HSETEX"), bulk(self.key.as_bytes())];
1730        match &self.condition {
1731            Some(HSetExCondition::Fnx) => args.push(bulk("FNX")),
1732            Some(HSetExCondition::Fxx) => args.push(bulk("FXX")),
1733            None => {}
1734        }
1735        if let Some(ex) = self.ex {
1736            args.push(bulk("EX"));
1737            args.push(bulk(ex.to_string()));
1738        }
1739        if let Some(px) = self.px {
1740            args.push(bulk("PX"));
1741            args.push(bulk(px.to_string()));
1742        }
1743        if let Some(exat) = self.exat {
1744            args.push(bulk("EXAT"));
1745            args.push(bulk(exat.to_string()));
1746        }
1747        if let Some(pxat) = self.pxat {
1748            args.push(bulk("PXAT"));
1749            args.push(bulk(pxat.to_string()));
1750        }
1751        if self.keep_ttl {
1752            args.push(bulk("KEEPTTL"));
1753        }
1754        args.push(bulk("FIELDS"));
1755        args.push(bulk(self.fields.len().to_string()));
1756        for (f, v) in &self.fields {
1757            args.push(bulk(f.as_bytes()));
1758            args.push(bulk(v.as_bytes()));
1759        }
1760        array(args)
1761    }
1762
1763    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1764        match frame {
1765            Frame::Integer(n) => Ok(n),
1766            other => Err(RedisError::UnexpectedResponse {
1767                expected: "integer",
1768                actual: format!("{other:?}"),
1769            }),
1770        }
1771    }
1772
1773    fn name(&self) -> &str {
1774        "HSETEX"
1775    }
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780    use super::*;
1781    use redis_tower_core::Command;
1782    use redis_tower_protocol::Frame;
1783    use redis_tower_protocol::helpers::{array, bulk};
1784
1785    // -- HGet --
1786
1787    #[test]
1788    fn hget_to_frame() {
1789        let cmd = HGet::new("myhash", "field1");
1790        assert_eq!(
1791            cmd.to_frame(),
1792            array(vec![bulk("HGET"), bulk("myhash"), bulk("field1")])
1793        );
1794    }
1795
1796    #[test]
1797    fn hget_parse_value() {
1798        let cmd = HGet::new("h", "f");
1799        let frame = Frame::BulkString(Some(Bytes::from("val")));
1800        assert_eq!(cmd.parse_response(frame).unwrap(), Some(Bytes::from("val")));
1801    }
1802
1803    #[test]
1804    fn hget_parse_null() {
1805        let cmd = HGet::new("h", "f");
1806        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1807    }
1808
1809    #[test]
1810    fn hget_parse_error_on_integer() {
1811        let cmd = HGet::new("h", "f");
1812        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
1813    }
1814
1815    // -- HSet --
1816
1817    #[test]
1818    fn hset_single_to_frame() {
1819        let cmd = HSet::new("myhash", "f1", "v1");
1820        assert_eq!(
1821            cmd.to_frame(),
1822            array(vec![bulk("HSET"), bulk("myhash"), bulk("f1"), bulk("v1")])
1823        );
1824    }
1825
1826    #[test]
1827    fn hset_multiple_to_frame() {
1828        let cmd = HSet::new("h", "f1", "v1").field("f2", "v2");
1829        assert_eq!(
1830            cmd.to_frame(),
1831            array(vec![
1832                bulk("HSET"),
1833                bulk("h"),
1834                bulk("f1"),
1835                bulk("v1"),
1836                bulk("f2"),
1837                bulk("v2"),
1838            ])
1839        );
1840    }
1841
1842    #[test]
1843    fn hset_parse_integer() {
1844        let cmd = HSet::new("h", "f", "v");
1845        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
1846    }
1847
1848    #[test]
1849    fn hset_from_fields_to_frame() {
1850        let cmd = HSet::from_fields("h", [("f1", "v1"), ("f2", "v2")]);
1851        assert_eq!(
1852            cmd.to_frame(),
1853            array(vec![
1854                bulk("HSET"),
1855                bulk("h"),
1856                bulk("f1"),
1857                bulk("v1"),
1858                bulk("f2"),
1859                bulk("v2"),
1860            ])
1861        );
1862    }
1863
1864    #[test]
1865    fn hset_from_fields_matches_incremental() {
1866        let incremental = HSet::new("h", "f1", "v1").field("f2", "v2");
1867        let bulk = HSet::from_fields("h", [("f1", "v1"), ("f2", "v2")]);
1868        assert_eq!(incremental.to_frame(), bulk.to_frame());
1869    }
1870
1871    #[test]
1872    fn hset_from_fields_vec() {
1873        let fields = vec![("name", "Alice"), ("city", "Portland")];
1874        let cmd = HSet::from_fields("user:1", fields);
1875        assert_eq!(
1876            cmd.to_frame(),
1877            array(vec![
1878                bulk("HSET"),
1879                bulk("user:1"),
1880                bulk("name"),
1881                bulk("Alice"),
1882                bulk("city"),
1883                bulk("Portland"),
1884            ])
1885        );
1886    }
1887
1888    // -- HDel --
1889
1890    #[test]
1891    fn hdel_to_frame() {
1892        let cmd = HDel::new("h", "f1");
1893        assert_eq!(
1894            cmd.to_frame(),
1895            array(vec![bulk("HDEL"), bulk("h"), bulk("f1")])
1896        );
1897    }
1898
1899    #[test]
1900    fn hdel_multiple_to_frame() {
1901        let cmd = HDel::fields("h", vec!["f1", "f2"]);
1902        assert_eq!(
1903            cmd.to_frame(),
1904            array(vec![bulk("HDEL"), bulk("h"), bulk("f1"), bulk("f2")])
1905        );
1906    }
1907
1908    // -- HExists --
1909
1910    #[test]
1911    fn hexists_to_frame() {
1912        let cmd = HExists::new("h", "f");
1913        assert_eq!(
1914            cmd.to_frame(),
1915            array(vec![bulk("HEXISTS"), bulk("h"), bulk("f")])
1916        );
1917    }
1918
1919    #[test]
1920    fn hexists_parse_true() {
1921        let cmd = HExists::new("h", "f");
1922        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
1923    }
1924
1925    #[test]
1926    fn hexists_parse_false() {
1927        let cmd = HExists::new("h", "f");
1928        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
1929    }
1930
1931    // -- HGetAll --
1932
1933    #[test]
1934    fn hgetall_to_frame() {
1935        let cmd = HGetAll::new("myhash");
1936        assert_eq!(cmd.to_frame(), array(vec![bulk("HGETALL"), bulk("myhash")]));
1937    }
1938
1939    #[test]
1940    fn hgetall_parse_flat_array() {
1941        let cmd = HGetAll::new("h");
1942        let frame = array(vec![
1943            Frame::BulkString(Some(Bytes::from("f1"))),
1944            Frame::BulkString(Some(Bytes::from("v1"))),
1945            Frame::BulkString(Some(Bytes::from("f2"))),
1946            Frame::BulkString(Some(Bytes::from("v2"))),
1947        ]);
1948        let result = cmd.parse_response(frame).unwrap();
1949        assert_eq!(
1950            result,
1951            vec![
1952                (Bytes::from("f1"), Bytes::from("v1")),
1953                (Bytes::from("f2"), Bytes::from("v2")),
1954            ]
1955        );
1956    }
1957
1958    #[test]
1959    fn hgetall_parse_map() {
1960        let cmd = HGetAll::new("h");
1961        let frame = Frame::Map(vec![(
1962            Frame::BulkString(Some(Bytes::from("f1"))),
1963            Frame::BulkString(Some(Bytes::from("v1"))),
1964        )]);
1965        let result = cmd.parse_response(frame).unwrap();
1966        assert_eq!(result, vec![(Bytes::from("f1"), Bytes::from("v1"))]);
1967    }
1968
1969    #[test]
1970    fn hgetall_parse_odd_array_error() {
1971        let cmd = HGetAll::new("h");
1972        let frame = array(vec![Frame::BulkString(Some(Bytes::from("f1")))]);
1973        assert!(cmd.parse_response(frame).is_err());
1974    }
1975
1976    #[test]
1977    fn hgetall_parse_error_on_integer() {
1978        let cmd = HGetAll::new("h");
1979        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
1980    }
1981
1982    // -- HIncrBy --
1983
1984    #[test]
1985    fn hincrby_to_frame() {
1986        let cmd = HIncrBy::new("h", "f", 5);
1987        assert_eq!(
1988            cmd.to_frame(),
1989            array(vec![bulk("HINCRBY"), bulk("h"), bulk("f"), bulk("5")])
1990        );
1991    }
1992
1993    // -- HIncrByFloat --
1994
1995    #[test]
1996    fn hincrbyfloat_to_frame() {
1997        let cmd = HIncrByFloat::new("h", "f", 1.5);
1998        assert_eq!(
1999            cmd.to_frame(),
2000            array(vec![
2001                bulk("HINCRBYFLOAT"),
2002                bulk("h"),
2003                bulk("f"),
2004                bulk("1.5")
2005            ])
2006        );
2007    }
2008
2009    #[test]
2010    fn hincrbyfloat_parse_bulk_string() {
2011        let cmd = HIncrByFloat::new("h", "f", 1.0);
2012        let frame = Frame::BulkString(Some(Bytes::from("3.5")));
2013        let result = cmd.parse_response(frame).unwrap();
2014        assert!((result - 3.5).abs() < f64::EPSILON);
2015    }
2016
2017    #[test]
2018    fn hincrbyfloat_parse_double() {
2019        let cmd = HIncrByFloat::new("h", "f", 1.0);
2020        let result = cmd.parse_response(Frame::Double(3.5)).unwrap();
2021        assert!((result - 3.5).abs() < f64::EPSILON);
2022    }
2023
2024    // -- HSetNx --
2025
2026    #[test]
2027    fn hsetnx_to_frame() {
2028        let cmd = HSetNx::new("h", "f", "v");
2029        assert_eq!(
2030            cmd.to_frame(),
2031            array(vec![bulk("HSETNX"), bulk("h"), bulk("f"), bulk("v")])
2032        );
2033    }
2034
2035    #[test]
2036    fn hsetnx_parse_true() {
2037        let cmd = HSetNx::new("h", "f", "v");
2038        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2039    }
2040
2041    // -- HExpire --
2042
2043    #[test]
2044    fn hexpire_to_frame() {
2045        let cmd = HExpire::new("h", 60, vec!["f1", "f2"]);
2046        assert_eq!(
2047            cmd.to_frame(),
2048            array(vec![
2049                bulk("HEXPIRE"),
2050                bulk("h"),
2051                bulk("60"),
2052                bulk("FIELDS"),
2053                bulk("2"),
2054                bulk("f1"),
2055                bulk("f2"),
2056            ])
2057        );
2058    }
2059
2060    #[test]
2061    fn hexpire_parse_per_field() {
2062        let cmd = HExpire::new("h", 60, vec!["f1", "f2"]);
2063        let frame = array(vec![Frame::Integer(1), Frame::Integer(0)]);
2064        let result = cmd.parse_response(frame).unwrap();
2065        assert_eq!(result, vec![1, 0]);
2066    }
2067
2068    // -- HRandField --
2069
2070    #[test]
2071    fn hrandfield_to_frame_no_count() {
2072        let cmd = HRandField::new("h");
2073        assert_eq!(cmd.to_frame(), array(vec![bulk("HRANDFIELD"), bulk("h")]));
2074    }
2075
2076    #[test]
2077    fn hrandfield_to_frame_with_count() {
2078        let cmd = HRandField::new("h").count(3);
2079        assert_eq!(
2080            cmd.to_frame(),
2081            array(vec![bulk("HRANDFIELD"), bulk("h"), bulk("3")])
2082        );
2083    }
2084
2085    #[test]
2086    fn hrandfield_parse_single() {
2087        let cmd = HRandField::new("h");
2088        let frame = Frame::BulkString(Some(Bytes::from("field1")));
2089        let result = cmd.parse_response(frame).unwrap();
2090        assert_eq!(result, vec![Bytes::from("field1")]);
2091    }
2092
2093    #[test]
2094    fn hrandfield_parse_null_empty() {
2095        let cmd = HRandField::new("h");
2096        let result = cmd.parse_response(Frame::Null).unwrap();
2097        assert!(result.is_empty());
2098    }
2099
2100    // -- HMGet --
2101
2102    #[test]
2103    fn hmget_to_frame() {
2104        let cmd = HMGet::fields("h", vec!["f1", "f2"]);
2105        assert_eq!(
2106            cmd.to_frame(),
2107            array(vec![bulk("HMGET"), bulk("h"), bulk("f1"), bulk("f2")])
2108        );
2109    }
2110
2111    #[test]
2112    fn hmget_builder_to_frame() {
2113        let cmd = HMGet::new("h", "f1").field("f2");
2114        assert_eq!(
2115            cmd.to_frame(),
2116            array(vec![bulk("HMGET"), bulk("h"), bulk("f1"), bulk("f2")])
2117        );
2118    }
2119
2120    #[test]
2121    fn hmget_parse_mixed() {
2122        let cmd = HMGet::fields("h", vec!["f1", "f2"]);
2123        let frame = array(vec![
2124            Frame::BulkString(Some(Bytes::from("v1"))),
2125            Frame::Null,
2126        ]);
2127        let result = cmd.parse_response(frame).unwrap();
2128        assert_eq!(result, vec![Some(Bytes::from("v1")), None]);
2129    }
2130
2131    // -- HStrLen --
2132
2133    #[test]
2134    fn hstrlen_to_frame() {
2135        let cmd = HStrLen::new("h", "f");
2136        assert_eq!(
2137            cmd.to_frame(),
2138            array(vec![bulk("HSTRLEN"), bulk("h"), bulk("f")])
2139        );
2140    }
2141
2142    #[test]
2143    fn hstrlen_parse_integer() {
2144        let cmd = HStrLen::new("h", "f");
2145        assert_eq!(cmd.parse_response(Frame::Integer(5)).unwrap(), 5);
2146    }
2147
2148    // -- HPExpireTime --
2149
2150    #[test]
2151    fn hpexpiretime_to_frame() {
2152        let cmd = HPExpireTime::new("h", vec!["f1", "f2"]);
2153        assert_eq!(
2154            cmd.to_frame(),
2155            array(vec![
2156                bulk("HPEXPIRETIME"),
2157                bulk("h"),
2158                bulk("FIELDS"),
2159                bulk("2"),
2160                bulk("f1"),
2161                bulk("f2"),
2162            ])
2163        );
2164    }
2165
2166    #[test]
2167    fn hpexpiretime_parse_per_field() {
2168        let cmd = HPExpireTime::new("h", vec!["f1"]);
2169        let frame = array(vec![Frame::Integer(1700000000000)]);
2170        let result = cmd.parse_response(frame).unwrap();
2171        assert_eq!(result, vec![1700000000000]);
2172    }
2173
2174    // -- HGetDel --
2175
2176    #[test]
2177    fn hgetdel_to_frame() {
2178        let cmd = HGetDel::new("h", vec!["f1", "f2"]);
2179        assert_eq!(
2180            cmd.to_frame(),
2181            array(vec![
2182                bulk("HGETDEL"),
2183                bulk("h"),
2184                bulk("FIELDS"),
2185                bulk("2"),
2186                bulk("f1"),
2187                bulk("f2"),
2188            ])
2189        );
2190    }
2191
2192    #[test]
2193    fn hgetdel_parse_bulk_and_nil() {
2194        let cmd = HGetDel::new("h", vec!["f1", "f2"]);
2195        let frame = array(vec![
2196            Frame::BulkString(Some(Bytes::from("v1"))),
2197            Frame::Null,
2198        ]);
2199        assert_eq!(
2200            cmd.parse_response(frame).unwrap(),
2201            vec![Some(Bytes::from("v1")), None]
2202        );
2203    }
2204
2205    // -- HGetEx --
2206
2207    #[test]
2208    fn hgetex_no_ttl_to_frame() {
2209        let cmd = HGetEx::new("h", vec!["f1"]);
2210        assert_eq!(
2211            cmd.to_frame(),
2212            array(vec![
2213                bulk("HGETEX"),
2214                bulk("h"),
2215                bulk("FIELDS"),
2216                bulk("1"),
2217                bulk("f1"),
2218            ])
2219        );
2220    }
2221
2222    #[test]
2223    fn hgetex_ex_to_frame() {
2224        let cmd = HGetEx::new("h", vec!["f1", "f2"]).ex(60);
2225        assert_eq!(
2226            cmd.to_frame(),
2227            array(vec![
2228                bulk("HGETEX"),
2229                bulk("h"),
2230                bulk("EX"),
2231                bulk("60"),
2232                bulk("FIELDS"),
2233                bulk("2"),
2234                bulk("f1"),
2235                bulk("f2"),
2236            ])
2237        );
2238    }
2239
2240    #[test]
2241    fn hgetex_persist_to_frame() {
2242        let cmd = HGetEx::new("h", vec!["f1"]).persist();
2243        assert_eq!(
2244            cmd.to_frame(),
2245            array(vec![
2246                bulk("HGETEX"),
2247                bulk("h"),
2248                bulk("PERSIST"),
2249                bulk("FIELDS"),
2250                bulk("1"),
2251                bulk("f1"),
2252            ])
2253        );
2254    }
2255
2256    // -- HSetEx --
2257
2258    #[test]
2259    fn hsetex_to_frame() {
2260        let cmd = HSetEx::new("h", vec![("f1", "v1"), ("f2", "v2")]).ex(60);
2261        assert_eq!(
2262            cmd.to_frame(),
2263            array(vec![
2264                bulk("HSETEX"),
2265                bulk("h"),
2266                bulk("EX"),
2267                bulk("60"),
2268                bulk("FIELDS"),
2269                bulk("2"),
2270                bulk("f1"),
2271                bulk("v1"),
2272                bulk("f2"),
2273                bulk("v2"),
2274            ])
2275        );
2276    }
2277
2278    #[test]
2279    fn hsetex_fnx_keepttl_to_frame() {
2280        let cmd = HSetEx::new("h", vec![("f1", "v1")]).fnx().keep_ttl();
2281        assert_eq!(
2282            cmd.to_frame(),
2283            array(vec![
2284                bulk("HSETEX"),
2285                bulk("h"),
2286                bulk("FNX"),
2287                bulk("KEEPTTL"),
2288                bulk("FIELDS"),
2289                bulk("1"),
2290                bulk("f1"),
2291                bulk("v1"),
2292            ])
2293        );
2294    }
2295
2296    #[test]
2297    fn hsetex_parse_integer() {
2298        let cmd = HSetEx::new("h", vec![("f1", "v1")]);
2299        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
2300    }
2301}