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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "redisjson"
version = "2.0.4"
version = "2.0.5"
authors = ["Gavrie Philipson <gavrie@redislabs.com>"]
edition = "2018"

Expand Down
157 changes: 93 additions & 64 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,12 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
let v = self.get_first(path.get_path())?;
Ok(self.resp_serialize_inner(v))
} else {
let res = self.get_values(path.get_path())?;
if !res.is_empty() {
Ok(res
.iter()
.map(|v| self.resp_serialize_inner(v))
.collect::<Vec<RedisValue>>()
.into())
} else {
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path.get_original()),
))
}
Ok(self
.get_values(path.get_path())?
.iter()
.map(|v| self.resp_serialize_inner(v))
.collect::<Vec<RedisValue>>()
.into())
}
}

Expand Down Expand Up @@ -398,15 +392,17 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
}
}

pub fn obj_len(&self, path: &str) -> Result<usize, Error> {
let first = self.get_first(path)?;
match first.get_type() {
SelectValueType::Object => Ok(first.len().unwrap()),
_ => Err(
err_msg_json_expected("object", self.get_type(path).unwrap().as_str())
.as_str()
.into(),
),
pub fn obj_len(&self, path: &str) -> Result<ObjectLen, Error> {
match self.get_first(path) {
Ok(first) => match first.get_type() {
SelectValueType::Object => Ok(ObjectLen::Len(first.len().unwrap())),
_ => Err(
err_msg_json_expected("object", self.get_type(path).unwrap().as_str())
.as_str()
.into(),
),
},
_ => Ok(ObjectLen::NoneExisting),
}
}

Expand Down Expand Up @@ -478,12 +474,13 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
end: i64,
) -> Result<RedisValue, Error> {
let arr = self.get_first(path)?;
Ok(
match self.arr_first_index_single(arr, &scalar_value, start, end) {
FoundIndex::NotArray => RedisValue::Integer(-1),
i => i.into(),
},
)
match self.arr_first_index_single(arr, &scalar_value, start, end) {
FoundIndex::NotArray => Err(Error::from(err_msg_json_expected(
"array",
self.get_type(path).unwrap().as_str(),
))),
i => Ok(i.into()),
}
}

/// Returns first array index of `v` in `arr`, or NotFound if not found in `arr`, or NotArray if `arr` is not an array
Expand Down Expand Up @@ -722,9 +719,7 @@ where
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_paths(res, f)),
_ => Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path),
)),
_ => Ok(vec![]),
}
}

Expand All @@ -739,9 +734,7 @@ where
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_values(res, f)),
_ => Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path),
)),
_ => Ok(vec![]),
}
}

Expand Down Expand Up @@ -1377,6 +1370,12 @@ impl From<FoundIndex> for RedisValue {
}
}

pub enum ObjectLen {
Len(usize),
NoneExisting,
NotObject,
}

pub fn command_json_arr_index<M: Manager>(
manager: M,
ctx: &Context,
Expand All @@ -1403,15 +1402,20 @@ pub fn command_json_arr_index<M: Manager>(
)));
}

let res = key
.get_value()?
.map_or(Ok(RedisValue::Integer(-1)), |doc| {
let res = key.get_value()?.map_or_else(
|| {
Err(Error::from(err_msg_json_path_doesnt_exist_with_param(
path.get_original(),
)))
},
|doc| {
if path.is_legacy() {
KeyValue::new(doc).arr_index_legacy(path.get_path(), scalar_value, start, end)
} else {
KeyValue::new(doc).arr_index(path.get_path(), scalar_value, start, end)
}
})?;
},
)?;

Ok(res)
}
Expand Down Expand Up @@ -1527,18 +1531,30 @@ pub fn command_json_arr_len<M: Manager>(
return Err(RedisError::nonexistent_key());
}
};
// let root = key
// .get_value()?
// .ok_or_else(RedisError::nonexistent_key)?;
let values = find_all_values(path.get_path(), root, |v| {
v.get_type() == SelectValueType::Array
})?;

