-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy pathcommands.rs
2023 lines (1837 loc) · 60.4 KB
/
commands.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Redis Ltd. 2016 - present
* Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or
* the Server Side Public License v1 (SSPLv1).
*/
use crate::error::Error;
use crate::formatter::RedisJsonFormatter;
use crate::jsonpath::select_value::{SelectValue, SelectValueType};
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::redisjson::{normalize_arr_indices, Format, Path};
use redis_module::{Context, RedisValue};
use redis_module::{NextArg, RedisError, RedisResult, RedisString, REDIS_OK};
use std::cmp::Ordering;
use std::str::FromStr;
use crate::jsonpath::{
calc_once, calc_once_paths, calc_once_with_paths, compile, json_path::JsonPathToken,
json_path::UserPathTracker,
};
use crate::redisjson::SetOptions;
use serde_json::{Number, Value};
use itertools::FoldWhile::{Continue, Done};
use itertools::{EitherOrBoth, Itertools};
use serde::{Serialize, Serializer};
use std::collections::HashMap;
const JSON_ROOT_PATH: &str = "$";
const JSON_ROOT_PATH_LEGACY: &str = ".";
const CMD_ARG_NOESCAPE: &str = "NOESCAPE";
const CMD_ARG_INDENT: &str = "INDENT";
const CMD_ARG_NEWLINE: &str = "NEWLINE";
const CMD_ARG_SPACE: &str = "SPACE";
const CMD_ARG_FORMAT: &str = "FORMAT";
// Compile time evaluation of the max len() of all elements of the array
const fn max_strlen(arr: &[&str]) -> usize {
let mut max_strlen = 0;
let arr_len = arr.len();
if arr_len < 1 {
return max_strlen;
}
let mut pos = 0;
while pos < arr_len {
let curr_strlen = arr[pos].len();
if max_strlen < curr_strlen {
max_strlen = curr_strlen;
}
pos += 1;
}
max_strlen
}
// We use this constant to further optimize json_get command, by calculating the max subcommand length
// Any subcommand added to JSON.GET should be included on the following array
const JSONGET_SUBCOMMANDS_MAXSTRLEN: usize = max_strlen(&[
CMD_ARG_NOESCAPE,
CMD_ARG_INDENT,
CMD_ARG_NEWLINE,
CMD_ARG_SPACE,
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,
}
impl<'a, V: SelectValue + 'a> KeyValue<'a, V> {
pub fn new(v: &'a V) -> KeyValue<'a, V> {
KeyValue { val: v }
}
fn get_first<'b>(&'a self, path: &'b str) -> Result<&'a V, Error> {
let results = self.get_values(path)?;
match results.first() {
Some(s) => Ok(s),
None => Err(err_msg_json_path_doesnt_exist_with_param(path)
.as_str()
.into()),
}
}
fn resp_serialize(&'a self, path: Path) -> RedisResult {
if path.is_legacy() {
let v = self.get_first(path.get_path())?;
Ok(Self::resp_serialize_inner(v))
} else {
Ok(self
.get_values(path.get_path())?
.iter()
.map(|v| Self::resp_serialize_inner(v))
.collect::<Vec<RedisValue>>()
.into())
}
}
fn resp_serialize_inner(v: &V) -> RedisValue {
match v.get_type() {
SelectValueType::Null => RedisValue::Null,
SelectValueType::Bool => {
let bool_val = v.get_bool();
match bool_val {
true => RedisValue::SimpleString("true".to_string()),
false => RedisValue::SimpleString("false".to_string()),
}
}
SelectValueType::Long => RedisValue::Integer(v.get_long()),
SelectValueType::Double => RedisValue::Float(v.get_double()),
SelectValueType::String => RedisValue::BulkString(v.get_str()),
SelectValueType::Array => {
let mut res: Vec<RedisValue> = Vec::with_capacity(v.len().unwrap() + 1);
res.push(RedisValue::SimpleStringStatic("["));
v.values()
.unwrap()
.for_each(|v| res.push(Self::resp_serialize_inner(v)));
RedisValue::Array(res)
}
SelectValueType::Object => {
let mut res: Vec<RedisValue> = Vec::with_capacity(v.len().unwrap() + 1);
res.push(RedisValue::SimpleStringStatic("{"));
for (k, v) in v.items().unwrap() {
res.push(RedisValue::BulkString(k.to_string()));
res.push(Self::resp_serialize_inner(v));
}
RedisValue::Array(res)
}
}
}
fn get_values<'b>(&'a self, path: &'b str) -> Result<Vec<&'a V>, Error> {
let query = compile(path)?;
let results = calc_once(query, self.val);
Ok(results)
}
pub fn serialize_object<O: Serialize>(
o: &O,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
) -> String {
let formatter = RedisJsonFormatter::new(indent, space, newline);
let mut out = serde_json::Serializer::with_formatter(Vec::new(), formatter);
o.serialize(&mut out).unwrap();
String::from_utf8(out.into_inner()).unwrap()
}
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> {
// 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 query = compile(path.get_path());
if query.is_err() {
return acc;
}
let query = query.unwrap();
let s = calc_once(query, self.val);
let value = if is_legacy && !s.is_empty() {
Some(Values::Single(s[0]))
} else if !is_legacy {
Some(Values::Multi(s))
} else {
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(err_msg_json_path_doesnt_exist_with_param(p.as_str()).into());
}
Ok(Self::serialize_object(&temp_doc, indent, newline, space).into())
}
fn to_json_single(
&'a self,
path: &str,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
is_legacy: bool,
) -> Result<RedisValue, Error> {
if is_legacy {
Ok(self.to_string_single(path, indent, newline, space)?.into())
} else {
Ok(self.to_string_multi(path, indent, newline, space)?.into())
}
}
fn to_json(
&'a self,
paths: &mut Vec<Path>,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
format: Format,
) -> Result<RedisValue, Error> {
if format == Format::BSON {
return Err("ERR Soon to come...".into());
}
let is_legacy = !paths.iter().any(|p| !p.is_legacy());
if paths.len() > 1 {
self.to_json_multi(paths, indent, newline, space, is_legacy)
} else {
self.to_json_single(paths[0].get_path(), indent, newline, space, is_legacy)
}
}
fn find_add_paths(&mut self, path: &str) -> Result<Vec<UpdateInfo>, Error> {
let mut query = compile(path)?;
if !query.is_static() {
return Err("Err wrong static path".into());
}
if query.size() < 1 {
return Err("Err path must end with object key to set".into());
}
let (last, token_type) = query.pop_last().unwrap();
match token_type {
JsonPathToken::String => {
if query.size() == 1 {
// Adding to the root
Ok(vec![UpdateInfo::AUI(AddUpdateInfo {
path: Vec::new(),
key: last,
})])
} else {
// Adding somewhere in existing object
let res = calc_once_paths(query, self.val);
Ok(res
.into_iter()
.map(|v| {
UpdateInfo::AUI(AddUpdateInfo {
path: v,
key: last.to_string(),
})
})
.collect())
}
}
JsonPathToken::Number => {
// if we reach here with array path we are either out of range
// or no-oping an NX where the value is already present
let query = compile(path)?;
let res = calc_once_paths(query, self.val);
if res.is_empty() {
Err("ERR array index out of range".into())
} else {
Ok(Vec::new())
}
}
}
}
pub fn find_paths(
&mut self,
path: &str,
option: &SetOptions,
) -> Result<Vec<UpdateInfo>, Error> {
if SetOptions::NotExists != *option {
let query = compile(path)?;
let res = calc_once_paths(query, self.val);
if !res.is_empty() {
return Ok(res
.into_iter()
.map(|v| UpdateInfo::SUI(SetUpdateInfo { path: v }))
.collect());
}
}
if SetOptions::AlreadyExists == *option {
Ok(Vec::new()) // empty vector means no updates
} else {
self.find_add_paths(path)
}
}
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("ERR Soon to come...".into()), //results.into() as Bson,
};
Ok(res)
}
pub fn to_string(&self, path: &str, format: Format) -> Result<String, Error> {
let results = self.get_first(path)?;
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,
indent: Option<&str>,
newline: Option<&str>,
space: Option<&str>,
) -> Result<String, Error> {
let results = self.get_values(path)?;
Ok(Self::serialize_object(&results, indent, newline, space))
}
pub fn get_type(&self, path: &str) -> Result<String, Error> {
let s = Self::value_name(self.get_first(path)?);
Ok(s.to_string())
}
pub fn value_name(value: &V) -> &str {
match value.get_type() {
SelectValueType::Null => "null",
SelectValueType::Bool => "boolean",
SelectValueType::Long => "integer",
// For dealing with u64 values over i64::MAX, get_type() replies
// that they are SelectValueType::Double to prevent panics from
// incorrect casts. However when querying the type of such a value,
// any response other than 'integer' is a breaking change
SelectValueType::Double => match value.is_double() {
Some(true) => "number",
Some(false) => "integer",
_ => unreachable!(),
},
SelectValueType::String => "string",
SelectValueType::Array => "array",
SelectValueType::Object => "object",
}
}
pub fn str_len(&self, path: &str) -> Result<usize, Error> {
let first = self.get_first(path)?;
match first.get_type() {
SelectValueType::String => Ok(first.get_str().len()),
_ => 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_msg_json_expected("array", 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),
}
}
pub fn is_equal<T1: SelectValue, T2: SelectValue>(a: &T1, b: &T2) -> bool {
match (a.get_type(), b.get_type()) {
(SelectValueType::Null, SelectValueType::Null) => true,
(SelectValueType::Bool, SelectValueType::Bool) => a.get_bool() == b.get_bool(),
(SelectValueType::Long, SelectValueType::Long) => a.get_long() == b.get_long(),
(SelectValueType::Double, SelectValueType::Double) => a.get_double() == b.get_double(),
(SelectValueType::String, SelectValueType::String) => a.get_str() == b.get_str(),
(SelectValueType::Array, SelectValueType::Array) => {
if a.len().unwrap() != b.len().unwrap() {
false
} else {
for (i, e) in a.values().unwrap().into_iter().enumerate() {
if !Self::is_equal(e, b.get_index(i).unwrap()) {
return false;
}
}
true
}
}
(SelectValueType::Object, SelectValueType::Object) => {
if a.len().unwrap() != b.len().unwrap() {
false
} else {
for k in a.keys().unwrap() {
let temp1 = a.get_key(k);
let temp2 = b.get_key(k);
match (temp1, temp2) {
(Some(a1), Some(b1)) => {
if !Self::is_equal(a1, b1) {
return false;
}
}
(_, _) => return false,
}
}
true
}
}
(_, _) => false,
}
}
pub fn arr_index(
&self,
path: &str,
json_value: Value,
start: i64,
end: i64,
) -> Result<RedisValue, Error> {
let res = self
.get_values(path)?
.iter()
.map(|value| {
self.arr_first_index_single(value, &json_value, start, end)
.into()
})
.collect::<Vec<RedisValue>>();
Ok(res.into())
}
pub fn arr_index_legacy(
&self,
path: &str,
json_value: Value,
start: i64,
end: i64,
) -> Result<RedisValue, Error> {
let arr = self.get_first(path)?;
match self.arr_first_index_single(arr, &json_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
fn arr_first_index_single(&self, arr: &V, v: &Value, start: i64, end: i64) -> FoundIndex {
if !arr.is_array() {
return FoundIndex::NotArray;
}
let len = arr.len().unwrap() as i64;
if len == 0 {
return FoundIndex::NotFound;
}
// end=0 means INFINITY to support backward with RedisJSON
let (start, end) = normalize_arr_indices(start, end, len);
if end < start {
// don't search at all
return FoundIndex::NotFound;
}
for index in start..end {
if Self::is_equal(arr.get_index(index as usize).unwrap(), v) {
return FoundIndex::Index(index);
}
}
FoundIndex::NotFound
}
pub fn obj_keys(&self, path: &str) -> Result<Box<dyn Iterator<Item = &'_ str> + '_>, Error> {
self.get_first(path)?.keys().ok_or_else(|| {
err_msg_json_expected("object", self.get_type(path).unwrap().as_str())
.as_str()
.into()
})
}
}
///
/// JSON.GET <key>
/// [INDENT indentation-string]
/// [NEWLINE line-break-string]
/// [SPACE space-string]
/// [path ...]
///
/// TODO add support for multi path
pub fn json_get<M: Manager>(manager: M, ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key = args.next_arg()?;
// Set Capcity to 1 assumiung the common case has one path
let mut paths: Vec<Path> = Vec::with_capacity(1);
let mut format = Format::JSON;
let mut indent = None;
let mut space = None;
let mut newline = None;
while let Ok(arg) = args.next_str() {
match arg {
// fast way to consider arg a path by using the max length of all possible subcommands
// See #390 for the comparison of this function with/without this optimization
arg if arg.len() > JSONGET_SUBCOMMANDS_MAXSTRLEN => paths.push(Path::new(arg)),
arg if arg.eq_ignore_ascii_case(CMD_ARG_INDENT) => indent = Some(args.next_str()?),
arg if arg.eq_ignore_ascii_case(CMD_ARG_NEWLINE) => newline = Some(args.next_str()?),
arg if arg.eq_ignore_ascii_case(CMD_ARG_SPACE) => space = Some(args.next_str()?),
// Silently ignore. Compatibility with ReJSON v1.0 which has this option. See #168 TODO add support
arg if arg.eq_ignore_ascii_case(CMD_ARG_NOESCAPE) => continue,
arg if arg.eq_ignore_ascii_case(CMD_ARG_FORMAT) => {
format = Format::from_str(args.next_str()?)?;
}
_ => paths.push(Path::new(arg)),
};
}
// path is optional -> no path found we use root "$"
if paths.is_empty() {
paths.push(Path::new(JSON_ROOT_PATH_LEGACY));
}
let key = manager.open_key_read(ctx, &key)?;
let value = match key.get_value()? {
Some(doc) => KeyValue::new(doc).to_json(&mut paths, indent, newline, space, format)?,
None => RedisValue::Null,
};
Ok(value)
}
///
/// JSON.SET <key> <path> <json> [NX | XX | FORMAT <format>]
///
pub fn json_set<M: Manager>(manager: M, ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key = args.next_arg()?;
let path = Path::new(args.next_str()?);
let value = args.next_str()?;
let mut format = Format::JSON;
let mut set_option = SetOptions::None;
while let Some(s) = args.next() {
match s.try_as_str()? {
arg if arg.eq_ignore_ascii_case("NX") && set_option == SetOptions::None => {
set_option = SetOptions::NotExists
}
arg if arg.eq_ignore_ascii_case("XX") && set_option == SetOptions::None => {
set_option = SetOptions::AlreadyExists
}
arg if arg.eq_ignore_ascii_case("FORMAT") => {
format = Format::from_str(args.next_str()?)?;
}
_ => return Err(RedisError::Str("ERR syntax error")),
};
}
let mut redis_key = manager.open_key_write(ctx, key)?;
let current = redis_key.get_value()?;
let val = manager.from_str(value, format, true)?;
match (current, set_option) {
(Some(ref mut doc), ref op) => {
if path.get_path() == JSON_ROOT_PATH {
if *op != SetOptions::NotExists {
redis_key.set_value(Vec::new(), val)?;
redis_key.apply_changes(ctx, "json.set")?;
REDIS_OK
} else {
Ok(RedisValue::Null)
}
} else {
let mut update_info = KeyValue::new(*doc).find_paths(path.get_path(), op)?;
if !update_info.is_empty() {
let mut res = false;
if update_info.len() == 1 {
res = match update_info.pop().unwrap() {
UpdateInfo::SUI(sui) => redis_key.set_value(sui.path, val)?,
UpdateInfo::AUI(aui) => redis_key.dict_add(aui.path, &aui.key, val)?,
}
} else {
for ui in update_info {
res = match ui {
UpdateInfo::SUI(sui) => {
redis_key.set_value(sui.path, val.clone())?
}
UpdateInfo::AUI(aui) => {
redis_key.dict_add(aui.path, &aui.key, val.clone())?
}
}
}
}
if res {
redis_key.apply_changes(ctx, "json.set")?;
REDIS_OK
} else {
Ok(RedisValue::Null)
}
} else {
Ok(RedisValue::Null)
}
}
}
(None, SetOptions::AlreadyExists) => Ok(RedisValue::Null),
(None, _) => {
if path.get_path() == JSON_ROOT_PATH {
redis_key.set_value(Vec::new(), val)?;
redis_key.apply_changes(ctx, "json.set")?;
REDIS_OK
} else {
Err(RedisError::Str(
"ERR new objects must be created at the root",
))
}
}
}
}
fn find_paths<T: SelectValue, F: FnMut(&T) -> bool>(
path: &str,
doc: &T,
mut f: F,
) -> Result<Vec<Vec<String>>, RedisError> {
let query = match compile(path) {
Ok(q) => q,
Err(e) => return Err(RedisError::String(e.to_string())),
};
let res = calc_once_with_paths(query, doc);
Ok(res
.into_iter()
.filter(|e| f(e.res))
.map(|e| e.path_tracker.unwrap().to_string_path())
.collect())
}
/// Returns tuples of Value and its concrete path which match the given `path`
fn get_all_values_and_paths<'a, T: SelectValue>(
path: &str,
doc: &'a T,
) -> Result<Vec<(&'a T, Vec<String>)>, RedisError> {
let query = match compile(path) {
Ok(q) => q,
Err(e) => return Err(RedisError::String(e.to_string())),
};
let res = calc_once_with_paths(query, doc);
Ok(res
.into_iter()
.map(|e| (e.res, e.path_tracker.unwrap().to_string_path()))
.collect())
}
/// Returns a Vec of paths with `None` for Values that do not match the filter
fn filter_paths<T, F>(values_and_paths: Vec<(&T, Vec<String>)>, f: F) -> Vec<Option<Vec<String>>>
where
F: Fn(&T) -> bool,
{
values_and_paths
.into_iter()
.map(|(v, p)| match f(v) {
true => Some(p),
_ => None,
})
.collect::<Vec<Option<Vec<String>>>>()
}
/// Returns a Vec of Values with `None` for Values that do not match the filter
fn filter_values<T, F>(values_and_paths: Vec<(&T, Vec<String>)>, f: F) -> Vec<Option<&T>>
where
F: Fn(&T) -> bool,
{
values_and_paths
.into_iter()
.map(|(v, _)| match f(v) {
true => Some(v),
_ => None,
})
.collect::<Vec<Option<&T>>>()
}
fn find_all_paths<T: SelectValue, F: FnMut(&T) -> bool>(
path: &str,
doc: &T,
f: F,
) -> Result<Vec<Option<Vec<String>>>, RedisError>
where
F: Fn(&T) -> bool,
{
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_paths(res, f)),
_ => Ok(vec![]),
}
}
fn find_all_values<'a, T: SelectValue, F: FnMut(&T) -> bool>(
path: &str,
doc: &'a T,
f: F,
) -> Result<Vec<Option<&'a T>>, RedisError>
where
F: Fn(&T) -> bool,
{
let res = get_all_values_and_paths(path, doc)?;
match res.is_empty() {
false => Ok(filter_values(res, f)),
_ => Ok(vec![]),
}
}
fn to_json_value<T>(values: Vec<Option<T>>, none_value: Value) -> Vec<Value>
where
Value: From<T>,
{
values
.into_iter()
.map(|n| n.map_or_else(|| none_value.clone(), |t| t.into()))
.collect::<Vec<Value>>()
}
/// Sort the paths so higher indices precede lower indices on the same array,
/// And longer paths precede shorter paths
/// And if a path is a sub-path of the other, then only paths with shallower hierarchy (closer to the top-level) remain
fn prepare_paths_for_deletion(paths: &mut Vec<Vec<String>>) {
if paths.len() < 2 {
// No need to reorder when there are less than 2 paths
return;
}
paths.sort_by(|v1, v2| {
v1.iter()
.zip_longest(v2.iter())
.fold_while(Ordering::Equal, |_acc, v| {
match v {
EitherOrBoth::Left(_) => Done(Ordering::Less), // Shorter paths after longer paths
EitherOrBoth::Right(_) => Done(Ordering::Greater), // Shorter paths after longer paths
EitherOrBoth::Both(p1, p2) => {
let i1 = p1.parse::<usize>();
let i2 = p2.parse::<usize>();
match (i1, i2) {
(Err(_), Err(_)) => match p1.cmp(p2) {
// String compare
Ordering::Less => Done(Ordering::Less),
Ordering::Equal => Continue(Ordering::Equal),
Ordering::Greater => Done(Ordering::Greater),
},
(Ok(_), Err(_)) => Done(Ordering::Greater), //String before Numeric
(Err(_), Ok(_)) => Done(Ordering::Less), //String before Numeric
(Ok(i1), Ok(i2)) => {
// Numeric compare - higher indices before lower ones
match i2.cmp(&i1) {
Ordering::Greater => Done(Ordering::Greater),
Ordering::Less => Done(Ordering::Less),
Ordering::Equal => Continue(Ordering::Equal),
}
}
}
}
}
})
.into_inner()
});
// Remove paths which are nested by others (on each sub-tree only top most ancestor should be deleted)
// (TODO: Add a mode in which the jsonpath selector will already skip nested paths)
let mut string_paths = Vec::new();
paths.iter().for_each(|v| {
string_paths.push(v.join(","));
});
string_paths.sort();
paths.retain(|v| {
let path = v.join(",");
let found = string_paths.binary_search(&path).unwrap();
for p in string_paths.iter().take(found) {
if path.starts_with(p.as_str()) {
return false;
}
}
true
});
}
///
/// JSON.DEL <key> [path]
///
pub fn json_del<M: Manager>(manager: M, ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key = args.next_arg()?;
let path = match args.next() {
None => Path::new(JSON_ROOT_PATH_LEGACY),
Some(s) => Path::new(s.try_as_str()?),
};
let mut redis_key = manager.open_key_write(ctx, key)?;
let deleted = match redis_key.get_value()? {
Some(doc) => {
let res = if path.get_path() == JSON_ROOT_PATH {
redis_key.delete()?;
1
} else {
let mut paths = find_paths(path.get_path(), doc, |_| true)?;
prepare_paths_for_deletion(&mut paths);
let mut changed = 0;
for p in paths {
if redis_key.delete_path(p)? {
changed += 1;
}
}
changed
};
if res > 0 {
redis_key.apply_changes(ctx, "json.del")?;
}
res
}
None => 0,
};
Ok((deleted as i64).into())
}
///
/// JSON.MGET <key> [key ...] <path>
///
pub fn json_mget<M: Manager>(manager: M, ctx: &Context, args: Vec<RedisString>) -> RedisResult {
if args.len() < 3 {
return Err(RedisError::WrongArity);
}
args.last().ok_or(RedisError::WrongArity).and_then(|path| {
let path = Path::new(path.try_as_str()?);
let keys = &args[1..args.len() - 1];
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_single(path.get_path(), None, None, None);
let is_legacy = path.is_legacy();
let results: Result<Vec<RedisValue>, RedisError> = keys
.iter()
.map(|key| {
manager
.open_key_read(ctx, key)
.map_or(Ok(RedisValue::Null), |json_key| {
json_key.get_value().map_or(Ok(RedisValue::Null), |value| {
value
.map(|doc| {
if !is_legacy {
to_string(doc)
} else {
to_string_legacy(doc)
}
})
.transpose()
.map_or(Ok(RedisValue::Null), |v| Ok(v.into()))
})
})
})
.collect();
Ok(results?.into())
})
}
///
/// JSON.TYPE <key> [path]
///
pub fn json_type<M: Manager>(manager: M, ctx: &Context, args: Vec<RedisString>) -> RedisResult {
let mut args = args.into_iter().skip(1);
let key = args.next_arg()?;
let path = Path::new(args.next_str().unwrap_or(JSON_ROOT_PATH_LEGACY));
let key = manager.open_key_read(ctx, &key)?;
if path.is_legacy() {
json_type_legacy::<M>(&key, path.get_path())
} else {
json_type_impl::<M>(&key, path.get_path())
}
}
fn json_type_impl<M>(redis_key: &M::ReadHolder, path: &str) -> RedisResult
where
M: Manager,
{
let root = redis_key.get_value()?;
let res = match root {
Some(root) => KeyValue::new(root)
.get_values(path)?
.iter()
.map(|v| (KeyValue::value_name(*v)).into())
.collect::<Vec<RedisValue>>()
.into(),
None => RedisValue::Null,
};
Ok(res)
}
fn json_type_legacy<M>(redis_key: &M::ReadHolder, path: &str) -> RedisResult
where
M: Manager,
{
let value = redis_key.get_value()?.map_or_else(
|| RedisValue::Null,
|doc| {
KeyValue::new(doc)
.get_type(path)
.map_or(RedisValue::Null, |s| s.into())
},
);
Ok(value)
}
enum NumOp {
Incr,
Mult,
Pow,
}
fn json_num_op<M>(
manager: M,
ctx: &Context,
args: Vec<RedisString>,
cmd: &str,
op: NumOp,
) -> RedisResult
where
M: Manager,
{
let mut args = args.into_iter().skip(1);
let key = args.next_arg()?;
let path = Path::new(args.next_str()?);
let number = args.next_str()?;
let mut redis_key = manager.open_key_write(ctx, key)?;
if path.is_legacy() {
json_num_op_legacy::<M>(&mut redis_key, ctx, path.get_path(), number, op, cmd)
} else {
json_num_op_impl::<M>(&mut redis_key, ctx, path.get_path(), number, op, cmd)
}
}