Skip to main content

redis_tower_commands/
json.rs

1//! RedisJSON document commands.
2//!
3//! Available with the `json` feature (included by `stack`) and requiring
4//! RedisJSON on the server. JSON paths and serialized JSON values are textual
5//! grammar; Redis keys remain binary-safe. Commands return typed scalars,
6//! optional bytes, or raw JSON text according to the selected operation/path.
7//!
8//! ```
9//! use redis_tower_commands::{JsonGet, JsonSet};
10//! use redis_tower_core::Command;
11//!
12//! let set = JsonSet::new("user:1", "$", r#"{"name":"Ada"}"#);
13//! let get = JsonGet::new("user:1").path("$.name");
14//! assert_eq!((set.name(), get.name()), ("JSON.SET", "JSON.GET"));
15//! ```
16//!
17//! See the [command cookbook] for module reply normalization.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#raw-custom-and-module-replies
20
21use crate::CommandArg;
22use bytes::Bytes;
23use redis_tower_core::{Command, Frame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26/// Condition for JSON.SET (NX or XX).
27#[derive(Clone)]
28pub enum JsonSetCondition {
29    /// Only set if the path does not exist.
30    Nx,
31    /// Only set if the path already exists.
32    Xx,
33}
34
35/// JSON.SET key path value \[NX|XX\]
36///
37/// Sets the JSON value at `path` in the key. Creates the key if it does not
38/// exist. Returns `Ok(())` on success.
39#[derive(Clone)]
40pub struct JsonSet {
41    key: CommandArg,
42    path: String,
43    value: String,
44    condition: Option<JsonSetCondition>,
45}
46
47impl JsonSet {
48    /// Create a new [`JsonSet`] command.
49    pub fn new(
50        key: impl Into<CommandArg>,
51        path: impl Into<String>,
52        value: impl Into<String>,
53    ) -> Self {
54        Self {
55            key: key.into(),
56            path: path.into(),
57            value: value.into(),
58            condition: None,
59        }
60    }
61
62    /// Only set if the path does not already exist.
63    pub fn nx(mut self) -> Self {
64        self.condition = Some(JsonSetCondition::Nx);
65        self
66    }
67
68    /// Only set if the path already exists.
69    pub fn xx(mut self) -> Self {
70        self.condition = Some(JsonSetCondition::Xx);
71        self
72    }
73}
74
75impl Command for JsonSet {
76    type Response = ();
77
78    fn to_frame(&self) -> Frame {
79        let mut args = vec![
80            bulk("JSON.SET"),
81            bulk(&self.key),
82            bulk(self.path.as_str()),
83            bulk(self.value.as_str()),
84        ];
85        match &self.condition {
86            Some(JsonSetCondition::Nx) => args.push(bulk("NX")),
87            Some(JsonSetCondition::Xx) => args.push(bulk("XX")),
88            None => {}
89        }
90        array(args)
91    }
92
93    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
94        match frame {
95            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
96            Frame::Null => Ok(()),
97            other => Err(RedisError::UnexpectedResponse {
98                expected: "OK or null",
99                actual: format!("{other:?}"),
100            }),
101        }
102    }
103
104    fn name(&self) -> &str {
105        "JSON.SET"
106    }
107}
108
109/// JSON.GET key \[path ...\]
110///
111/// Returns the JSON value at one or more paths. When multiple paths are given,
112/// returns a JSON object mapping each path to its value.
113#[derive(Clone)]
114pub struct JsonGet {
115    key: CommandArg,
116    paths: Vec<String>,
117}
118
119impl JsonGet {
120    /// Create a new [`JsonGet`] command.
121    pub fn new(key: impl Into<CommandArg>) -> Self {
122        Self {
123            key: key.into(),
124            paths: Vec::new(),
125        }
126    }
127
128    /// Add a path to retrieve.
129    pub fn path(mut self, path: impl Into<String>) -> Self {
130        self.paths.push(path.into());
131        self
132    }
133
134    /// Add multiple paths to retrieve.
135    pub fn paths(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
136        self.paths.extend(paths.into_iter().map(Into::into));
137        self
138    }
139}
140
141impl Command for JsonGet {
142    type Response = Option<Bytes>;
143
144    fn to_frame(&self) -> Frame {
145        let mut args = vec![bulk("JSON.GET"), bulk(&self.key)];
146        for path in &self.paths {
147            args.push(bulk(path.as_str()));
148        }
149        array(args)
150    }
151
152    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
153        match frame {
154            Frame::BulkString(data) => Ok(data),
155            Frame::Null => Ok(None),
156            other => Err(RedisError::UnexpectedResponse {
157                expected: "bulk string or null",
158                actual: format!("{other:?}"),
159            }),
160        }
161    }
162
163    fn name(&self) -> &str {
164        "JSON.GET"
165    }
166
167    fn idempotent(&self) -> bool {
168        true
169    }
170}
171
172/// JSON.DEL key \[path\]
173///
174/// Deletes a value at `path` in the JSON document stored at `key`. Returns
175/// the number of paths deleted.
176#[derive(Clone)]
177pub struct JsonDel {
178    key: CommandArg,
179    path: Option<String>,
180}
181
182impl JsonDel {
183    /// Create a new [`JsonDel`] command.
184    pub fn new(key: impl Into<CommandArg>) -> Self {
185        Self {
186            key: key.into(),
187            path: None,
188        }
189    }
190
191    /// Set the path to delete. If omitted, the entire key is deleted.
192    pub fn path(mut self, path: impl Into<String>) -> Self {
193        self.path = Some(path.into());
194        self
195    }
196}
197
198impl Command for JsonDel {
199    type Response = i64;
200
201    fn to_frame(&self) -> Frame {
202        let mut args = vec![bulk("JSON.DEL"), bulk(&self.key)];
203        if let Some(path) = &self.path {
204            args.push(bulk(path.as_str()));
205        }
206        array(args)
207    }
208
209    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
210        match frame {
211            Frame::Integer(n) => Ok(n),
212            other => Err(RedisError::UnexpectedResponse {
213                expected: "integer",
214                actual: format!("{other:?}"),
215            }),
216        }
217    }
218
219    fn name(&self) -> &str {
220        "JSON.DEL"
221    }
222}
223
224/// JSON.MGET key \[key ...\] path
225///
226/// Returns the values at `path` from multiple keys. Returns `None` for keys
227/// where the path does not exist.
228#[derive(Clone)]
229pub struct JsonMGet {
230    keys: Vec<CommandArg>,
231    path: String,
232}
233
234impl JsonMGet {
235    /// Create a new [`JsonMGet`] command.
236    pub fn new(
237        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
238        path: impl Into<String>,
239    ) -> Self {
240        Self {
241            keys: keys.into_iter().map(Into::into).collect(),
242            path: path.into(),
243        }
244    }
245}
246
247impl Command for JsonMGet {
248    type Response = Vec<Option<Bytes>>;
249
250    fn to_frame(&self) -> Frame {
251        let mut args = vec![bulk("JSON.MGET")];
252        for key in &self.keys {
253            args.push(bulk(key));
254        }
255        args.push(bulk(self.path.as_str()));
256        array(args)
257    }
258
259    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
260        match frame {
261            Frame::Array(Some(frames)) => frames
262                .into_iter()
263                .map(|f| match f {
264                    Frame::BulkString(data) => Ok(data),
265                    Frame::Null => Ok(None),
266                    other => Err(RedisError::UnexpectedResponse {
267                        expected: "bulk string or null",
268                        actual: format!("{other:?}"),
269                    }),
270                })
271                .collect(),
272            other => Err(RedisError::UnexpectedResponse {
273                expected: "array",
274                actual: format!("{other:?}"),
275            }),
276        }
277    }
278
279    fn name(&self) -> &str {
280        "JSON.MGET"
281    }
282
283    fn idempotent(&self) -> bool {
284        true
285    }
286}
287
288/// JSON.TYPE key \[path\]
289///
290/// Returns the type of the JSON value at `path`.
291///
292/// Legacy paths return a single type directly. JSONPath expressions return a
293/// match array; this command returns the first matched type, or `None` when the
294/// key or path has no matches.
295#[derive(Clone)]
296pub struct JsonType {
297    key: CommandArg,
298    path: Option<String>,
299}
300
301impl JsonType {
302    /// Create a new [`JsonType`] command.
303    pub fn new(key: impl Into<CommandArg>) -> Self {
304        Self {
305            key: key.into(),
306            path: None,
307        }
308    }
309
310    /// Set the path to query. If omitted, returns the type of the root.
311    pub fn path(mut self, path: impl Into<String>) -> Self {
312        self.path = Some(path.into());
313        self
314    }
315}
316
317impl Command for JsonType {
318    type Response = Option<Bytes>;
319
320    fn to_frame(&self) -> Frame {
321        let mut args = vec![bulk("JSON.TYPE"), bulk(&self.key)];
322        if let Some(path) = &self.path {
323            args.push(bulk(path.as_str()));
324        }
325        array(args)
326    }
327
328    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
329        let mut current = frame;
330        loop {
331            match current {
332                Frame::BulkString(data) => return Ok(data),
333                Frame::SimpleString(data) => return Ok(Some(data)),
334                Frame::Null | Frame::Array(None) => return Ok(None),
335                Frame::Array(Some(frames)) => match frames.into_iter().next() {
336                    Some(first) => current = first,
337                    None => return Ok(None),
338                },
339                other => {
340                    return Err(RedisError::UnexpectedResponse {
341                        expected: "string, null, or JSONPath match array",
342                        actual: format!("{other:?}"),
343                    });
344                }
345            }
346        }
347    }
348
349    fn name(&self) -> &str {
350        "JSON.TYPE"
351    }
352
353    fn idempotent(&self) -> bool {
354        true
355    }
356}
357
358/// JSON.NUMINCRBY key path value
359///
360/// Increments the numeric value at `path` by `value`. Returns the new value
361/// as a string.
362#[derive(Clone)]
363pub struct JsonNumIncrBy {
364    key: CommandArg,
365    path: String,
366    value: f64,
367}
368
369impl JsonNumIncrBy {
370    /// Create a new [`JsonNumIncrBy`] command.
371    pub fn new(key: impl Into<CommandArg>, path: impl Into<String>, value: f64) -> Self {
372        Self {
373            key: key.into(),
374            path: path.into(),
375            value,
376        }
377    }
378}
379
380impl Command for JsonNumIncrBy {
381    type Response = Bytes;
382
383    fn to_frame(&self) -> Frame {
384        array(vec![
385            bulk("JSON.NUMINCRBY"),
386            bulk(&self.key),
387            bulk(self.path.as_str()),
388            bulk(self.value.to_string()),
389        ])
390    }
391
392    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
393        match frame {
394            Frame::BulkString(Some(data)) => Ok(data),
395            other => Err(RedisError::UnexpectedResponse {
396                expected: "bulk string",
397                actual: format!("{other:?}"),
398            }),
399        }
400    }
401
402    fn name(&self) -> &str {
403        "JSON.NUMINCRBY"
404    }
405}
406
407/// JSON.STRLEN key \[path\]
408///
409/// Returns the length of the JSON string at `path`. For multiple matches,
410/// returns an array of integers.
411#[derive(Clone)]
412pub struct JsonStrLen {
413    key: CommandArg,
414    path: Option<String>,
415}
416
417impl JsonStrLen {
418    /// Create a new [`JsonStrLen`] command.
419    pub fn new(key: impl Into<CommandArg>) -> Self {
420        Self {
421            key: key.into(),
422            path: None,
423        }
424    }
425
426    /// Set the path to query.
427    pub fn path(mut self, path: impl Into<String>) -> Self {
428        self.path = Some(path.into());
429        self
430    }
431}
432
433impl Command for JsonStrLen {
434    type Response = Frame;
435
436    fn to_frame(&self) -> Frame {
437        let mut args = vec![bulk("JSON.STRLEN"), bulk(&self.key)];
438        if let Some(path) = &self.path {
439            args.push(bulk(path.as_str()));
440        }
441        array(args)
442    }
443
444    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
445        Ok(frame)
446    }
447
448    fn name(&self) -> &str {
449        "JSON.STRLEN"
450    }
451
452    fn idempotent(&self) -> bool {
453        true
454    }
455}
456
457/// JSON.STRAPPEND key \[path\] value
458///
459/// Appends a string to the JSON string at `path`. Returns the new length(s).
460#[derive(Clone)]
461pub struct JsonStrAppend {
462    key: CommandArg,
463    path: Option<String>,
464    value: String,
465}
466
467impl JsonStrAppend {
468    /// Create a new [`JsonStrAppend`] command.
469    pub fn new(key: impl Into<CommandArg>, value: impl Into<String>) -> Self {
470        Self {
471            key: key.into(),
472            path: None,
473            value: value.into(),
474        }
475    }
476
477    /// Set the path to append to.
478    pub fn path(mut self, path: impl Into<String>) -> Self {
479        self.path = Some(path.into());
480        self
481    }
482}
483
484impl Command for JsonStrAppend {
485    type Response = Frame;
486
487    fn to_frame(&self) -> Frame {
488        let mut args = vec![bulk("JSON.STRAPPEND"), bulk(&self.key)];
489        if let Some(path) = &self.path {
490            args.push(bulk(path.as_str()));
491        }
492        args.push(bulk(self.value.as_str()));
493        array(args)
494    }
495
496    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
497        Ok(frame)
498    }
499
500    fn name(&self) -> &str {
501        "JSON.STRAPPEND"
502    }
503}
504
505/// JSON.ARRAPPEND key path value \[value ...\]
506///
507/// Appends one or more values to the array at `path`. Returns the new
508/// length(s) of the array.
509#[derive(Clone)]
510pub struct JsonArrAppend {
511    key: CommandArg,
512    path: String,
513    values: Vec<String>,
514}
515
516impl JsonArrAppend {
517    /// Create a new [`JsonArrAppend`] command.
518    pub fn new(key: impl Into<CommandArg>, path: impl Into<String>) -> Self {
519        Self {
520            key: key.into(),
521            path: path.into(),
522            values: Vec::new(),
523        }
524    }
525
526    /// Add a JSON value to append.
527    pub fn value(mut self, value: impl Into<String>) -> Self {
528        self.values.push(value.into());
529        self
530    }
531
532    /// Add multiple JSON values to append.
533    pub fn values(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
534        self.values.extend(values.into_iter().map(Into::into));
535        self
536    }
537}
538
539impl Command for JsonArrAppend {
540    type Response = Frame;
541
542    fn to_frame(&self) -> Frame {
543        let mut args = vec![
544            bulk("JSON.ARRAPPEND"),
545            bulk(&self.key),
546            bulk(self.path.as_str()),
547        ];
548        for value in &self.values {
549            args.push(bulk(value.as_str()));
550        }
551        array(args)
552    }
553
554    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
555        Ok(frame)
556    }
557
558    fn name(&self) -> &str {
559        "JSON.ARRAPPEND"
560    }
561}
562
563/// JSON.ARRLEN key \[path\]
564///
565/// Returns the length of the JSON array at `path`.
566#[derive(Clone)]
567pub struct JsonArrLen {
568    key: CommandArg,
569    path: Option<String>,
570}
571
572impl JsonArrLen {
573    /// Create a new [`JsonArrLen`] command.
574    pub fn new(key: impl Into<CommandArg>) -> Self {
575        Self {
576            key: key.into(),
577            path: None,
578        }
579    }
580
581    /// Set the path to query.
582    pub fn path(mut self, path: impl Into<String>) -> Self {
583        self.path = Some(path.into());
584        self
585    }
586}
587
588impl Command for JsonArrLen {
589    type Response = Frame;
590
591    fn to_frame(&self) -> Frame {
592        let mut args = vec![bulk("JSON.ARRLEN"), bulk(&self.key)];
593        if let Some(path) = &self.path {
594            args.push(bulk(path.as_str()));
595        }
596        array(args)
597    }
598
599    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
600        Ok(frame)
601    }
602
603    fn name(&self) -> &str {
604        "JSON.ARRLEN"
605    }
606
607    fn idempotent(&self) -> bool {
608        true
609    }
610}
611
612/// JSON.ARRINDEX key path value \[start \[stop\]\]
613///
614/// Searches for the first occurrence of `value` in the array at `path`.
615/// Returns the index, or -1 if not found.
616#[derive(Clone)]
617pub struct JsonArrIndex {
618    key: CommandArg,
619    path: String,
620    value: String,
621    start: Option<i64>,
622    stop: Option<i64>,
623}
624
625impl JsonArrIndex {
626    /// Create a new [`JsonArrIndex`] command.
627    pub fn new(
628        key: impl Into<CommandArg>,
629        path: impl Into<String>,
630        value: impl Into<String>,
631    ) -> Self {
632        Self {
633            key: key.into(),
634            path: path.into(),
635            value: value.into(),
636            start: None,
637            stop: None,
638        }
639    }
640
641    /// Set the start index for the search.
642    pub fn start(mut self, start: i64) -> Self {
643        self.start = Some(start);
644        self
645    }
646
647    /// Set the stop index for the search. Requires `start` to be set.
648    pub fn stop(mut self, stop: i64) -> Self {
649        self.stop = Some(stop);
650        self
651    }
652}
653
654impl Command for JsonArrIndex {
655    type Response = Frame;
656
657    fn to_frame(&self) -> Frame {
658        let mut args = vec![
659            bulk("JSON.ARRINDEX"),
660            bulk(&self.key),
661            bulk(self.path.as_str()),
662            bulk(self.value.as_str()),
663        ];
664        if let Some(start) = self.start {
665            args.push(bulk(start.to_string()));
666            if let Some(stop) = self.stop {
667                args.push(bulk(stop.to_string()));
668            }
669        }
670        array(args)
671    }
672
673    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
674        Ok(frame)
675    }
676
677    fn name(&self) -> &str {
678        "JSON.ARRINDEX"
679    }
680
681    fn idempotent(&self) -> bool {
682        true
683    }
684}
685
686/// JSON.ARRPOP key \[path \[index\]\]
687///
688/// Removes and returns the element at `index` from the array at `path`.
689/// Defaults to the last element (-1).
690#[derive(Clone)]
691pub struct JsonArrPop {
692    key: CommandArg,
693    path: Option<String>,
694    index: Option<i64>,
695}
696
697impl JsonArrPop {
698    /// Create a new [`JsonArrPop`] command.
699    pub fn new(key: impl Into<CommandArg>) -> Self {
700        Self {
701            key: key.into(),
702            path: None,
703            index: None,
704        }
705    }
706
707    /// Set the path of the array to pop from.
708    pub fn path(mut self, path: impl Into<String>) -> Self {
709        self.path = Some(path.into());
710        self
711    }
712
713    /// Set the index of the element to pop. Defaults to -1 (last element).
714    pub fn index(mut self, index: i64) -> Self {
715        self.index = Some(index);
716        self
717    }
718}
719
720impl Command for JsonArrPop {
721    type Response = Option<Bytes>;
722
723    fn to_frame(&self) -> Frame {
724        let mut args = vec![bulk("JSON.ARRPOP"), bulk(&self.key)];
725        if let Some(path) = &self.path {
726            args.push(bulk(path.as_str()));
727            if let Some(index) = self.index {
728                args.push(bulk(index.to_string()));
729            }
730        }
731        array(args)
732    }
733
734    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
735        match frame {
736            Frame::BulkString(data) => Ok(data),
737            Frame::Null => Ok(None),
738            other => Err(RedisError::UnexpectedResponse {
739                expected: "bulk string or null",
740                actual: format!("{other:?}"),
741            }),
742        }
743    }
744
745    fn name(&self) -> &str {
746        "JSON.ARRPOP"
747    }
748}
749
750/// JSON.OBJKEYS key \[path\]
751///
752/// Returns the keys of the JSON object at `path`.
753#[derive(Clone)]
754pub struct JsonObjKeys {
755    key: CommandArg,
756    path: Option<String>,
757}
758
759impl JsonObjKeys {
760    /// Create a new [`JsonObjKeys`] command.
761    pub fn new(key: impl Into<CommandArg>) -> Self {
762        Self {
763            key: key.into(),
764            path: None,
765        }
766    }
767
768    /// Set the path to query.
769    pub fn path(mut self, path: impl Into<String>) -> Self {
770        self.path = Some(path.into());
771        self
772    }
773}
774
775impl Command for JsonObjKeys {
776    type Response = Frame;
777
778    fn to_frame(&self) -> Frame {
779        let mut args = vec![bulk("JSON.OBJKEYS"), bulk(&self.key)];
780        if let Some(path) = &self.path {
781            args.push(bulk(path.as_str()));
782        }
783        array(args)
784    }
785
786    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
787        Ok(frame)
788    }
789
790    fn name(&self) -> &str {
791        "JSON.OBJKEYS"
792    }
793
794    fn idempotent(&self) -> bool {
795        true
796    }
797}
798
799/// JSON.OBJLEN key \[path\]
800///
801/// Returns the number of keys in the JSON object at `path`.
802#[derive(Clone)]
803pub struct JsonObjLen {
804    key: CommandArg,
805    path: Option<String>,
806}
807
808impl JsonObjLen {
809    /// Create a new [`JsonObjLen`] command.
810    pub fn new(key: impl Into<CommandArg>) -> Self {
811        Self {
812            key: key.into(),
813            path: None,
814        }
815    }
816
817    /// Set the path to query.
818    pub fn path(mut self, path: impl Into<String>) -> Self {
819        self.path = Some(path.into());
820        self
821    }
822}
823
824impl Command for JsonObjLen {
825    type Response = Frame;
826
827    fn to_frame(&self) -> Frame {
828        let mut args = vec![bulk("JSON.OBJLEN"), bulk(&self.key)];
829        if let Some(path) = &self.path {
830            args.push(bulk(path.as_str()));
831        }
832        array(args)
833    }
834
835    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
836        Ok(frame)
837    }
838
839    fn name(&self) -> &str {
840        "JSON.OBJLEN"
841    }
842
843    fn idempotent(&self) -> bool {
844        true
845    }
846}
847
848/// JSON.MERGE key path value
849///
850/// Merges a JSON value into the existing document at `path` in `key`. The
851/// value is merged recursively: existing keys are overwritten, new keys are
852/// added, and setting a key to `null` removes it. Returns `Ok(())` on success.
853#[derive(Clone)]
854pub struct JsonMerge {
855    key: CommandArg,
856    path: String,
857    value: String,
858}
859
860impl JsonMerge {
861    /// Create a new `JSON.MERGE` command.
862    pub fn new(
863        key: impl Into<CommandArg>,
864        path: impl Into<String>,
865        value: impl Into<String>,
866    ) -> Self {
867        Self {
868            key: key.into(),
869            path: path.into(),
870            value: value.into(),
871        }
872    }
873}
874
875impl Command for JsonMerge {
876    type Response = ();
877
878    fn to_frame(&self) -> Frame {
879        array(vec![
880            bulk("JSON.MERGE"),
881            bulk(&self.key),
882            bulk(self.path.as_str()),
883            bulk(self.value.as_str()),
884        ])
885    }
886
887    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
888        match frame {
889            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
890            Frame::Null => Ok(()),
891            other => Err(RedisError::UnexpectedResponse {
892                expected: "OK or null",
893                actual: format!("{other:?}"),
894            }),
895        }
896    }
897
898    fn name(&self) -> &str {
899        "JSON.MERGE"
900    }
901}
902
903/// JSON.MSET key path value \[key path value ...\]
904///
905/// Sets multiple JSON values across one or more keys in a single atomic call.
906/// Each triple is a `(key, path, value)` where `value` is a serialized JSON
907/// string. Returns `Ok(())` on success.
908///
909/// # Example
910///
911/// ```no_run
912/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
913/// use redis_tower_commands::JsonMSet;
914/// use redis_tower_core::RedisConnection;
915///
916/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
917///
918/// conn.execute(
919///     JsonMSet::new()
920///         .entry("k1", "$", "1")
921///         .entry("k2", "$", "{\"a\":2}"),
922/// )
923/// .await?;
924/// # Ok(())
925/// # }
926/// ```
927#[derive(Clone, Default)]
928pub struct JsonMSet {
929    entries: Vec<(CommandArg, String, String)>,
930}
931
932impl JsonMSet {
933    /// Create an empty `JSON.MSET` command.
934    pub fn new() -> Self {
935        Self {
936            entries: Vec::new(),
937        }
938    }
939
940    /// Add a `(key, path, value)` triple. `value` is a serialized JSON string.
941    pub fn entry(
942        mut self,
943        key: impl Into<CommandArg>,
944        path: impl Into<String>,
945        value: impl Into<String>,
946    ) -> Self {
947        self.entries.push((key.into(), path.into(), value.into()));
948        self
949    }
950}
951
952impl Command for JsonMSet {
953    type Response = ();
954
955    fn to_frame(&self) -> Frame {
956        let mut args = vec![bulk("JSON.MSET")];
957        for (key, path, value) in &self.entries {
958            args.push(bulk(key));
959            args.push(bulk(path.as_str()));
960            args.push(bulk(value.as_str()));
961        }
962        array(args)
963    }
964
965    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
966        match frame {
967            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
968            other => Err(RedisError::UnexpectedResponse {
969                expected: "OK",
970                actual: format!("{other:?}"),
971            }),
972        }
973    }
974
975    fn name(&self) -> &str {
976        "JSON.MSET"
977    }
978}
979
980/// JSON.TOGGLE key path
981///
982/// Toggles boolean values stored at the matching paths. Returns the raw
983/// RedisJSON reply: an array of new booleans (`1`/`0`, with nil for a path
984/// whose value is not a boolean) under a JSONPath, or a scalar under a legacy
985/// path.
986///
987/// # Example
988///
989/// ```no_run
990/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
991/// use redis_tower_commands::JsonToggle;
992/// use redis_tower_core::RedisConnection;
993///
994/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
995///
996/// let toggled = conn.execute(JsonToggle::new("k", "$.enabled")).await?;
997/// # let _ = toggled;
998/// # Ok(())
999/// # }
1000/// ```
1001#[derive(Clone)]
1002pub struct JsonToggle {
1003    key: CommandArg,
1004    path: String,
1005}
1006
1007impl JsonToggle {
1008    /// Create a new [`JsonToggle`] command.
1009    pub fn new(key: impl Into<CommandArg>, path: impl Into<String>) -> Self {
1010        Self {
1011            key: key.into(),
1012            path: path.into(),
1013        }
1014    }
1015}
1016
1017impl Command for JsonToggle {
1018    type Response = Frame;
1019
1020    fn to_frame(&self) -> Frame {
1021        array(vec![
1022            bulk("JSON.TOGGLE"),
1023            bulk(&self.key),
1024            bulk(self.path.as_str()),
1025        ])
1026    }
1027
1028    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1029        Ok(frame)
1030    }
1031
1032    fn name(&self) -> &str {
1033        "JSON.TOGGLE"
1034    }
1035}
1036
1037/// JSON.CLEAR key \[path\]
1038///
1039/// Clears container values (arrays and objects) and sets numeric values to `0`
1040/// at the matching paths. Returns the number of values cleared.
1041///
1042/// # Example
1043///
1044/// ```no_run
1045/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1046/// use redis_tower_commands::JsonClear;
1047/// use redis_tower_core::RedisConnection;
1048///
1049/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1050///
1051/// let cleared = conn.execute(JsonClear::new("k").path("$.items")).await?;
1052/// # let _ = cleared;
1053/// # Ok(())
1054/// # }
1055/// ```
1056#[derive(Clone)]
1057pub struct JsonClear {
1058    key: CommandArg,
1059    path: Option<String>,
1060}
1061
1062impl JsonClear {
1063    /// Create a new [`JsonClear`] command.
1064    pub fn new(key: impl Into<CommandArg>) -> Self {
1065        Self {
1066            key: key.into(),
1067            path: None,
1068        }
1069    }
1070
1071    /// Limit the clear to the given path. Defaults to the root.
1072    pub fn path(mut self, path: impl Into<String>) -> Self {
1073        self.path = Some(path.into());
1074        self
1075    }
1076}
1077
1078impl Command for JsonClear {
1079    type Response = i64;
1080
1081    fn to_frame(&self) -> Frame {
1082        let mut args = vec![bulk("JSON.CLEAR"), bulk(&self.key)];
1083        if let Some(path) = &self.path {
1084            args.push(bulk(path.as_str()));
1085        }
1086        array(args)
1087    }
1088
1089    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1090        match frame {
1091            Frame::Integer(n) => Ok(n),
1092            other => Err(RedisError::UnexpectedResponse {
1093                expected: "integer",
1094                actual: format!("{other:?}"),
1095            }),
1096        }
1097    }
1098
1099    fn name(&self) -> &str {
1100        "JSON.CLEAR"
1101    }
1102}
1103
1104/// JSON.ARRINSERT key path index value \[value ...\]
1105///
1106/// Inserts one or more JSON values into the array at `path` before `index`.
1107/// Each `value` is a serialized JSON string. Returns the raw RedisJSON reply:
1108/// an array of new array lengths (nil where the path is not an array) under a
1109/// JSONPath, or a single length under a legacy path.
1110///
1111/// # Example
1112///
1113/// ```no_run
1114/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1115/// use redis_tower_commands::JsonArrInsert;
1116/// use redis_tower_core::RedisConnection;
1117///
1118/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1119///
1120/// let lengths = conn
1121///     .execute(JsonArrInsert::new("k", "$.items", 0).value("1").value("2"))
1122///     .await?;
1123/// # let _ = lengths;
1124/// # Ok(())
1125/// # }
1126/// ```
1127#[derive(Clone)]
1128pub struct JsonArrInsert {
1129    key: CommandArg,
1130    path: String,
1131    index: i64,
1132    values: Vec<String>,
1133}
1134
1135impl JsonArrInsert {
1136    /// Create a new [`JsonArrInsert`] command.
1137    pub fn new(key: impl Into<CommandArg>, path: impl Into<String>, index: i64) -> Self {
1138        Self {
1139            key: key.into(),
1140            path: path.into(),
1141            index,
1142            values: Vec::new(),
1143        }
1144    }
1145
1146    /// Add a JSON value to insert.
1147    pub fn value(mut self, value: impl Into<String>) -> Self {
1148        self.values.push(value.into());
1149        self
1150    }
1151
1152    /// Add multiple JSON values to insert.
1153    pub fn values(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
1154        self.values.extend(values.into_iter().map(Into::into));
1155        self
1156    }
1157}
1158
1159impl Command for JsonArrInsert {
1160    type Response = Frame;
1161
1162    fn to_frame(&self) -> Frame {
1163        let mut args = vec![
1164            bulk("JSON.ARRINSERT"),
1165            bulk(&self.key),
1166            bulk(self.path.as_str()),
1167            bulk(self.index.to_string()),
1168        ];
1169        for value in &self.values {
1170            args.push(bulk(value.as_str()));
1171        }
1172        array(args)
1173    }
1174
1175    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1176        Ok(frame)
1177    }
1178
1179    fn name(&self) -> &str {
1180        "JSON.ARRINSERT"
1181    }
1182}
1183
1184/// JSON.ARRTRIM key path start stop
1185///
1186/// Trims the array at `path` to the inclusive `[start, stop]` range. Returns
1187/// the raw RedisJSON reply: an array of new array lengths (nil where the path
1188/// is not an array) under a JSONPath, or a single length under a legacy path.
1189///
1190/// # Example
1191///
1192/// ```no_run
1193/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1194/// use redis_tower_commands::JsonArrTrim;
1195/// use redis_tower_core::RedisConnection;
1196///
1197/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1198///
1199/// let lengths = conn
1200///     .execute(JsonArrTrim::new("k", "$.items", 0, 10))
1201///     .await?;
1202/// # let _ = lengths;
1203/// # Ok(())
1204/// # }
1205/// ```
1206#[derive(Clone)]
1207pub struct JsonArrTrim {
1208    key: CommandArg,
1209    path: String,
1210    start: i64,
1211    stop: i64,
1212}
1213
1214impl JsonArrTrim {
1215    /// Create a new [`JsonArrTrim`] command.
1216    pub fn new(key: impl Into<CommandArg>, path: impl Into<String>, start: i64, stop: i64) -> Self {
1217        Self {
1218            key: key.into(),
1219            path: path.into(),
1220            start,
1221            stop,
1222        }
1223    }
1224}
1225
1226impl Command for JsonArrTrim {
1227    type Response = Frame;
1228
1229    fn to_frame(&self) -> Frame {
1230        array(vec![
1231            bulk("JSON.ARRTRIM"),
1232            bulk(&self.key),
1233            bulk(self.path.as_str()),
1234            bulk(self.start.to_string()),
1235            bulk(self.stop.to_string()),
1236        ])
1237    }
1238
1239    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1240        Ok(frame)
1241    }
1242
1243    fn name(&self) -> &str {
1244        "JSON.ARRTRIM"
1245    }
1246}
1247
1248/// JSON.FORGET key \[path\]
1249///
1250/// An alias for [`JsonDel`]. Deletes a value at `path` in the JSON document
1251/// stored at `key` and returns the number of paths deleted.
1252#[derive(Clone)]
1253pub struct JsonForget {
1254    key: CommandArg,
1255    path: Option<String>,
1256}
1257
1258impl JsonForget {
1259    /// Create a new [`JsonForget`] command.
1260    pub fn new(key: impl Into<CommandArg>) -> Self {
1261        Self {
1262            key: key.into(),
1263            path: None,
1264        }
1265    }
1266
1267    /// Set the path to delete. If omitted, the entire key is deleted.
1268    pub fn path(mut self, path: impl Into<String>) -> Self {
1269        self.path = Some(path.into());
1270        self
1271    }
1272}
1273
1274impl Command for JsonForget {
1275    type Response = i64;
1276
1277    fn to_frame(&self) -> Frame {
1278        let mut args = vec![bulk("JSON.FORGET"), bulk(&self.key)];
1279        if let Some(path) = &self.path {
1280            args.push(bulk(path.as_str()));
1281        }
1282        array(args)
1283    }
1284
1285    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1286        match frame {
1287            Frame::Integer(n) => Ok(n),
1288            other => Err(RedisError::UnexpectedResponse {
1289                expected: "integer",
1290                actual: format!("{other:?}"),
1291            }),
1292        }
1293    }
1294
1295    fn name(&self) -> &str {
1296        "JSON.FORGET"
1297    }
1298}
1299
1300/// JSON.DEBUG MEMORY key \[path\]
1301///
1302/// Reports the memory usage in bytes of a value in the JSON document stored at
1303/// `key`. With no path the size of the whole document is returned.
1304#[derive(Clone)]
1305pub struct JsonDebugMemory {
1306    key: CommandArg,
1307    path: Option<String>,
1308}
1309
1310impl JsonDebugMemory {
1311    /// Create a new [`JsonDebugMemory`] command.
1312    pub fn new(key: impl Into<CommandArg>) -> Self {
1313        Self {
1314            key: key.into(),
1315            path: None,
1316        }
1317    }
1318
1319    /// Report memory for the value at a specific (legacy) path.
1320    pub fn path(mut self, path: impl Into<String>) -> Self {
1321        self.path = Some(path.into());
1322        self
1323    }
1324}
1325
1326impl Command for JsonDebugMemory {
1327    type Response = i64;
1328
1329    fn to_frame(&self) -> Frame {
1330        let mut args = vec![bulk("JSON.DEBUG"), bulk("MEMORY"), bulk(&self.key)];
1331        if let Some(path) = &self.path {
1332            args.push(bulk(path.as_str()));
1333        }
1334        array(args)
1335    }
1336
1337    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1338        match frame {
1339            Frame::Integer(n) => Ok(n),
1340            other => Err(RedisError::UnexpectedResponse {
1341                expected: "integer",
1342                actual: format!("{other:?}"),
1343            }),
1344        }
1345    }
1346
1347    fn name(&self) -> &str {
1348        "JSON.DEBUG MEMORY"
1349    }
1350
1351    fn idempotent(&self) -> bool {
1352        true
1353    }
1354}
1355
1356#[cfg(test)]
1357mod tests {
1358    use super::*;
1359    use redis_tower_core::Command;
1360    use redis_tower_protocol::Frame;
1361    use redis_tower_protocol::helpers::{array, bulk};
1362
1363    #[test]
1364    fn idempotency_flags() {
1365        // Read-only commands are safe to retry.
1366        assert!(JsonGet::new("k").idempotent());
1367        // Mutating commands keep the default (false).
1368        assert!(!JsonSet::new("k", "$", "1").idempotent());
1369    }
1370
1371    #[test]
1372    fn json_mset_to_frame() {
1373        let cmd = JsonMSet::new()
1374            .entry("k1", "$", "1")
1375            .entry("k2", "$", "{\"a\":2}");
1376        assert_eq!(
1377            cmd.to_frame(),
1378            array(vec![
1379                bulk("JSON.MSET"),
1380                bulk("k1"),
1381                bulk("$"),
1382                bulk("1"),
1383                bulk("k2"),
1384                bulk("$"),
1385                bulk("{\"a\":2}"),
1386            ])
1387        );
1388    }
1389
1390    #[test]
1391    fn json_toggle_to_frame() {
1392        let cmd = JsonToggle::new("k", "$.enabled");
1393        assert_eq!(
1394            cmd.to_frame(),
1395            array(vec![bulk("JSON.TOGGLE"), bulk("k"), bulk("$.enabled")])
1396        );
1397    }
1398
1399    #[test]
1400    fn json_toggle_parse_returns_raw_frame() {
1401        let cmd = JsonToggle::new("k", "$.a");
1402        let frame = array(vec![Frame::Integer(1), Frame::Null]);
1403        assert_eq!(cmd.parse_response(frame.clone()).unwrap(), frame);
1404    }
1405
1406    #[test]
1407    fn json_clear_default_path_to_frame() {
1408        let cmd = JsonClear::new("k");
1409        assert_eq!(cmd.to_frame(), array(vec![bulk("JSON.CLEAR"), bulk("k")]));
1410    }
1411
1412    #[test]
1413    fn json_clear_with_path_to_frame() {
1414        let cmd = JsonClear::new("k").path("$.items");
1415        assert_eq!(
1416            cmd.to_frame(),
1417            array(vec![bulk("JSON.CLEAR"), bulk("k"), bulk("$.items")])
1418        );
1419    }
1420
1421    #[test]
1422    fn json_arrinsert_to_frame() {
1423        let cmd = JsonArrInsert::new("k", "$.items", 0).value("1").value("2");
1424        assert_eq!(
1425            cmd.to_frame(),
1426            array(vec![
1427                bulk("JSON.ARRINSERT"),
1428                bulk("k"),
1429                bulk("$.items"),
1430                bulk("0"),
1431                bulk("1"),
1432                bulk("2"),
1433            ])
1434        );
1435    }
1436
1437    #[test]
1438    fn json_arrtrim_to_frame() {
1439        let cmd = JsonArrTrim::new("k", "$.items", 0, 10);
1440        assert_eq!(
1441            cmd.to_frame(),
1442            array(vec![
1443                bulk("JSON.ARRTRIM"),
1444                bulk("k"),
1445                bulk("$.items"),
1446                bulk("0"),
1447                bulk("10"),
1448            ])
1449        );
1450    }
1451
1452    #[test]
1453    fn json_forget_to_frame() {
1454        let cmd = JsonForget::new("doc").path("$.a");
1455        assert_eq!(
1456            cmd.to_frame(),
1457            array(vec![bulk("JSON.FORGET"), bulk("doc"), bulk("$.a")])
1458        );
1459        assert_eq!(
1460            JsonForget::new("doc").to_frame(),
1461            array(vec![bulk("JSON.FORGET"), bulk("doc")])
1462        );
1463    }
1464
1465    #[test]
1466    fn json_forget_parse_integer() {
1467        let cmd = JsonForget::new("doc");
1468        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
1469    }
1470
1471    #[test]
1472    fn json_debug_memory_to_frame() {
1473        assert_eq!(
1474            JsonDebugMemory::new("doc").to_frame(),
1475            array(vec![bulk("JSON.DEBUG"), bulk("MEMORY"), bulk("doc")])
1476        );
1477        assert_eq!(
1478            JsonDebugMemory::new("doc").path(".").to_frame(),
1479            array(vec![
1480                bulk("JSON.DEBUG"),
1481                bulk("MEMORY"),
1482                bulk("doc"),
1483                bulk(".")
1484            ])
1485        );
1486    }
1487
1488    #[test]
1489    fn json_debug_memory_parse_integer() {
1490        let cmd = JsonDebugMemory::new("doc");
1491        assert_eq!(cmd.parse_response(Frame::Integer(64)).unwrap(), 64);
1492        assert!(cmd.idempotent());
1493    }
1494
1495    #[test]
1496    fn json_type_parses_legacy_and_jsonpath_responses() {
1497        let cmd = JsonType::new("doc").path("$.name");
1498
1499        assert_eq!(
1500            cmd.parse_response(Frame::BulkString(Some(Bytes::from("string"))))
1501                .unwrap(),
1502            Some(Bytes::from("string"))
1503        );
1504        assert_eq!(
1505            cmd.parse_response(Frame::Array(Some(vec![Frame::Array(Some(vec![
1506                Frame::BulkString(Some(Bytes::from("string"))),
1507            ]))])))
1508            .unwrap(),
1509            Some(Bytes::from("string"))
1510        );
1511    }
1512
1513    #[test]
1514    fn json_type_returns_none_for_missing_jsonpath() {
1515        let cmd = JsonType::new("doc").path("$.missing");
1516
1517        assert_eq!(
1518            cmd.parse_response(Frame::Array(Some(Vec::new()))).unwrap(),
1519            None
1520        );
1521        assert_eq!(
1522            cmd.parse_response(Frame::Array(Some(vec![Frame::Array(Some(Vec::new()))])))
1523                .unwrap(),
1524            None
1525        );
1526    }
1527}