if is_legacy && values.is_empty() {
return Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path.get_original()),
));
}
let mut res = vec![];
for v in values {
let cur_val: RedisValue = match v {
Some(v) => (v.len().unwrap() as i64).into(),
_ => RedisValue::Null,
_ => {
if !is_legacy {
RedisValue::Null
} else {
return Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(
path.get_original(),
"not an array",
),
));
}
}
};
if !is_legacy {
res.push(cur_val);
Expand Down Expand Up @@ -1744,20 +1760,19 @@ fn json_obj_keys<M>(redis_key: &mut M::ReadHolder, path: &str) -> RedisResult
where
M: Manager,
{
let root = redis_key.get_value()?;
let res: RedisValue = match root {
Some(root) => {
let values = find_all_values(path, root, |v| v.get_type() == SelectValueType::Object)?;
let mut res: Vec<RedisValue> = vec![];
for v in values {
res.push(match v {
Some(v) => v.keys().unwrap().collect::<Vec<&str>>().into(),
_ => RedisValue::Null,
});
}
res.into()
let root = redis_key
.get_value()?
.ok_or_else(RedisError::nonexistent_key)?;
let res: RedisValue = {
let values = find_all_values(path, root, |v| v.get_type() == SelectValueType::Object)?;
let mut res: Vec<RedisValue> = vec![];
for v in values {
res.push(match v {
Some(v) => v.keys().unwrap().collect::<Vec<&str>>().into(),
_ => RedisValue::Null,
});
}
None => RedisValue::Null,
res.into()
};
Ok(res.into())
}
Expand All @@ -1766,14 +1781,21 @@ fn json_obj_keys_legacy<M>(redis_key: &mut M::ReadHolder, path: &str) -> RedisRe
where
M: Manager,
{
let value = match redis_key.get_value()? {
Some(doc) => KeyValue::new(doc)
.obj_keys(path)?
.collect::<Vec<&str>>()
.into(),
None => RedisValue::Null,
let root = match redis_key.get_value()? {
Some(v) => v,
_ => return Ok(RedisValue::Null),
};
let value = match KeyValue::new(root).get_first(path) {
Ok(v) => match v.get_type() {
SelectValueType::Object => v.keys().unwrap().collect::<Vec<&str>>().into(),
_ => {
return Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not an object"),
))
}
},
_ => RedisValue::Null,
};

Ok(value)
}

Expand Down Expand Up @@ -1808,7 +1830,11 @@ where
})
.collect::<Vec<RedisValue>>()
.into(),
None => RedisValue::Null,
None => {
return Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not an object"),
))
}
};
Ok(res)
}
Expand All @@ -1818,7 +1844,10 @@ where
M: Manager,
{
match redis_key.get_value()? {
Some(doc) => Ok(RedisValue::Integer(KeyValue::new(doc).obj_len(path)? as i64)),
Some(doc) => match KeyValue::new(doc).obj_len(path)? {
ObjectLen::Len(l) => Ok(RedisValue::Integer(l as i64)),
_ => Ok(RedisValue::Null),
},
None => Ok(RedisValue::Null),
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ macro_rules! redis_json_module_create {(
["json.objkeys", json_obj_keys, "readonly", 1,1,1],
["json.objlen", json_obj_len, "readonly", 1,1,1],
["json.clear", json_clear, "write", 1,1,1],
["json.debug", json_debug, "readonly", 1,1,1],
["json.debug", json_debug, "readonly", 2,2,1],
["json.forget", json_del, "write", 1,1,1],
["json.resp", json_resp, "readonly", 1,1,1],
["json._cacheinfo", json_cache_info, "readonly", 1,1,1],
Expand All @@ -463,6 +463,6 @@ redis_json_module_create! {
data_types: [REDIS_JSON_TYPE],
pre_command_function: pre_command,
get_manage: Some(manager::RedisJsonKeyManager{phantom:PhantomData}),
version: 02_00_04,
version: 02_00_05,
init: dummy_init,
}
15 changes: 8 additions & 7 deletions tests/pytest/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,19 +745,20 @@ def testLenCommands(env):
r.assertEqual(r.execute_command('JSON.ARRLEN', 'test', '.arr'), 6)

# test elements with undefined lengths
r.assertEqual(r.execute_command('JSON.ARRLEN', 'test', '.bool'), None)
r.expect('JSON.STRLEN', 'test', '.none').raiseError()
r.expect('JSON.OBJLEN', 'test', '.int').raiseError()
r.expect('JSON.STRLEN', 'test', '.num').raiseError()
r.expect('JSON.ARRLEN', 'test', '.bool').raiseError().contains("not an array")
r.expect('JSON.STRLEN', 'test', '.none').raiseError().contains("expected string but found null")
r.expect('JSON.OBJLEN', 'test', '.int').raiseError().contains("expected object but found integer")
r.expect('JSON.STRLEN', 'test', '.num').raiseError().contains("expected string but found number")

# test a non existing key
r.expect('JSON.LEN', 'test', '.foo').raiseError()
r.expect('JSON.ARRLEN', 'test', '.foo').raiseError().contains("does not exist")

# test an out of bounds index
r.expect('JSON.LEN', 'test', '.arr[999]').raiseError()
r.expect('JSON.ARRLEN', 'test', '.arr[999]').raiseError().contains("does not exist")

# test an infinite index
r.expect('JSON.LEN', 'test', '.arr[-inf]').raiseError()
r.expect('JSON.ARRLEN', 'test', '.arr[-inf]').raiseError().contains("path error")
r.expect('JSON.ARRLEN', 'test', '.arr[4294967295]').raiseError().contains("does not exist")

def testObjKeysCommand(env):
"""Test JSON.OBJKEYS command"""
Expand Down
Loading