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
133 changes: 86 additions & 47 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::error::Error;
use crate::formatter::RedisJsonFormatter;
use crate::manager::err_msg_json_path_doesnt_exist_with_param;
use crate::manager::{err_msg_json_expected, err_msg_json_path_doesnt_exist_with_param_or};
use crate::manager::{err_msg_json_path_doesnt_exist, err_msg_json_path_doesnt_exist_with_param};
use crate::manager::{AddUpdateInfo, Manager, ReadHolder, SetUpdateInfo, UpdateInfo, WriteHolder};
use crate::nodevisitor::{StaticPathElement, StaticPathParser, VisitStatus};
use crate::redisjson::{normalize_arr_indices, Format, Path};
Expand Down Expand Up @@ -398,15 +398,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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't it make more sense that this is an error?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, in new behavior it is an error (see json_obj_len). This is to maintain legacy behavior.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So why add it as part of the valid return value and not as error?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for backward compatibility with V 1.0 (only with legacy path)
JSON.OBJKEYS doc1 .nowhere and JSON.OBJKEYS no_such_doc . should return null (as before)

}
}

Expand Down Expand Up @@ -467,7 +469,11 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
.into()
})
.collect::<Vec<RedisValue>>();
Ok(res.into())
if res.is_empty() {
Err(Error::from(err_msg_json_path_doesnt_exist()))
} else {
Ok(res.into())
}
}

pub fn arr_index_legacy(
Expand All @@ -478,12 +484,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 @@ -1377,6 +1384,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 +1416,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,9 +1545,6 @@ 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
})?;
Expand All @@ -1538,7 +1553,18 @@ pub fn command_json_arr_len<M: Manager>(
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 +1770,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 = {
Comment thread
MeirShpilraien marked this conversation as resolved.
Resolved
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 +1791,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 +1840,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 +1854,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
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