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
135 changes: 71 additions & 64 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
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::{AddUpdateInfo, Manager, ReadHolder, SetUpdateInfo, UpdateInfo, WriteHolder};
use crate::nodevisitor::{StaticPathElement, StaticPathParser, VisitStatus};
use crate::redisjson::{normalize_arr_indices, Format, Path};
use jsonpath_lib::select::select_value::{SelectValue, SelectValueType};
use jsonpath_lib::select::Selector;
use redis_module::{Context, RedisValue};
use redis_module::{NextArg, RedisError, RedisResult, RedisString, REDIS_OK};
use std::cmp::Ordering;

use jsonpath_lib::select::Selector;

use crate::nodevisitor::{StaticPathElement, StaticPathParser, VisitStatus};

use crate::error::Error;

use crate::redisjson::SetOptions;

use serde_json::{Number, Value};
Expand Down Expand Up @@ -87,7 +86,9 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
let results = self.get_values(path)?;
match results.first() {
Some(s) => Ok(s),
None => Err("ERR path does not exist".into()),
None => Err(err_msg_json_path_doesnt_exist_with_param(path)
.as_str()
.into()),
}
}

Expand All @@ -104,10 +105,9 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
.collect::<Vec<RedisValue>>()
.into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist",
path.get_path()
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path.get_original()),
))
}
}
}
Expand Down Expand Up @@ -204,7 +204,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
acc
});
if let Some(p) = missing_path {
return Err(format!("ERR path {} does not exist", p).into());
return Err(err_msg_json_path_doesnt_exist_with_param(p.as_str()).into());
}
Ok(Self::serialize_object(&temp_doc, indent, newline, space).into())
}
Expand Down Expand Up @@ -233,7 +233,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
format: Format,
) -> Result<RedisValue, Error> {
if format == Format::BSON {
return Err("Soon to come...".into());
return Err("ERR Soon to come...".into());
}
let is_legacy = !paths.iter().any(|p| !p.is_legacy());
if paths.len() > 1 {
Expand Down Expand Up @@ -291,9 +291,9 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
// if we reach here with array path we must be out of range
// otherwise the path would be valid to be set and we would not
// have reached here!!
Err("array index out of range".into())
Err("ERR array index out of range".into())
} else {
Err("path not an object or array".into())
Err("ERR path not an object or array".into())
}
}

Expand Down Expand Up @@ -325,7 +325,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
pub fn serialize(results: &V, format: Format) -> Result<String, Error> {
let res = match format {
Format::JSON => serde_json::to_string(results)?,
Format::BSON => return Err("Soon to come...".into()), //results.into() as Bson,
Format::BSON => return Err("ERR Soon to come...".into()), //results.into() as Bson,
};
Ok(res)
}
Expand Down Expand Up @@ -378,23 +378,35 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
let first = self.get_first(path)?;
match first.get_type() {
SelectValueType::String => Ok(first.get_str().len()),
_ => Err("ERR wrong type of path value".into()),
_ => Err(
err_msg_json_expected("string", self.get_type(path).unwrap().as_str())
.as_str()
.into(),
),
}
}

pub fn arr_len(&self, path: &str) -> Result<usize, Error> {
let first = self.get_first(path)?;
match first.get_type() {
SelectValueType::Array => Ok(first.len().unwrap()),
_ => Err("ERR wrong type of path value".into()),
_ => Err(
err_msg_json_expected("array", self.get_type(path).unwrap().as_str())
.as_str()
.into(),
),
}
}

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 wrong type of path value".into()),
_ => Err(
err_msg_json_expected("object", self.get_type(path).unwrap().as_str())
.as_str()
.into(),
),
}
}

Expand Down Expand Up @@ -502,9 +514,11 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
}

pub fn obj_keys(&self, path: &str) -> Result<Box<dyn Iterator<Item = &'_ str> + '_>, Error> {
self.get_first(path)?
.keys()
.ok_or_else(|| "ERR wrong type of path value".into())
self.get_first(path)?.keys().ok_or_else(|| {
err_msg_json_expected("object", self.get_type(path).unwrap().as_str())
.as_str()
.into()
})
}
}

Expand Down Expand Up @@ -708,10 +722,9 @@ where
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_paths(res, f)),
_ => Err(RedisError::String(format!(
"Path '{}' does not exist",
path
))),
_ => Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path),
)),
}
}

Expand All @@ -726,10 +739,9 @@ where
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_values(res, f)),
_ => Err(RedisError::String(format!(
"Path '{}' does not exist",
path
))),
_ => Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param(path),
)),
}
}

Expand Down Expand Up @@ -1016,10 +1028,9 @@ where
redis_key.apply_changes(ctx, cmd)?;
Ok(res.unwrap().to_string().into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or does not contains a number",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "does not contains a number"),
))
}
}

Expand Down Expand Up @@ -1109,10 +1120,9 @@ where
redis_key.apply_changes(ctx, "json.toggle")?;
Ok(res.to_string().into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or not a bool",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not a bool"),
))
}
}

Expand Down Expand Up @@ -1201,10 +1211,9 @@ where
redis_key.apply_changes(ctx, "json.strappend")?;
Ok(res.unwrap().into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or not a string",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not a string"),
))
}
}

