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
42 changes: 37 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::array_index::ArrayIndex;
use crate::error::Error;
use crate::redisjson::{Format, Path, RedisJSON, SetOptions};

const JSON_ROOT_PATH: &'static str = "$";
pub const REDIS_JSON_TYPE_VERSION: i32 = 3;

static REDIS_JSON_TYPE: RedisType = RedisType::new(
Expand Down Expand Up @@ -71,7 +72,9 @@ fn json_del(ctx: &Context, args: Vec<String>) -> RedisResult {
let mut args = args.into_iter().skip(1);

let key = args.next_string()?;
let path = backwards_compat_path(args.next_string()?);
let path = args
.next_string()
.map_or_else(|_| JSON_ROOT_PATH.to_string(), |v| backwards_compat_path(v));

let redis_key = ctx.open_key_writable(&key);
let deleted = match redis_key.get_value::<RedisJSON>(&REDIS_JSON_TYPE)? {
Expand Down Expand Up @@ -188,7 +191,7 @@ fn json_get(ctx: &Context, args: Vec<String>) -> RedisResult {

// path is optional -> no path found we use root "$"
if paths.is_empty() {
paths.push(Path::new("$".to_string()));
paths.push(Path::new(JSON_ROOT_PATH.to_string()));
}

let key = ctx.open_key_writable(&key);
Expand Down Expand Up @@ -409,7 +412,7 @@ fn json_str_append(ctx: &Context, args: Vec<String>) -> RedisResult {
path = backwards_compat_path(path_or_json);
json = val;
} else {
path = "$".to_string();
path = JSON_ROOT_PATH.to_string();
json = path_or_json;
}

Expand Down Expand Up @@ -606,7 +609,7 @@ fn json_arr_pop(ctx: &Context, args: Vec<String>) -> RedisResult {
let index = args.next_i64().unwrap_or(i64::MAX);
(path, index)
})
.unwrap_or(("$".to_string(), i64::MAX));
.unwrap_or((JSON_ROOT_PATH.to_string(), i64::MAX));

let redis_key = ctx.open_key_writable(&key);
let mut res = Value::Null;
Expand Down Expand Up @@ -731,6 +734,32 @@ fn json_obj_len(ctx: &Context, args: Vec<String>) -> RedisResult {
json_len(ctx, args, |doc, path| doc.obj_len(path))
}

///
/// JSON.CLEAR <key> [path ...]
///
fn json_clear(ctx: &Context, args: Vec<String>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key = args.next_string()?;
let paths = args.map(Path::new).collect::<Vec<_>>();

let paths = if paths.is_empty() {
vec![Path::new(JSON_ROOT_PATH.to_string())]
} else {
paths
};

// FIXME: handle multi paths
let key = ctx.open_key_writable(&key);
let deleted = match key.get_value::<RedisJSON>(&REDIS_JSON_TYPE)? {
Some(doc) => {
let res = doc.clear(paths.first().unwrap().fixed.as_str())?;
ctx.replicate_verbatim();
res
}
None => 0,
};
Ok(deleted.into())
}
///
/// JSON.DEBUG <subcommand & arguments>
///
Expand Down Expand Up @@ -772,7 +801,9 @@ fn json_resp(ctx: &Context, args: Vec<String>) -> RedisResult {
let mut args = args.into_iter().skip(1);

let key = args.next_string()?;
let path = backwards_compat_path(args.next_string()?);
let path = args
.next_string()
.map_or_else(|_| JSON_ROOT_PATH.to_string(), |v| backwards_compat_path(v));

let key = ctx.open_key(&key);
match key.get_value::<RedisJSON>(&REDIS_JSON_TYPE)? {
Expand Down Expand Up @@ -866,6 +897,7 @@ redis_module! {
["json.arrtrim", json_arr_trim, "write", 1,1,1],
["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.forget", json_del, "write", 1,1,1],
["json.resp", json_resp, "readonly", 1,1,1],
Expand Down
25 changes: 25 additions & 0 deletions src/redisjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,31 @@ impl RedisJSON {
Ok(deleted)
}

pub fn clear(&mut self, path: &str) -> Result<usize, Error> {
let current_data = self.data.take();
let mut cleared = 0;

let clear_func = &mut |v| match v {
Value::Object(mut obj) => {
obj.clear();
cleared += 1;
Some(Value::from(obj))
}
Value::Array(mut arr) => {
arr.clear();
cleared += 1;
Some(Value::from(arr))
}
_ => Some(v),
};

self.data = if path == "$" {
clear_func(current_data).unwrap()
} else {
jsonpath_lib::replace_with(current_data, path, clear_func)?
};
Ok(cleared)
}
pub fn to_string(&self, path: &str, format: Format) -> Result<String, Error> {
let results = self.get_first(path)?;
Self::serialize(results, format)
Expand Down
48 changes: 48 additions & 0 deletions tests/pytest/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,54 @@ def testObjectCRUD(env):
r.assertEqual(1, r.execute_command('JSON.DEL', 'test', '.'))
r.assertIsNone(r.execute_command('JSON.GET', 'test', '.'))

# Test deleting with default (root) path
r.assertOk(r.execute_command('JSON.SET', 'test', '.', '{"foo": "bar"}'))
r.assertEqual(1, r.execute_command('JSON.DEL', 'test'))
r.assertIsNone(r.execute_command('JSON.GET', 'test', '.'))

def testClear(env):
"""Test JSON.CLEAR command"""

r = env
r.expect('JSON.SET', 'test', '.', r'{"n":42,"s":"42","arr":[{"n":44},"s",{"n":{"a":1,"b":2}},{"n2":{"x":3.02,"n":["to","be","cleared",4],"y":4.91}}]}')\
.ok()

# Test get multi results (using .. recursive descent)
# TODO: Enable when supporting multi results (and not only the first)
#r.expect('JSON.GET', 'test', '$..n').equal([42,44,{"a": 1,"b": 2},["to","be","cleared",4]])

# Make sure specific obj content exists before clear
obj_content = r'{"a":1,"b":2}'
r.expect('JSON.GET', 'test', '$.arr[2].n').equal(obj_content)
# Make sure specific arr content exists before clear
arr_content = r'["to","be","cleared",4]'
r.expect('JSON.GET', 'test', '$.arr[3].n2.n').equal(arr_content)

# Clear obj and arr with specific paths
r.expect('JSON.CLEAR', 'test', '$.arr[2].n').equal(1)
r.expect('JSON.CLEAR', 'test', '$.arr[3].n2.n').equal(1)

# Fail clear on inappropriate path (not obj or arr)
r.expect('JSON.CLEAR', 'test', '$.arr[1]').equal(0)

# Make sure specific obj content was cleared
r.expect('JSON.GET', 'test', '$.arr[2].n').equal('{}')
# Make sure specific arr content was cleared
r.expect('JSON.GET', 'test', '$.arr[3].n2.n').equal('[]')

# Make sure only appropriate content (obj and arr) was cleared - and that errors were printed for inappropriate content (string and numeric)
# TODO: Enable when supporting multi results (and not only the first)
#r.expect('JSON.GET', 'test', '$..n').equal([42, 44, {}, []])

# Clear root
# TODO: switch order of the following paths and expect .equals(2) when supporting multi-paths
r.expect('JSON.CLEAR', 'test', '$', '$.arr[2].n').equal(1)
r.expect('JSON.GET', 'test', '$').equal('{}')

r.expect('JSON.SET', 'test', '$', obj_content).ok()
r.expect('JSON.CLEAR', 'test').equal(1)
r.expect('JSON.GET', 'test', '$').equal('{}')

def testArrayCRUD(env):
"""Test JSON Array CRUDness"""

Expand Down