Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 65 additions & 53 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::redisjson::SetOptions;

use serde_json::{Number, Value};

use serde::Serialize;
use serde::{Serialize, Serializer};
use std::collections::HashMap;
const JSON_ROOT_PATH: &str = "$";
const JSON_ROOT_PATH_LEGACY: &str = ".";
Expand Down Expand Up @@ -53,6 +53,23 @@ const JSONGET_SUBCOMMANDS_MAXSTRLEN: usize = max_strlen(&[
CMD_ARG_FORMAT,
]);

enum Values<'a, V: SelectValue> {
Single(&'a V),
Multi(Vec<&'a V>),
}

impl<'a, V: SelectValue> Serialize for Values<'a, V> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Values::Single(v) => v.serialize(serializer),
Values::Multi(v) => v.serialize(serializer),
}
}
}

pub struct KeyValue<'a, V: SelectValue> {
val: &'a V,
}
Expand Down Expand Up @@ -151,71 +168,55 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
String::from_utf8(out.into_inner()).unwrap()
}

fn to_json_legacy(
fn to_json_multi(
&'a self,
paths: &mut Vec<Path>,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
is_legacy: bool,
) -> Result<RedisValue, Error> {
if paths.len() > 1 {
// TODO: Creating a temp doc here duplicates memory usage. This can be very memory inefficient.
// A better way would be to create a doc of references to the original doc but no current support
// in serde_json. I'm going for this implementation anyway because serde_json isn't supposed to be
// memory efficient and we're using it anyway. See https://github.com/serde-rs/json/issues/635.
let mut missing_path = None;
let temp_doc = paths.drain(..).fold(HashMap::new(), |mut acc, path| {
let mut selector = Selector::new();
selector.value(self.val);
if selector.str_path(path.get_path()).is_err() {
return acc;
}
let value = match selector.select() {
Ok(s) => s.first().copied(),
Err(_) => None,
};
if value.is_none() && missing_path.is_none() {
missing_path = Some(path.get_original().to_string());
}
acc.insert(path.get_original(), value);
acc
});
if let Some(p) = missing_path {
return Err(format!("ERR path {} does not exist", p).into());
// TODO: Creating a temp doc here duplicates memory usage. This can be very memory inefficient.
// A better way would be to create a doc of references to the original doc but no current support
// in serde_json. I'm going for this implementation anyway because serde_json isn't supposed to be
// memory efficient and we're using it anyway. See https://github.com/serde-rs/json/issues/635.
let mut missing_path = None;
let temp_doc = paths.drain(..).fold(HashMap::new(), |mut acc, path: Path| {
let mut selector = Selector::new();
selector.value(self.val);
if selector.str_path(path.get_path()).is_err() {
return acc;
}
let value = match selector.select() {
Ok(s) if is_legacy && !s.is_empty() => Some(Values::Single(s[0])),
Ok(s) if !is_legacy => Some(Values::Multi(s)),
_ => None,
};

Ok(Self::serialize_object(&temp_doc, indent, newline, space).into())
} else {
Ok(
Self::serialize_object(
self.get_first(paths[0].get_path())?,
indent,
newline,
space,
)
.into(),
)
if value.is_none() && missing_path.is_none() {
missing_path = Some(path.get_original().to_string());
}
acc.insert(path.get_original(), value);
acc
});
if let Some(p) = missing_path {
return Err(format!("ERR path {} does not exist", p).into());
}
Ok(Self::serialize_object(&temp_doc, indent, newline, space).into())
}

fn to_json_multi(
fn to_json_single(
&'a self,
paths: &Vec<Path>,
path: &str,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
is_legacy: bool,
) -> Result<RedisValue, Error> {
if paths.len() > 1 {
let mut res: Vec<Vec<&V>> = vec![];
for path in paths {
let values = self.get_values(path.get_path())?;
res.push(values);
}
Ok(Self::serialize_object(&res, indent, newline, space).into())
if is_legacy {
Ok(self.to_string_single(path, indent, newline, space)?.into())
} else {
Ok(self
.to_string_multi(paths[0].get_path(), indent, newline, space)?
.into())
Ok(self.to_string_multi(path, indent, newline, space)?.into())
}
}

Expand All @@ -231,10 +232,10 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
return Err("Soon to come...".into());
}
let is_legacy = !paths.iter().any(|p| !p.is_legacy());
if is_legacy {
self.to_json_legacy(paths, indent, newline, space)
if paths.len() > 1 {
self.to_json_multi(paths, indent, newline, space, is_legacy)
} else {
self.to_json_multi(paths, indent, newline, space)
self.to_json_single(paths[0].get_path(), indent, newline, space, is_legacy)
}
}

Expand Down Expand Up @@ -330,6 +331,17 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
Self::serialize(results, format)
}

pub fn to_string_single(
&self,
path: &str,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
) -> Result<String, Error> {
let result = self.get_first(path)?;
Ok(Self::serialize_object(&result, indent, newline, space))
}

pub fn to_string_multi(
&self,
path: &str,
Expand Down Expand Up @@ -785,7 +797,7 @@ pub fn command_json_mget<M: Manager>(
let to_string =
|doc: &M::V| KeyValue::new(doc).to_string_multi(path.get_path(), None, None, None);
let to_string_legacy =
|doc: &M::V| KeyValue::new(doc).to_string(path.get_path(), Format::JSON);
|doc: &M::V| KeyValue::new(doc).to_string_single(path.get_path(), None, None, None);
let is_legacy = path.is_legacy();

let results: Result<Vec<RedisValue>, RedisError> = keys
Expand Down
15 changes: 11 additions & 4 deletions tests/pytest/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,21 +148,28 @@ def testSetAndGetCommands(env):

# Test multi paths
res = r.execute_command('JSON.GET', 'doc1', '$..tm', '$..nu')
r.assertEqual(res, '[[[46,876.85],[134.761,"jcoels",null]],[[377,"qda",true]]]')
r.assertEqual(json.loads(res), {"$..tm": [[46, 876.85], [134.761, "jcoels", None]], "$..nu": [[377, "qda", True]]})
# Test multi paths - if one path is none-legacy - result format is not legacy
res = r.execute_command('JSON.GET', 'doc1', '..tm', '$..nu')
r.assertEqual(res, '[[[46,876.85],[134.761,"jcoels",null]],[[377,"qda",true]]]')
r.assertEqual(json.loads(res), {"..tm": [[46, 876.85], [134.761, "jcoels", None]], "$..nu": [[377, "qda", True]]})
# Test multi paths with formatting (using the same path in order to get a map and still avoid failure due to undefined ordering between map keys)
res = r.execute_command('JSON.GET', 'doc2', 'INDENT', '\\t', 'NEWLINE', '\\n', 'SPACE', ' ', '$..a', '$..a')
r.assertEqual(res, '{\\n\\t"$..a": [\\n\\t\\t4.2,\\n\\t\\t4.2\\n\\t]\\n}')

# Test missing key
r.assertIsNone(r.execute_command('JSON.GET', 'docX', '..tm', '$..nu'))
# Test missing path
res = r.execute_command('JSON.GET', 'doc1', '..tm', '$..back_in_nov')
r.assertEqual(res, '[[[46,876.85],[134.761,"jcoels",null]],[]]')
r.assertEqual(json.loads(res), {"$..back_in_nov": [], "..tm": [[46, 876.85], [134.761, "jcoels", None]]})
res = r.execute_command('JSON.GET', 'doc2', '..a', '..b', '$.back_in_nov')
r.assertEqual(res, '[[4.2,4.2],[3],[]]')
r.assertEqual(json.loads(res), {"$.back_in_nov": [], "..a": [4.2, 4.2], "..b": [3]})

# Test legacy multi path (all paths are legacy)
res = r.execute_command('JSON.GET', 'doc1', '..nu', '..tm')
r.assertEqual(json.loads(res), json.loads('{"..nu":[377,"qda",true],"..tm":[46,876.85]}'))
# Test multi paths with formatting (using the same path in order to get a map and still avoid failure due to undefined ordering between map keys)
res = r.execute_command('JSON.GET', 'doc2', 'INDENT', '\\t', 'NEWLINE', '\\n', 'SPACE', ' ', '..a', '..a')
r.assertEqual(res, '{\\n\\t"..a": 4.2\\n}')
# Test legacy single path
res = r.execute_command('JSON.GET', 'doc1', '..tm')
r.assertEqual(res, '[46,876.85]')
Expand Down