Expand Down Expand Up @@ -1281,14 +1290,14 @@ pub fn command_json_arr_append<M: Manager>(
if !path.is_legacy() {
json_arr_append::<M>(&mut redis_key, ctx, path.get_path(), args)
} else {
json_arr_append_legacy::<M>(&mut redis_key, ctx, path.get_path(), args)
json_arr_append_legacy::<M>(&mut redis_key, ctx, &path, args)
}
}

fn json_arr_append_legacy<M>(
redis_key: &mut M::WriteHolder,
ctx: &Context,
path: &str,
path: &Path,
args: Vec<M::O>,
) -> RedisResult
where
Expand All @@ -1297,12 +1306,13 @@ where
let root = redis_key
.get_value()?
.ok_or_else(RedisError::nonexistent_key)?;
let mut paths = find_paths(path, root, |v| v.get_type() == SelectValueType::Array)?;
let mut paths = find_paths(path.get_path(), root, |v| {
v.get_type() == SelectValueType::Array
})?;
if paths.is_empty() {
Err(RedisError::String(format!(
"Path '{}' does not exist",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path.get_original(), "not an array"),
))
} else if paths.len() == 1 {
let res = redis_key.arr_append(paths.pop().unwrap(), args)?;
redis_key.apply_changes(ctx, "json.arrappend")?;
Expand Down Expand Up @@ -1384,9 +1394,9 @@ pub fn command_json_arr_index<M: Manager>(
let is_legacy = path.is_legacy();
let scalar_value: Value = serde_json::from_str(json_scalar)?;
if !is_legacy && (scalar_value.is_array() || scalar_value.is_object()) {
return Err(RedisError::String(format!(
"ERR expected scalar but found {}",
json_scalar
return Err(RedisError::String(err_msg_json_expected(
"scalar",
json_scalar,
)));
}

Expand Down Expand Up @@ -1489,10 +1499,9 @@ where
redis_key.apply_changes(ctx, "json.arrinsert")?;
Ok(res.unwrap().into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or not an array",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not an array"),
))
}
}

Expand Down Expand Up @@ -1624,10 +1633,9 @@ where
None => Ok(().into()),
}
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or not an array",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not an array"),
))
}
}

Expand Down Expand Up @@ -1706,10 +1714,9 @@ where
redis_key.apply_changes(ctx, "json.arrtrim")?;
Ok(res.unwrap().into())
} else {
Err(RedisError::String(format!(
"Path '{}' does not exist or not an array",
path
)))
Err(RedisError::String(
err_msg_json_path_doesnt_exist_with_param_or(path, "not an array"),
))
}
}

Expand Down
42 changes: 30 additions & 12 deletions src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,31 @@ pub trait Manager {
}

fn err_json(value: &Value, expected_value: &'static str) -> Error {
Error::from(format!(
"ERR wrong type of path value - expected {} but found {}",
Error::from(err_msg_json_expected(
expected_value,
RedisJSON::value_name(value)
RedisJSON::value_name(value),
))
}

pub(crate) fn err_msg_json_expected<'a>(expected_value: &'static str, found: &str) -> String {
format!(
"WRONGTYPE wrong type of path value - expected {} but found {}",
expected_value, found
)
}

pub(crate) fn err_msg_json_path_doesnt_exist_with_param(path: &str) -> String {
format!("ERR Path '{}' does not exist", path)
}

pub(crate) fn err_msg_json_path_doesnt_exist() -> String {
"ERR Path does not exist".to_string()
}

pub(crate) fn err_msg_json_path_doesnt_exist_with_param_or(path: &str, or: &str) -> String {
format!("ERR Path '{}' does not exist or {}", path, or)
}

pub struct KeyHolderWrite<'a> {
key: RedisKeyWritable,
key_name: RedisString,
Expand Down Expand Up @@ -203,7 +221,7 @@ impl<'a> KeyHolderWrite<'a> {
Ok(res.clone())
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(n) => match n {
Value::Number(n) => Ok(n),
_ => Err(RedisError::Str("return value is not a number")),
Expand Down Expand Up @@ -341,7 +359,7 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
Ok(Some(Value::Bool(val)))
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(n) => Ok(n),
}
}
Expand All @@ -356,13 +374,13 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
Ok(Some(Value::String(new_str)))
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(l) => Ok(l),
}
} else {
Err(RedisError::String(format!(
"ERR wrong type of value - expected string but found {}",
val
Err(RedisError::String(err_msg_json_expected(
"string",
val.as_str(),
)))
}
}
Expand All @@ -376,7 +394,7 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
Ok(Some(v))
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(n) => Ok(n),
}
}
Expand All @@ -403,7 +421,7 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
Ok(Some(new_value))
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(l) => Ok(l),
}
}
Expand Down Expand Up @@ -461,7 +479,7 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
}
})?;
match res {
None => Err(RedisError::Str("path does not exists")),
None => Err(RedisError::String(err_msg_json_path_doesnt_exist())),
Some(l) => Ok(l),
}
}
Expand Down
Loading